edited_code
stringlengths
17
978k
original_code
stringlengths
17
978k
#!/opt/anaconda3/bin/python from bs4 import BeautifulSoup import requests import ftfy import glob import argparse import os import jsonlines def main(args): # Create the new file. Overwrite if it exits f = open(args.output_file, "w+") f.close() # Get a list of documents in the folder filelist = glob.glob(args.input_folder+'*.xhtml') n = 0 with jsonlines.open(args.output_file, 'w') as writer: for f in filelist: html_content = open(f, "r") basename = os.path.basename(f).replace(".xhtml", "") # Parse the html content soup = BeautifulSoup(html_content, "lxml") written = 0 myarticle = {} myarticle['doc_type'] = args.doc_type myarticle['id'] = args.doc_type+"_"+basename myarticle['language_reported'] = args.language_reported pid = 0 paragraphs = [] for p in soup.find_all("p"): text = p.text.strip() text = ftfy.fix_text(text) if len(text): if text[-1] != '.' and text[-1] != ":": ... # print(f'Heading or bulleted list: {text}') else: if p.parent: thisclasses = p.get('class') parentclasses = p.parent.get('class') if not parentclasses: parentclasses = [] if not thisclasses: thisclasses = [] if 'K-REFLISTE' in thisclasses: ... # Uncomment to debug # print(f"Removed {p.get("class")} - {text}\n") elif 'TOP' in parentclasses: ... # Uncomment to debug. #print(f"Removed {p.parent.get("class")} - {text}\n") elif 'K-NOTE-TBLNOTER' in parentclasses: ... # Uncomment to debug #print(f"Removed {p.parent.get("class")} - {text}\n") elif 'K-NOTETEXT' in parentclasses: ... # Uncomment to debug #print(f"Removed {p.parent.get("class")} - {text}\n") else: if len(text.split()) >= 10 and not text.startswith("Det har oppstått en teknisk feil.") and not text.startswith("A technical error has occurred. You can try to locate relevant documents"): paragraphs.append({ 'paragraph_id': len(paragraphs), 'text': text.rstrip("\n") }) myarticle['paragraphs'] = paragraphs writer.write(myarticle) n += 1 print(f'{n} documents from {len(filelist)} files are written to {args.output_file}') def parse_args(): # Parse commandline parser = argparse.ArgumentParser( description="Process the corpus downloaded from the governments API. The corpus consists of multiple files in xhtml format. Output is an UTF-8 json-lines-file with one document per line") parser.add_argument('--language_reported', required=False, default="N/A", type=str, help='Language reported. Can be nob, nno, no or N/A') parser.add_argument('--doc_type', required=True, type=str, help='For instance government') parser.add_argument('--output_file', required=True, help='Output file name. Will overwrite it exists') parser.add_argument('--input_folder', required=True, help='Input folder. Will read all files in folder') args = parser.parse_args() return args if __name__ == "__main__": args = parse_args() main(args)
#!/opt/anaconda3/bin/python from bs4 import BeautifulSoup import requests import ftfy import glob import argparse import os import jsonlines def main(args): # Create the new file. Overwrite if it exits f = open(args.output_file, "w+") f.close() # Get a list of documents in the folder filelist = glob.glob(args.input_folder+'*.xhtml') n = 0 with jsonlines.open(args.output_file, 'w') as writer: for f in filelist: html_content = open(f, "r") basename = os.path.basename(f).replace(".xhtml", "") # Parse the html content soup = BeautifulSoup(html_content, "lxml") written = 0 myarticle = {} myarticle['doc_type'] = args.doc_type myarticle['id'] = args.doc_type+"_"+basename myarticle['language_reported'] = args.language_reported pid = 0 paragraphs = [] for p in soup.find_all("p"): text = p.text.strip() text = ftfy.fix_text(text) if len(text): if text[-1] != '.' and text[-1] != ":": ... # print(f'Heading or bulleted list: {text}') else: if p.parent: thisclasses = p.get('class') parentclasses = p.parent.get('class') if not parentclasses: parentclasses = [] if not thisclasses: thisclasses = [] if 'K-REFLISTE' in thisclasses: ... # Uncomment to debug # print(f"Removed {p.get('class')} - {text}\n") elif 'TOP' in parentclasses: ... # Uncomment to debug. #print(f"Removed {p.parent.get('class')} - {text}\n") elif 'K-NOTE-TBLNOTER' in parentclasses: ... # Uncomment to debug #print(f"Removed {p.parent.get('class')} - {text}\n") elif 'K-NOTETEXT' in parentclasses: ... # Uncomment to debug #print(f"Removed {p.parent.get('class')} - {text}\n") else: if len(text.split()) >= 10 and not text.startswith("Det har oppstått en teknisk feil.") and not text.startswith("A technical error has occurred. You can try to locate relevant documents"): paragraphs.append({ 'paragraph_id': len(paragraphs), 'text': text.rstrip("\n") }) myarticle['paragraphs'] = paragraphs writer.write(myarticle) n += 1 print(f'{n} documents from {len(filelist)} files are written to {args.output_file}') def parse_args(): # Parse commandline parser = argparse.ArgumentParser( description="Process the corpus downloaded from the governments API. The corpus consists of multiple files in xhtml format. Output is an UTF-8 json-lines-file with one document per line") parser.add_argument('--language_reported', required=False, default="N/A", type=str, help='Language reported. Can be nob, nno, no or N/A') parser.add_argument('--doc_type', required=True, type=str, help='For instance government') parser.add_argument('--output_file', required=True, help='Output file name. Will overwrite it exists') parser.add_argument('--input_folder', required=True, help='Input folder. Will read all files in folder') args = parser.parse_args() return args if __name__ == "__main__": args = parse_args() main(args)
from gql import gql from dds import client as dds_client link_service_mutation = gql( """ mutation { linkService( serviceType: REDIS, serviceName: "test-service", appname: "test-app" ) { ok error } } """ ) result = dds_client.execute(link_service_mutation)["linkService"] print(f"success: {result["ok"]}") print(f"error: {result["error"]}")
from gql import gql from dds import client as dds_client link_service_mutation = gql( """ mutation { linkService( serviceType: REDIS, serviceName: "test-service", appname: "test-app" ) { ok error } } """ ) result = dds_client.execute(link_service_mutation)["linkService"] print(f"success: {result['ok']}") print(f"error: {result['error']}")
import discord from discord.ext import commands from Globals import Globals def return_category(guild: discord.Guild, category_id_to_check: int): category_dict = {i.id: i for i in guild.categories} if category_id_to_check in category_dict: return category_dict[category_id_to_check] return None def in_category(category_to_check, guild): for category in guild.categories: if category.id == category_to_check: return True return False def check_if_it_commands(category): c = Globals.conn.cursor() c.execute("""select cat_id from pug_channels where cat_id = :cat_id""", {"cat_id": category.id}) data = c.fetchone() return True if data is not None else False async def update_channels(role: discord.Role): for channel in role.guild.channels: if str(channel.category) not in ["6V6 pugs", "5V5 pugs", None]: await channel.set_permissions(role, connect=False) class ServerPreference(commands.Cog): def __init__(self, client: commands.Bot): self.client = client @commands.group(name="setup") @commands.has_permissions(administrator=True) async def setup(self, ctx): pass @commands.command() async def change_prefix(self, ctx, prefix): c = Globals.conn.cursor() c.execute(""" UPDATE server_preference SET prefix = :prefix WHERE guild_id = :guild""", {"prefix": prefix, "guild": ctx.guild.id}) Globals.conn.commit() await ctx.send(f"prefix has been changed to {prefix}") @setup.command() @commands.has_permissions(administrator=True) async def help(self, ctx): c = Globals.conn.cursor() c.execute("""select prefix from server_preference where guild_id = :guild_id""", {"guild_id": ctx.guild.id}) data = c.fetchone() prefix = data[0] embed = discord.Embed(title="setup help", colour=0xff0000) embed.set_author(name=ctx.guild.name, icon_url=ctx.guild.icon_url) embed.set_thumbnail(url=self.client.user.default_avatar_url) embed.add_field(name="**" + prefix + "change_prefix {prefix}**", value="changes the command prefix\n **the prefix can only be between 1-5 chars**", inline=False) embed.add_field(name="**" + prefix + "setup report_channel {channel id}**", value="changes/sets the place where the reports will be sent", inline=False) embed.add_field(name="**" + prefix + "setup moderator_role {role id}**", value="changes/sets the moderator role id", inline=False) embed.add_field(name="**" + prefix + "setup helper_role {role id}**", value="changes/sets the helpers role id", inline=False) embed.add_field(name="**" + prefix + "setup audit_log_channel {channel id}**", value="changes/sets the place where the audit log messages will be sent", inline=False) embed.add_field(name="**" + prefix + "setup commands_log_channel {channel id} **", value="changes/sets the place where the commands log messages will be sent", inline=False) embed.add_field(name="**" + prefix + "setup voice_create_category {category id}**", value="changes/sets the place where the join to create a channel channel will be created", inline=False) embed.add_field(name="**" + prefix + "setup voice**", value="creates the join to create a channel", inline=False) embed.add_field(name="**" + prefix + "setup server_stats**", value="create the member count channel", inline=False) embed.add_field(name="**" + prefix + "setup pug {limit}**", value="create a pugs category with according to the limit", inline=False) await ctx.send(embed=embed) @setup.command() @commands.has_permissions(administrator=True) async def report_channel(self, ctx, channel_id): try: channel_id = int(channel_id) if ctx.guild.get_channel(channel_id) is not None: c = Globals.conn.cursor() c.execute(""" UPDATE server_preference SET report_mod_channel_id = :channel_id WHERE guild_id = :guild""", {"channel_id": channel_id, "guild": ctx.guild.id}) Globals.conn.commit() await ctx.send(f"you have successfully set the report channel id to {channel_id} ") else: await ctx.send("you gave me not a channel id") except ValueError: await ctx.send("you gave us not an id") @setup.command() @commands.has_permissions(administrator=True) async def enable_moderation(self, ctx: commands.Context): c = Globals.conn.cursor() c.execute("""update server_preference set moderation = :true where guild_id = :guild_id""", {"guild_id": ctx.guild.id, "true": "true"}) Globals.conn.commit() await ctx.send("you have successfully enabled moderation") @setup.command() @commands.has_permissions(administrator=True) async def moderator_role(self, ctx, role_id): try: role_id = int(role_id) if ctx.guild.get_role(role_id) is not None: c = Globals.conn.cursor() c.execute(""" UPDATE server_preference SET mods_role_id = :role_id WHERE guild_id = :guild""", {"role_id": role_id, "guild": ctx.guild.id}) Globals.conn.commit() await ctx.send(f"you have successfully set the moderator role id to {role_id} ") else: await ctx.send("you have gave me not a role id") except ValueError: await ctx.send("you have gave me not an id") @setup.command() @commands.has_permissions(administrator=True) async def helper_role(self, ctx, role_id): try: role_id = int(role_id) if ctx.guild.get_role(role_id) is not None: c = Globals.conn.cursor() c.execute(""" UPDATE server_preference SET helpers_role_id = :role_id WHERE guild_id = :guild""", {"role_id": role_id, "guild": ctx.guild.id}) Globals.conn.commit() await ctx.send(f"you have successfully set the helpers role id to {role_id} ") else: await ctx.send("you have gave me not a role id") except ValueError: await ctx.send("you have gave me not an id") @setup.command() @commands.has_permissions(administrator=True) async def audit_log_channel(self, ctx: commands.Context, channel_id): try: channel_id = int(channel_id) channel = self.client.get_channel(channel_id) if channel is not None: c = Globals.conn.cursor() c.execute(""" UPDATE server_preference SET audit_log_channel_id = :channel_id WHERE guild_id = :guild""", {"channel_id": channel_id, "guild": ctx.guild.id}) Globals.conn.commit() await ctx.send(f"you have successfully set the command log channel ID to {channel_id} ") else: await ctx.send(f"you have not gave a channel ID") except ValueError: await ctx.send(f"you have not gave an ID") @setup.command() @commands.has_permissions(administrator=True) async def commands_log_channel(self, ctx: commands.Context, channel_id): try: channel_id = int(channel_id) channel = self.client.get_channel(channel_id) if channel is not None: c = Globals.conn.cursor() c.execute(""" UPDATE server_preference SET commands_log_channel_id = :channel_id WHERE guild_id = :guild""", {"channel_id": channel_id, "guild": ctx.guild.id}) Globals.conn.commit() await ctx.send(f"you have successfully set the command log channel ID to {channel_id} ") else: await ctx.send(f"you have not gave a channel ID") except ValueError: await ctx.send(f"you have not gave an ID") @setup.command() @commands.has_permissions(administrator=True) async def voice_create_category(self, ctx, category_id): try: category_id = int(category_id) if in_category(category_id, ctx.guild): c = Globals.conn.cursor() c.execute(""" UPDATE server_preference SET join_to_create_a_room_category_id = :category_id WHERE guild_id = :guild""", {"category_id": category_id, "guild": ctx.guild.id}) Globals.conn.commit() await ctx.send(f"you have successfully set the joint to crate a category ID to {category_id} ") else: await ctx.send(f"you gave a None category ID") except ValueError: await ctx.send(f"you have not gave an ID") @setup.command() @commands.has_permissions(administrator=True) async def voice(self, ctx): c = Globals.conn.cursor() c.execute("""SELECT * FROM server_preference WHERE guild_id = :guild_id""", {"guild_id": ctx.guild.id}) server_preference_data = c.fetchone() if server_preference_data[5] is None: await ctx.send("you didn't use the voice_create_category command") elif return_category(ctx.guild, server_preference_data[5]) is None: await ctx.send( f"{ctx.author.mention} the category with the id of {server_preference_data[5]} does not exist any more") else: if server_preference_data[6] is None or ctx.guild.get_channel(server_preference_data[6]) is None: voice_channel = await return_category(ctx.guild, server_preference_data[5]).create_voice_channel( name="join to create a channel") c.execute("""UPDATE server_preference SET join_to_create_a_room_channel_id= :channel_id WHERE guild_id = :guild_id""", {"channel_id": voice_channel.id, "guild_id": ctx.guild.id}) Globals.conn.commit() else: await ctx.send("you have already crated a channel ") @setup.command() async def server_stats(self, ctx: commands.Context): c = Globals.conn.cursor() c.execute("SELECT member_count_category_id FROM server_preference where guild_id = :guild_id", {"guild_id": ctx.guild.id}) server_preference_data = c.fetchone()[0] if not server_preference_data or not return_category(ctx.guild, server_preference_data): category = await ctx.guild.create_category(name="📊 Server Stats 📊") c.execute("""UPDATE server_preference SET member_count_category_id = :category_id WHERE guild_id = :guild_id""", {"category_id": category.id, "guild_id": ctx.guild.id}) await ctx.send(f"{ctx.author.mention} you have successfully enabled member count") Globals.conn.commit() else: await ctx.send(f"{ctx.author.mention} you all ready have a server stats category") @setup.command() @commands.has_permissions(administrator=True) async def pug(self, ctx: commands.Context, limit: int): c = Globals.conn.cursor() if limit == 6 or limit == 5 or limit == 12 or limit == 12: if limit == 5 or limit == 10: cat = await ctx.guild.create_category(name="5V5 pugs") text_channel = await ctx.guild.create_text_channel(name="pugs chat", category=cat) voice_channel = await ctx.guild.create_voice_channel(name="waiting", category=cat) c.execute("""insert into pug_channels(guild_id, cat_id, commands_channel_id,voice_channel_id,pug_limit) values (?,?,?,?,?)""", (ctx.guild.id, cat.id, text_channel.id, voice_channel.id, 5)) else: cat = await ctx.guild.create_category(name="6V6 pugs") text_channel = await ctx.guild.create_text_channel(name="pugs chat", category=cat) voice_channel = await ctx.guild.create_voice_channel(name="waiting", category=cat) c.execute("""insert into pug_channels(guild_id, cat_id, commands_channel_id,voice_channel_id,pug_limit) values (?,?,?,?,?)""", (ctx.guild.id, cat.id, text_channel.id, voice_channel.id, 6)) Globals.conn.commit() c.execute("""select pug_player_role from server_preference where guild_id = :guild_id""", {"guild_id": ctx.guild.id}) if c.fetchone()[0] is None: role = await ctx.guild.create_role(name="pug player") c.execute("""update server_preference set pug_player_role = :role_id where guild_id = :guild_id""", {"guild_id": ctx.guild.id, "role_id": role.id}) Globals.conn.commit() await update_channels(role) await ctx.send( f"You have successful setup a pugs category to {limit if limit == 5 or limit == 6 else limit / 2}V{limit if limit == 5 or limit == 6 else limit / 2}.\n" f"Feel free to change permissions names and more to the channels just **do not delete them.**\n" f"{"We have also created a new role called pug player **please do not delete it**, you can move it the position you want (it disable them from leaving the pugs room in that server)." if c.fetchone() is None else ""} ") else: await ctx.send("you can only enable pugs of 5V5 or 6V6.") @setup.command() async def delete_pug(self, ctx: commands.Context, category_id: int): cat = self.client.get_channel(category_id) if cat is not None: if check_if_it_commands(cat): for channel in cat.channels: await channel.delete() c = Globals.conn.cursor() c.execute("""delete from pug_channels where cat_id = :cat_id""", {"cat_id": cat.id}) Globals.conn.commit() await cat.delete() await ctx.send(f"you have successfully deleted the category and the channels of the ({cat},{cat.id}") else: await ctx.send(f"{category_id} is not a pug category or its not a category") else: await ctx.send(f"{category_id} is not an id") @commands.Cog.listener() async def on_guild_join(self, guild): c = Globals.conn.cursor() c.execute("""INSERT INTO server_preference(guild_id,prefix) SELECT :guild_id, :prefix WHERE NOT EXISTS (SELECT 1 FROM server_preference WHERE guild_id = :guild_id)""", {"guild_id": guild.id, "prefix": "!"}) Globals.conn.commit() @commands.Cog.listener() async def on_guild_remove(self, guild): c = Globals.conn.cursor() c.execute("""DELETE FROM server_preference WHERE guild_id=:guild_id""", {"guild_id": guild.id}) Globals.conn.commit() @commands.Cog.listener() async def on_command_error(self, ctx: commands.Context, error): if isinstance(error, commands.CommandNotFound): await self.help(ctx) else: raise error def setup(client: commands.Bot): client.add_cog(ServerPreference(client))
import discord from discord.ext import commands from Globals import Globals def return_category(guild: discord.Guild, category_id_to_check: int): category_dict = {i.id: i for i in guild.categories} if category_id_to_check in category_dict: return category_dict[category_id_to_check] return None def in_category(category_to_check, guild): for category in guild.categories: if category.id == category_to_check: return True return False def check_if_it_commands(category): c = Globals.conn.cursor() c.execute("""select cat_id from pug_channels where cat_id = :cat_id""", {"cat_id": category.id}) data = c.fetchone() return True if data is not None else False async def update_channels(role: discord.Role): for channel in role.guild.channels: if str(channel.category) not in ["6V6 pugs", "5V5 pugs", None]: await channel.set_permissions(role, connect=False) class ServerPreference(commands.Cog): def __init__(self, client: commands.Bot): self.client = client @commands.group(name="setup") @commands.has_permissions(administrator=True) async def setup(self, ctx): pass @commands.command() async def change_prefix(self, ctx, prefix): c = Globals.conn.cursor() c.execute(""" UPDATE server_preference SET prefix = :prefix WHERE guild_id = :guild""", {"prefix": prefix, "guild": ctx.guild.id}) Globals.conn.commit() await ctx.send(f"prefix has been changed to {prefix}") @setup.command() @commands.has_permissions(administrator=True) async def help(self, ctx): c = Globals.conn.cursor() c.execute("""select prefix from server_preference where guild_id = :guild_id""", {"guild_id": ctx.guild.id}) data = c.fetchone() prefix = data[0] embed = discord.Embed(title="setup help", colour=0xff0000) embed.set_author(name=ctx.guild.name, icon_url=ctx.guild.icon_url) embed.set_thumbnail(url=self.client.user.default_avatar_url) embed.add_field(name="**" + prefix + "change_prefix {prefix}**", value="changes the command prefix\n **the prefix can only be between 1-5 chars**", inline=False) embed.add_field(name="**" + prefix + "setup report_channel {channel id}**", value="changes/sets the place where the reports will be sent", inline=False) embed.add_field(name="**" + prefix + "setup moderator_role {role id}**", value="changes/sets the moderator role id", inline=False) embed.add_field(name="**" + prefix + "setup helper_role {role id}**", value="changes/sets the helpers role id", inline=False) embed.add_field(name="**" + prefix + "setup audit_log_channel {channel id}**", value="changes/sets the place where the audit log messages will be sent", inline=False) embed.add_field(name="**" + prefix + "setup commands_log_channel {channel id} **", value="changes/sets the place where the commands log messages will be sent", inline=False) embed.add_field(name="**" + prefix + "setup voice_create_category {category id}**", value="changes/sets the place where the join to create a channel channel will be created", inline=False) embed.add_field(name="**" + prefix + "setup voice**", value="creates the join to create a channel", inline=False) embed.add_field(name="**" + prefix + "setup server_stats**", value="create the member count channel", inline=False) embed.add_field(name="**" + prefix + "setup pug {limit}**", value="create a pugs category with according to the limit", inline=False) await ctx.send(embed=embed) @setup.command() @commands.has_permissions(administrator=True) async def report_channel(self, ctx, channel_id): try: channel_id = int(channel_id) if ctx.guild.get_channel(channel_id) is not None: c = Globals.conn.cursor() c.execute(""" UPDATE server_preference SET report_mod_channel_id = :channel_id WHERE guild_id = :guild""", {"channel_id": channel_id, "guild": ctx.guild.id}) Globals.conn.commit() await ctx.send(f"you have successfully set the report channel id to {channel_id} ") else: await ctx.send("you gave me not a channel id") except ValueError: await ctx.send("you gave us not an id") @setup.command() @commands.has_permissions(administrator=True) async def enable_moderation(self, ctx: commands.Context): c = Globals.conn.cursor() c.execute("""update server_preference set moderation = :true where guild_id = :guild_id""", {"guild_id": ctx.guild.id, "true": "true"}) Globals.conn.commit() await ctx.send("you have successfully enabled moderation") @setup.command() @commands.has_permissions(administrator=True) async def moderator_role(self, ctx, role_id): try: role_id = int(role_id) if ctx.guild.get_role(role_id) is not None: c = Globals.conn.cursor() c.execute(""" UPDATE server_preference SET mods_role_id = :role_id WHERE guild_id = :guild""", {"role_id": role_id, "guild": ctx.guild.id}) Globals.conn.commit() await ctx.send(f"you have successfully set the moderator role id to {role_id} ") else: await ctx.send("you have gave me not a role id") except ValueError: await ctx.send("you have gave me not an id") @setup.command() @commands.has_permissions(administrator=True) async def helper_role(self, ctx, role_id): try: role_id = int(role_id) if ctx.guild.get_role(role_id) is not None: c = Globals.conn.cursor() c.execute(""" UPDATE server_preference SET helpers_role_id = :role_id WHERE guild_id = :guild""", {"role_id": role_id, "guild": ctx.guild.id}) Globals.conn.commit() await ctx.send(f"you have successfully set the helpers role id to {role_id} ") else: await ctx.send("you have gave me not a role id") except ValueError: await ctx.send("you have gave me not an id") @setup.command() @commands.has_permissions(administrator=True) async def audit_log_channel(self, ctx: commands.Context, channel_id): try: channel_id = int(channel_id) channel = self.client.get_channel(channel_id) if channel is not None: c = Globals.conn.cursor() c.execute(""" UPDATE server_preference SET audit_log_channel_id = :channel_id WHERE guild_id = :guild""", {"channel_id": channel_id, "guild": ctx.guild.id}) Globals.conn.commit() await ctx.send(f"you have successfully set the command log channel ID to {channel_id} ") else: await ctx.send(f"you have not gave a channel ID") except ValueError: await ctx.send(f"you have not gave an ID") @setup.command() @commands.has_permissions(administrator=True) async def commands_log_channel(self, ctx: commands.Context, channel_id): try: channel_id = int(channel_id) channel = self.client.get_channel(channel_id) if channel is not None: c = Globals.conn.cursor() c.execute(""" UPDATE server_preference SET commands_log_channel_id = :channel_id WHERE guild_id = :guild""", {"channel_id": channel_id, "guild": ctx.guild.id}) Globals.conn.commit() await ctx.send(f"you have successfully set the command log channel ID to {channel_id} ") else: await ctx.send(f"you have not gave a channel ID") except ValueError: await ctx.send(f"you have not gave an ID") @setup.command() @commands.has_permissions(administrator=True) async def voice_create_category(self, ctx, category_id): try: category_id = int(category_id) if in_category(category_id, ctx.guild): c = Globals.conn.cursor() c.execute(""" UPDATE server_preference SET join_to_create_a_room_category_id = :category_id WHERE guild_id = :guild""", {"category_id": category_id, "guild": ctx.guild.id}) Globals.conn.commit() await ctx.send(f"you have successfully set the joint to crate a category ID to {category_id} ") else: await ctx.send(f"you gave a None category ID") except ValueError: await ctx.send(f"you have not gave an ID") @setup.command() @commands.has_permissions(administrator=True) async def voice(self, ctx): c = Globals.conn.cursor() c.execute("""SELECT * FROM server_preference WHERE guild_id = :guild_id""", {"guild_id": ctx.guild.id}) server_preference_data = c.fetchone() if server_preference_data[5] is None: await ctx.send("you didn't use the voice_create_category command") elif return_category(ctx.guild, server_preference_data[5]) is None: await ctx.send( f"{ctx.author.mention} the category with the id of {server_preference_data[5]} does not exist any more") else: if server_preference_data[6] is None or ctx.guild.get_channel(server_preference_data[6]) is None: voice_channel = await return_category(ctx.guild, server_preference_data[5]).create_voice_channel( name="join to create a channel") c.execute("""UPDATE server_preference SET join_to_create_a_room_channel_id= :channel_id WHERE guild_id = :guild_id""", {"channel_id": voice_channel.id, "guild_id": ctx.guild.id}) Globals.conn.commit() else: await ctx.send("you have already crated a channel ") @setup.command() async def server_stats(self, ctx: commands.Context): c = Globals.conn.cursor() c.execute("SELECT member_count_category_id FROM server_preference where guild_id = :guild_id", {"guild_id": ctx.guild.id}) server_preference_data = c.fetchone()[0] if not server_preference_data or not return_category(ctx.guild, server_preference_data): category = await ctx.guild.create_category(name="📊 Server Stats 📊") c.execute("""UPDATE server_preference SET member_count_category_id = :category_id WHERE guild_id = :guild_id""", {"category_id": category.id, "guild_id": ctx.guild.id}) await ctx.send(f"{ctx.author.mention} you have successfully enabled member count") Globals.conn.commit() else: await ctx.send(f"{ctx.author.mention} you all ready have a server stats category") @setup.command() @commands.has_permissions(administrator=True) async def pug(self, ctx: commands.Context, limit: int): c = Globals.conn.cursor() if limit == 6 or limit == 5 or limit == 12 or limit == 12: if limit == 5 or limit == 10: cat = await ctx.guild.create_category(name="5V5 pugs") text_channel = await ctx.guild.create_text_channel(name="pugs chat", category=cat) voice_channel = await ctx.guild.create_voice_channel(name="waiting", category=cat) c.execute("""insert into pug_channels(guild_id, cat_id, commands_channel_id,voice_channel_id,pug_limit) values (?,?,?,?,?)""", (ctx.guild.id, cat.id, text_channel.id, voice_channel.id, 5)) else: cat = await ctx.guild.create_category(name="6V6 pugs") text_channel = await ctx.guild.create_text_channel(name="pugs chat", category=cat) voice_channel = await ctx.guild.create_voice_channel(name="waiting", category=cat) c.execute("""insert into pug_channels(guild_id, cat_id, commands_channel_id,voice_channel_id,pug_limit) values (?,?,?,?,?)""", (ctx.guild.id, cat.id, text_channel.id, voice_channel.id, 6)) Globals.conn.commit() c.execute("""select pug_player_role from server_preference where guild_id = :guild_id""", {"guild_id": ctx.guild.id}) if c.fetchone()[0] is None: role = await ctx.guild.create_role(name="pug player") c.execute("""update server_preference set pug_player_role = :role_id where guild_id = :guild_id""", {"guild_id": ctx.guild.id, "role_id": role.id}) Globals.conn.commit() await update_channels(role) await ctx.send( f"You have successful setup a pugs category to {limit if limit == 5 or limit == 6 else limit / 2}V{limit if limit == 5 or limit == 6 else limit / 2}.\n" f"Feel free to change permissions names and more to the channels just **do not delete them.**\n" f"{'We have also created a new role called pug player **please do not delete it**, you can move it the position you want (it disable them from leaving the pugs room in that server).' if c.fetchone() is None else ''} ") else: await ctx.send("you can only enable pugs of 5V5 or 6V6.") @setup.command() async def delete_pug(self, ctx: commands.Context, category_id: int): cat = self.client.get_channel(category_id) if cat is not None: if check_if_it_commands(cat): for channel in cat.channels: await channel.delete() c = Globals.conn.cursor() c.execute("""delete from pug_channels where cat_id = :cat_id""", {"cat_id": cat.id}) Globals.conn.commit() await cat.delete() await ctx.send(f"you have successfully deleted the category and the channels of the ({cat},{cat.id}") else: await ctx.send(f"{category_id} is not a pug category or its not a category") else: await ctx.send(f"{category_id} is not an id") @commands.Cog.listener() async def on_guild_join(self, guild): c = Globals.conn.cursor() c.execute("""INSERT INTO server_preference(guild_id,prefix) SELECT :guild_id, :prefix WHERE NOT EXISTS (SELECT 1 FROM server_preference WHERE guild_id = :guild_id)""", {"guild_id": guild.id, "prefix": "!"}) Globals.conn.commit() @commands.Cog.listener() async def on_guild_remove(self, guild): c = Globals.conn.cursor() c.execute("""DELETE FROM server_preference WHERE guild_id=:guild_id""", {"guild_id": guild.id}) Globals.conn.commit() @commands.Cog.listener() async def on_command_error(self, ctx: commands.Context, error): if isinstance(error, commands.CommandNotFound): await self.help(ctx) else: raise error def setup(client: commands.Bot): client.add_cog(ServerPreference(client))
from stix_shifter_utils.stix_transmission.utils.RestApiClient import RestApiClient from stix_shifter_utils.utils import logger from stix_shifter_utils.utils.error_response import ErrorResponder from .response_mapper import ResponseMapper from datetime import datetime, timezone import secrets import string import hashlib import json from requests.exceptions import ConnectionError class MaxDailyQuotaException(Exception): pass class APIClient: QUERY_ENDPOINT = 'public_api/v1/xql/start_xql_query/' RESULT_ENDPOINT = 'public_api/v1/xql/get_query_results/' STREAM_ENDPOINT = 'public_api/v1/xql/get_query_results_stream/' QUOTA_ENDPOINT = '/public_api/v1/xql/get_quota/' def __init__(self, connection, configuration): self.auth = configuration.get('auth') self.logger = logger.set_logger(__name__) nonce = "".join([secrets.choice(string.ascii_letters + string.digits) for _ in range(64)]) timestamp = int(datetime.now(timezone.utc).timestamp()) * 1000 self.auth = configuration.get('auth') auth_key = f"{self.auth["api_key"]}{nonce}{timestamp}" auth_key = auth_key.encode("utf-8") api_key_hash = hashlib.sha256(auth_key).hexdigest() headers = { "x-xdr-timestamp": str(timestamp), "x-xdr-nonce": nonce, "x-xdr-auth-id": str(self.auth['api_key_id']), "Authorization": api_key_hash } self.client = RestApiClient(connection.get('host'), connection.get('port', None), headers, url_modifier_function=None, ) self.result_limit = connection['options'].get('result_limit') self.timeout = connection['options']['timeout'] self.quota_threshold = connection['quota_threshold'] self.connector = __name__.split('.')[1] def ping_data_source(self): """ Ping the Data Source :return: Response object """ data = { "request_data": {} } return self.client.call_api(self.QUOTA_ENDPOINT, 'POST', headers=self.client.headers, data=json.dumps(data), timeout=self.timeout) def get_remaining_quota(self): """ Pings the quota endpoint to fetch the remaining quota :return: Response object """ return_obj = {} response_dict = {} data = { "request_data": {} } quota_wrapper = None try: quota_wrapper = self.client.call_api(self.QUOTA_ENDPOINT, 'POST', headers=self.client.headers, data=json.dumps(data), timeout=self.timeout) quota_response_code = quota_wrapper.response.status_code quota_response_text = json.loads(quota_wrapper.read().decode('utf-8')) if quota_response_code == 200: if 'reply' in quota_response_text.keys(): # The daily quota unit for standard license is 5. additional units up to 10 can be added. if quota_response_text['reply']['license_quota'] == 5 and \ quota_response_text['reply']['additional_purchased_quota'] == 0.0: # For a Standard license,if the configured quota threshold is greater than 5, # the threshold quota value is reset to 5. self.quota_threshold = 5 if self.quota_threshold > 5 else self.quota_threshold if quota_response_text['reply']['used_quota'] >= self.quota_threshold: raise MaxDailyQuotaException else: if quota_response_text['reply']['used_quota'] >= self.quota_threshold: raise MaxDailyQuotaException return_obj['success'] = True else: return_obj = ResponseMapper().status_code_mapping(quota_response_code, quota_response_text) except ValueError as ex: if quota_wrapper is not None: self.logger.debug(quota_wrapper.read()) raise Exception(f'Cannot parse response: {ex}') from ex except MaxDailyQuotaException: response_dict['type'] = "MaxDailyQuotaException" response_dict['message'] = "query usage exceeded max daily quota" ErrorResponder.fill_error(return_obj, response_dict, ['message'], connector=self.connector) except ConnectionError: response_dict['type'] = "ConnectionError" response_dict['message'] = "Invalid Host" ErrorResponder.fill_error(return_obj, response_dict, ['message'], connector=self.connector) except Exception as ex: if 'timeout_error' in str(ex): response_dict['type'] = 'TimeoutError' else: response_dict['type'] = ex.__class__.__name__ response_dict['message'] = ex self.logger.error('error when getting search results: %s', ex) ErrorResponder.fill_error(return_obj, response_dict, ['message'], connector=self.connector) return return_obj def create_search(self, query): """ Queries the data source :return: Response object """ return_obj = self.get_remaining_quota() if return_obj['success']: if not isinstance(query, dict): query = json.loads(query) for dataset in query.keys(): query[dataset]["tenants"] = self.auth['tenant'].split(",") data = { "request_data": query[dataset] } return self.client.call_api(self.QUERY_ENDPOINT, 'POST', headers=self.client.headers, data=json.dumps(data), timeout=self.timeout) return return_obj def get_search_status(self, search_id): """ Queries the data source to fetch the status of api call :return: Response object """ data = { "request_data": { "query_id": search_id, "pending_flag": True, "limit": self.result_limit, "format": "json" } } return self.client.call_api(self.RESULT_ENDPOINT, 'POST', headers=self.client.headers, data=json.dumps(data), timeout=self.timeout) def get_search_results(self, search_id): """ Return the search results :param search_id:str :return: Response object """ data = { "request_data": { "query_id": search_id, "pending_flag": False, "limit": self.result_limit, "format": "json" } } return self.client.call_api(self.RESULT_ENDPOINT, 'POST', headers=self.client.headers, data=json.dumps(data), timeout=self.timeout) @staticmethod def delete_search(): """ Delete operation of a search id is not supported in Palo Alto Cortex XDR :return dict """ return {"code": 200, "success": True} def get_stream_results(self, stream_id): """ Return the stream results :param stream_id: string :return: Raw Json data """ data = { "request_data": {"stream_id": stream_id, "is_gzip_compressed": False } } return self.client.call_api(self.STREAM_ENDPOINT, 'POST', headers=self.client.headers, data=json.dumps(data), timeout=self.timeout)
from stix_shifter_utils.stix_transmission.utils.RestApiClient import RestApiClient from stix_shifter_utils.utils import logger from stix_shifter_utils.utils.error_response import ErrorResponder from .response_mapper import ResponseMapper from datetime import datetime, timezone import secrets import string import hashlib import json from requests.exceptions import ConnectionError class MaxDailyQuotaException(Exception): pass class APIClient: QUERY_ENDPOINT = 'public_api/v1/xql/start_xql_query/' RESULT_ENDPOINT = 'public_api/v1/xql/get_query_results/' STREAM_ENDPOINT = 'public_api/v1/xql/get_query_results_stream/' QUOTA_ENDPOINT = '/public_api/v1/xql/get_quota/' def __init__(self, connection, configuration): self.auth = configuration.get('auth') self.logger = logger.set_logger(__name__) nonce = "".join([secrets.choice(string.ascii_letters + string.digits) for _ in range(64)]) timestamp = int(datetime.now(timezone.utc).timestamp()) * 1000 self.auth = configuration.get('auth') auth_key = f"{self.auth['api_key']}{nonce}{timestamp}" auth_key = auth_key.encode("utf-8") api_key_hash = hashlib.sha256(auth_key).hexdigest() headers = { "x-xdr-timestamp": str(timestamp), "x-xdr-nonce": nonce, "x-xdr-auth-id": str(self.auth['api_key_id']), "Authorization": api_key_hash } self.client = RestApiClient(connection.get('host'), connection.get('port', None), headers, url_modifier_function=None, ) self.result_limit = connection['options'].get('result_limit') self.timeout = connection['options']['timeout'] self.quota_threshold = connection['quota_threshold'] self.connector = __name__.split('.')[1] def ping_data_source(self): """ Ping the Data Source :return: Response object """ data = { "request_data": {} } return self.client.call_api(self.QUOTA_ENDPOINT, 'POST', headers=self.client.headers, data=json.dumps(data), timeout=self.timeout) def get_remaining_quota(self): """ Pings the quota endpoint to fetch the remaining quota :return: Response object """ return_obj = {} response_dict = {} data = { "request_data": {} } quota_wrapper = None try: quota_wrapper = self.client.call_api(self.QUOTA_ENDPOINT, 'POST', headers=self.client.headers, data=json.dumps(data), timeout=self.timeout) quota_response_code = quota_wrapper.response.status_code quota_response_text = json.loads(quota_wrapper.read().decode('utf-8')) if quota_response_code == 200: if 'reply' in quota_response_text.keys(): # The daily quota unit for standard license is 5. additional units up to 10 can be added. if quota_response_text['reply']['license_quota'] == 5 and \ quota_response_text['reply']['additional_purchased_quota'] == 0.0: # For a Standard license,if the configured quota threshold is greater than 5, # the threshold quota value is reset to 5. self.quota_threshold = 5 if self.quota_threshold > 5 else self.quota_threshold if quota_response_text['reply']['used_quota'] >= self.quota_threshold: raise MaxDailyQuotaException else: if quota_response_text['reply']['used_quota'] >= self.quota_threshold: raise MaxDailyQuotaException return_obj['success'] = True else: return_obj = ResponseMapper().status_code_mapping(quota_response_code, quota_response_text) except ValueError as ex: if quota_wrapper is not None: self.logger.debug(quota_wrapper.read()) raise Exception(f'Cannot parse response: {ex}') from ex except MaxDailyQuotaException: response_dict['type'] = "MaxDailyQuotaException" response_dict['message'] = "query usage exceeded max daily quota" ErrorResponder.fill_error(return_obj, response_dict, ['message'], connector=self.connector) except ConnectionError: response_dict['type'] = "ConnectionError" response_dict['message'] = "Invalid Host" ErrorResponder.fill_error(return_obj, response_dict, ['message'], connector=self.connector) except Exception as ex: if 'timeout_error' in str(ex): response_dict['type'] = 'TimeoutError' else: response_dict['type'] = ex.__class__.__name__ response_dict['message'] = ex self.logger.error('error when getting search results: %s', ex) ErrorResponder.fill_error(return_obj, response_dict, ['message'], connector=self.connector) return return_obj def create_search(self, query): """ Queries the data source :return: Response object """ return_obj = self.get_remaining_quota() if return_obj['success']: if not isinstance(query, dict): query = json.loads(query) for dataset in query.keys(): query[dataset]["tenants"] = self.auth['tenant'].split(",") data = { "request_data": query[dataset] } return self.client.call_api(self.QUERY_ENDPOINT, 'POST', headers=self.client.headers, data=json.dumps(data), timeout=self.timeout) return return_obj def get_search_status(self, search_id): """ Queries the data source to fetch the status of api call :return: Response object """ data = { "request_data": { "query_id": search_id, "pending_flag": True, "limit": self.result_limit, "format": "json" } } return self.client.call_api(self.RESULT_ENDPOINT, 'POST', headers=self.client.headers, data=json.dumps(data), timeout=self.timeout) def get_search_results(self, search_id): """ Return the search results :param search_id:str :return: Response object """ data = { "request_data": { "query_id": search_id, "pending_flag": False, "limit": self.result_limit, "format": "json" } } return self.client.call_api(self.RESULT_ENDPOINT, 'POST', headers=self.client.headers, data=json.dumps(data), timeout=self.timeout) @staticmethod def delete_search(): """ Delete operation of a search id is not supported in Palo Alto Cortex XDR :return dict """ return {"code": 200, "success": True} def get_stream_results(self, stream_id): """ Return the stream results :param stream_id: string :return: Raw Json data """ data = { "request_data": {"stream_id": stream_id, "is_gzip_compressed": False } } return self.client.call_api(self.STREAM_ENDPOINT, 'POST', headers=self.client.headers, data=json.dumps(data), timeout=self.timeout)
import math import Levenshtein as Lev # see https://pypi.python.org/pypi/python-Levenshtein #see https://stackoverflow.com/q/29233888/2583476 keyboard_cartesian = {'q': {'x':0, 'y':0}, 'w': {'x':1, 'y':0}, 'e': {'x':2, 'y':0}, 'r': {'x':3, 'y':0}, 't': {'x':4, 'y':0}, 'y': {'x':5, 'y':0}, 'u': {'x':6, 'y':0}, 'i': {'x':7, 'y':0}, 'o': {'x':8, 'y':0}, 'p': {'x':9, 'y':0}, 'a': {'x':0, 'y':1},'z': {'x':0, 'y':2},'s': {'x':1, 'y':1},'x': {'x':1, 'y':2},'d': {'x':2, 'y':1},'c': {'x':2, 'y':2}, 'f': {'x':3, 'y':1}, 'b': {'x':4, 'y':2}, 'm': {'x':5, 'y':2}, 'j': {'x':6, 'y':1}, 'g': {'x':4, 'y':1}, 'h': {'x':5, 'y':1}, 'j': {'x':6, 'y':1}, 'k': {'x':7, 'y':1}, 'l': {'x':8, 'y':1}, 'v': {'x':3, 'y':2}, 'n': {'x':5, 'y':2}, } def euclidean_distance(a,b): X = (keyboard_cartesian[a]['x'] - keyboard_cartesian[b]['x'])**2 Y = (keyboard_cartesian[a]['y'] - keyboard_cartesian[b]['y'])**2 return math.sqrt(X+Y) # words.txt is any list of words at one word per line. I used SCOWL: http://app.aspell.net/create lines = [line.strip().lower() for line in open('words.txt')] outfile=open("covfefe_list.txt",'w') covfefe="covfefe" # This is your trumpism threshold=0.5 # Jaro-Winkler metric threshold: 0=completely different, 1=identical alphabet="abcdefghijklmnopqrstuvwyz" header="From\tTo\tEdits\tJaro-Winkler\tTotal Distance\tEdit list\n" outfile.write(header) for line in lines: total_dist=0 editout='' d= Lev.distance(line,covfefe) j=Lev.jaro_winkler(line,covfefe) edits=Lev.editops(line,covfefe) if j>threshold: print 'From \''+line+'\' to \''+covfefe+ '\' takes %d'%d+ ' edits. The J-W metric is %.3g'%j+' and the edits are:' outstring=line+'\t'+covfefe+'\t%d\t%.3g'%(d,j) for edit in edits: e=edit[0] if e=='delete': edittext='delete \''+ line[edit[1]] +'\' at %d'%(edit[1]+1) elif e=='insert': edittext='insert \''+covfefe[edit[2]]+ '\' at %d'%(edit[2]+1) else:#replace if line[edit[1]] in alphabet and covfefe[edit[2]] in alphabet: dist=euclidean_distance(line[edit[1]],covfefe[edit[2]]) total_dist+=dist edittext=edit[0]+' \''+line[edit[1]]+'\' at %d'%(edit[1]+1)+' with \''+covfefe[edit[2]]+'\' (distance %.3g)'%dist else: edittext=edit[0]+' \''+line[edit[1]]+'\' at %d'%(edit[1]+1)+' with \''+covfefe[edit[2]]+'\' (non-letter, distance ignored)' print ' '+edittext editout+=edittext+', ' outstring+='\t%.3g\t'%total_dist+editout+'\n' print ' total replacement distance: %.3g'%total_dist outfile.write(outstring) outfile.close() # The output format is tab-delimited and ready to import into a spreadsheet. # Unless you want the list of edits to be split into multiple cells, make sure commas is not sleected as a delimiter
import math import Levenshtein as Lev # see https://pypi.python.org/pypi/python-Levenshtein #see https://stackoverflow.com/q/29233888/2583476 keyboard_cartesian = {'q': {'x':0, 'y':0}, 'w': {'x':1, 'y':0}, 'e': {'x':2, 'y':0}, 'r': {'x':3, 'y':0}, 't': {'x':4, 'y':0}, 'y': {'x':5, 'y':0}, 'u': {'x':6, 'y':0}, 'i': {'x':7, 'y':0}, 'o': {'x':8, 'y':0}, 'p': {'x':9, 'y':0}, 'a': {'x':0, 'y':1},'z': {'x':0, 'y':2},'s': {'x':1, 'y':1},'x': {'x':1, 'y':2},'d': {'x':2, 'y':1},'c': {'x':2, 'y':2}, 'f': {'x':3, 'y':1}, 'b': {'x':4, 'y':2}, 'm': {'x':5, 'y':2}, 'j': {'x':6, 'y':1}, 'g': {'x':4, 'y':1}, 'h': {'x':5, 'y':1}, 'j': {'x':6, 'y':1}, 'k': {'x':7, 'y':1}, 'l': {'x':8, 'y':1}, 'v': {'x':3, 'y':2}, 'n': {'x':5, 'y':2}, } def euclidean_distance(a,b): X = (keyboard_cartesian[a]['x'] - keyboard_cartesian[b]['x'])**2 Y = (keyboard_cartesian[a]['y'] - keyboard_cartesian[b]['y'])**2 return math.sqrt(X+Y) # words.txt is any list of words at one word per line. I used SCOWL: http://app.aspell.net/create lines = [line.strip().lower() for line in open('words.txt')] outfile=open("covfefe_list.txt",'w') covfefe="covfefe" # This is your trumpism threshold=0.5 # Jaro-Winkler metric threshold: 0=completely different, 1=identical alphabet="abcdefghijklmnopqrstuvwyz" header="From\tTo\tEdits\tJaro-Winkler\tTotal Distance\tEdit list\n" outfile.write(header) for line in lines: total_dist=0 editout='' d= Lev.distance(line,covfefe) j=Lev.jaro_winkler(line,covfefe) edits=Lev.editops(line,covfefe) if j>threshold: print 'From \''+line+'\' to \''+covfefe+ '\' takes %d'%d+ ' edits. The J-W metric is %.3g'%j+' and the edits are:' outstring=line+'\t'+covfefe+'\t%d\t%.3g'%(d,j) for edit in edits: e=edit[0] if e=='delete': edittext='delete \''+ line[edit[1]] +'\' at %d'%(edit[1]+1) elif e=='insert': edittext='insert \''+covfefe[edit[2]]+ '\' at %d'%(edit[2]+1) else:#replace if line[edit[1]] in alphabet and covfefe[edit[2]] in alphabet: dist=euclidean_distance(line[edit[1]],covfefe[edit[2]]) total_dist+=dist edittext=edit[0]+' \''+line[edit[1]]+'\' at %d'%(edit[1]+1)+' with \''+covfefe[edit[2]]+'\' (distance %.3g)'%dist else: edittext=edit[0]+' \''+line[edit[1]]+'\' at %d'%(edit[1]+1)+' with \''+covfefe[edit[2]]+'\' (non-letter, distance ignored)' print ' '+edittext editout+=edittext+', ' outstring+='\t%.3g\t'%total_dist+editout+'\n' print ' total replacement distance: %.3g'%total_dist outfile.write(outstring) outfile.close() # The output format is tab-delimited and ready to import into a spreadsheet. # Unless you want the list of edits to be split into multiple cells, make sure commas is not sleected as a delimiter
#!/usr/bin/env python3 import requests import json from pprint import pprint from jnpr.healthbot import HealthBotClient from jnpr.healthbot import DeviceSchema from jnpr.healthbot import DeviceGroupSchema import argparse import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) parser = argparse.ArgumentParser(description='Onboard all devices from Apstra BP into HealthBot') optional = parser._action_groups.pop() required = parser.add_argument_group('required arguments') required.add_argument("-as","--aos_url",help="Apstra instance URL", required=True) required.add_argument("-hs","--hb_ip",help="Healthbot server IP", required=True) optional.add_argument("-au","--aos_user",help="Apstra instance username",default="admin") optional.add_argument("-ap","--aos_passwd",help="Apstra instance password",default="admin") optional.add_argument("-hu","--hb_user",help="Healthbot username",default="admin") optional.add_argument("-hp","--hb_passwd",help="Healthbot password",default="healthbot") optional.add_argument("-du","--device_user",help="Juniper device username",default="root") optional.add_argument("-dp","--device_passwd",help="Juniper device password",default="password") parser._action_groups.append(optional) args=parser.parse_args() hb_ip=args.hb_ip hb_user=args.hb_user hb_password=args.hb_passwd device_password=args.device_passwd device_user=args.device_user aos_url=args.aos_url bp_roles=dict() # Step 1 - Connect to HealthBot and get hbez handle hb=HealthBotClient(hb_ip,hb_user,hb_password) hb.open() # Step 2 - Get AOS API token tokenreq_body={'username':args.aos_user,'password':args.aos_passwd} req_header={'accept':'application/json','content-type':'application/json'} token_res=requests.post(f"{aos_url}/api/aaa/login",headers=req_header,json=tokenreq_body,verify=False) authtoken=token_res.json()['token'] headers={'AuthToken':authtoken} # Step 3 - Pull all defined blueprints blueprintlist=requests.get(f'{aos_url}/api/blueprints',headers=headers,verify=False) # Step 4 - Iterate over all blueprints(creating different device groups in HB per blueprint) for blueprint in blueprintlist.json()['items']: bpid=blueprint['id'] bp_roles[bpid]=dict() bp_name=blueprint['label'] transtable=bp_name.maketrans("_","-") bp_name=bp_name.translate(transtable) print(f'Blueprint: {bp_name}') # Multiple ways to get the switches via AOS API. bp_systems=requests.get(f'{aos_url}/api/blueprints/{bpid}/nodes?node_type=system',headers=headers,verify=False) systems=bp_systems.json()['nodes'] leafnames=[] spinenames=[] superspinenames=[] # Not sure if I can simplify this bit with graphql or not, so for now I need to pull facts from each device agent for key,system in systems.items(): if system['role'] in ['spine', 'leaf', 'superspine']: bp_roles[bpid][system['role']] = 1 switchinfo=requests.get(f"{aos_url}/api/systems/{system["system_id"]}",headers=headers,verify=False) mgmt_ip=switchinfo.json()['facts']['mgmt_ipaddr'] hostname=switchinfo.json()['status']['hostname'] vendor=switchinfo.json()['facts']['vendor'].lower() vendor_os=switchinfo.json()['facts']['os_family'].lower() if system['role'] == 'leaf': leafnames.append(hostname) if system['role'] == 'spine': spinenames.append(hostname) if system['role'] == 'superspine': superspinenames.append(hostname) # Now add this device to HB ds = DeviceSchema(device_id=hostname, host=mgmt_ip, vendor={vendor : {'operating-system': vendor_os}}, authentication={"password": {"password": device_password, "username": device_user}}) hb.device.add(schema=ds) print(f"{system["role"]} {hostname} has management ip {mgmt_ip}") # As long as there is at least one leaf, create a leaf device group for this blueprint if len(leafnames) > 0: dgs = DeviceGroupSchema(device_group_name=f"{bp_name}-leafs", devices=leafnames) dgs.description=f"Leaf switches from AOS blueprint {bp_name}" hb.device_group.add(dgs) # Same thing for spines if len(spinenames) > 0: dgs = DeviceGroupSchema(device_group_name=f"{bp_name}-spines", devices=spinenames) dgs.description=f"Spine switches from AOS blueprint {bp_name}" hb.device_group.add(dgs) # Same thing for superspines if len(spinenames) > 0: dgs = DeviceGroupSchema(device_group_name=f"{bp_name}-superspines", devices=superspinenames) dgs.description=f"Super Spine switches from AOS blueprint {bp_name}" hb.device_group.add(dgs) # Add to Apstra confglet grpc_configlet= { "ref_archs": [ "two_stage_l3clos" ], "generators": [ { "config_style": "junos", "section": "system", "template_text": "system {\n services {\n extension-service {\n request-response {\n grpc {\n clear-text;\n }\n }\n }\n }\n}", "negation_template_text": "", "filename": "" } ], "display_name": "enableoc" } create_oc_configlet=requests.post(f'{aos_url}/api/design/configlets',headers=headers,json=grpc_configlet,verify=False) # Assign configlet 'enableoc' to blueprints print("Assign configlet 'enableoc' to blueprints") for blueprint in blueprintlist.json()['items']: bpid=blueprint['id'] bp_configlet= { "configlet": { "generators": [ { "config_style": "junos", "section": "system", "template_text": "system {\n services {\n extension-service {\n request-response {\n grpc {\n clear-text;\n }\n }\n }\n }\n}", "negation_template_text": "", "filename": "" } ], "display_name": "enableoc" }, "condition": "role in "+ str(list(bp_roles[bpid].keys())) , "label": "enableoc" } apply_oc_configlet=requests.post(f'{aos_url}/api/blueprints/{bpid}/configlets',headers=headers,json=bp_configlet,verify=False) print("Blueprint ID "+str(bpid)+ " == apply ID: "+str(apply_oc_configlet.json())) print ("Done - please login to Healthbot and Apstra for commit changes") exit(0)
#!/usr/bin/env python3 import requests import json from pprint import pprint from jnpr.healthbot import HealthBotClient from jnpr.healthbot import DeviceSchema from jnpr.healthbot import DeviceGroupSchema import argparse import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) parser = argparse.ArgumentParser(description='Onboard all devices from Apstra BP into HealthBot') optional = parser._action_groups.pop() required = parser.add_argument_group('required arguments') required.add_argument("-as","--aos_url",help="Apstra instance URL", required=True) required.add_argument("-hs","--hb_ip",help="Healthbot server IP", required=True) optional.add_argument("-au","--aos_user",help="Apstra instance username",default="admin") optional.add_argument("-ap","--aos_passwd",help="Apstra instance password",default="admin") optional.add_argument("-hu","--hb_user",help="Healthbot username",default="admin") optional.add_argument("-hp","--hb_passwd",help="Healthbot password",default="healthbot") optional.add_argument("-du","--device_user",help="Juniper device username",default="root") optional.add_argument("-dp","--device_passwd",help="Juniper device password",default="password") parser._action_groups.append(optional) args=parser.parse_args() hb_ip=args.hb_ip hb_user=args.hb_user hb_password=args.hb_passwd device_password=args.device_passwd device_user=args.device_user aos_url=args.aos_url bp_roles=dict() # Step 1 - Connect to HealthBot and get hbez handle hb=HealthBotClient(hb_ip,hb_user,hb_password) hb.open() # Step 2 - Get AOS API token tokenreq_body={'username':args.aos_user,'password':args.aos_passwd} req_header={'accept':'application/json','content-type':'application/json'} token_res=requests.post(f"{aos_url}/api/aaa/login",headers=req_header,json=tokenreq_body,verify=False) authtoken=token_res.json()['token'] headers={'AuthToken':authtoken} # Step 3 - Pull all defined blueprints blueprintlist=requests.get(f'{aos_url}/api/blueprints',headers=headers,verify=False) # Step 4 - Iterate over all blueprints(creating different device groups in HB per blueprint) for blueprint in blueprintlist.json()['items']: bpid=blueprint['id'] bp_roles[bpid]=dict() bp_name=blueprint['label'] transtable=bp_name.maketrans("_","-") bp_name=bp_name.translate(transtable) print(f'Blueprint: {bp_name}') # Multiple ways to get the switches via AOS API. bp_systems=requests.get(f'{aos_url}/api/blueprints/{bpid}/nodes?node_type=system',headers=headers,verify=False) systems=bp_systems.json()['nodes'] leafnames=[] spinenames=[] superspinenames=[] # Not sure if I can simplify this bit with graphql or not, so for now I need to pull facts from each device agent for key,system in systems.items(): if system['role'] in ['spine', 'leaf', 'superspine']: bp_roles[bpid][system['role']] = 1 switchinfo=requests.get(f"{aos_url}/api/systems/{system['system_id']}",headers=headers,verify=False) mgmt_ip=switchinfo.json()['facts']['mgmt_ipaddr'] hostname=switchinfo.json()['status']['hostname'] vendor=switchinfo.json()['facts']['vendor'].lower() vendor_os=switchinfo.json()['facts']['os_family'].lower() if system['role'] == 'leaf': leafnames.append(hostname) if system['role'] == 'spine': spinenames.append(hostname) if system['role'] == 'superspine': superspinenames.append(hostname) # Now add this device to HB ds = DeviceSchema(device_id=hostname, host=mgmt_ip, vendor={vendor : {'operating-system': vendor_os}}, authentication={"password": {"password": device_password, "username": device_user}}) hb.device.add(schema=ds) print(f"{system['role']} {hostname} has management ip {mgmt_ip}") # As long as there is at least one leaf, create a leaf device group for this blueprint if len(leafnames) > 0: dgs = DeviceGroupSchema(device_group_name=f"{bp_name}-leafs", devices=leafnames) dgs.description=f"Leaf switches from AOS blueprint {bp_name}" hb.device_group.add(dgs) # Same thing for spines if len(spinenames) > 0: dgs = DeviceGroupSchema(device_group_name=f"{bp_name}-spines", devices=spinenames) dgs.description=f"Spine switches from AOS blueprint {bp_name}" hb.device_group.add(dgs) # Same thing for superspines if len(spinenames) > 0: dgs = DeviceGroupSchema(device_group_name=f"{bp_name}-superspines", devices=superspinenames) dgs.description=f"Super Spine switches from AOS blueprint {bp_name}" hb.device_group.add(dgs) # Add to Apstra confglet grpc_configlet= { "ref_archs": [ "two_stage_l3clos" ], "generators": [ { "config_style": "junos", "section": "system", "template_text": "system {\n services {\n extension-service {\n request-response {\n grpc {\n clear-text;\n }\n }\n }\n }\n}", "negation_template_text": "", "filename": "" } ], "display_name": "enableoc" } create_oc_configlet=requests.post(f'{aos_url}/api/design/configlets',headers=headers,json=grpc_configlet,verify=False) # Assign configlet 'enableoc' to blueprints print("Assign configlet 'enableoc' to blueprints") for blueprint in blueprintlist.json()['items']: bpid=blueprint['id'] bp_configlet= { "configlet": { "generators": [ { "config_style": "junos", "section": "system", "template_text": "system {\n services {\n extension-service {\n request-response {\n grpc {\n clear-text;\n }\n }\n }\n }\n}", "negation_template_text": "", "filename": "" } ], "display_name": "enableoc" }, "condition": "role in "+ str(list(bp_roles[bpid].keys())) , "label": "enableoc" } apply_oc_configlet=requests.post(f'{aos_url}/api/blueprints/{bpid}/configlets',headers=headers,json=bp_configlet,verify=False) print("Blueprint ID "+str(bpid)+ " == apply ID: "+str(apply_oc_configlet.json())) print ("Done - please login to Healthbot and Apstra for commit changes") exit(0)
#!python # Copyright 2018 Datawire. 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 import copy import subprocess from typing import Any, Callable, Dict, List, Optional, Tuple, Union, TYPE_CHECKING import datetime import functools import json import logging import multiprocessing import os import queue import re import signal import threading import time import uuid import requests import jsonpatch from expiringdict import ExpiringDict import concurrent.futures from pkg_resources import Requirement, resource_filename import clize from clize import Parameter from flask import Flask, render_template, send_from_directory, request, jsonify, Response from flask import json as flask_json import gunicorn.app.base from gunicorn.six import iteritems from ambassador import Config, IR, EnvoyConfig, Diagnostics, Scout, Version from ambassador.utils import SystemInfo, PeriodicTrigger, SavedSecret, load_url_contents from ambassador.utils import SecretHandler, KubewatchSecretHandler, FSSecretHandler from ambassador.config.resourcefetcher import ResourceFetcher from ambassador.diagnostics import EnvoyStats from ambassador.constants import Constants if TYPE_CHECKING: from ambassador.ir.irtlscontext import IRTLSContext __version__ = Version boot_time = datetime.datetime.now() tvars_cache = ExpiringDict(max_len=10, max_age_seconds=60) logging.basicConfig( level=logging.INFO, format="%%(asctime)s diagd %s [P%%(process)dT%%(threadName)s] %%(levelname)s: %%(message)s" % __version__, datefmt="%Y-%m-%d %H:%M:%S" ) # Shut up Werkzeug's standard request logs -- they're just too noisy. logging.getLogger("werkzeug").setLevel(logging.CRITICAL) # Likewise make requests a bit quieter. logging.getLogger("urllib3").setLevel(logging.WARNING) logging.getLogger("requests").setLevel(logging.WARNING) ambassador_targets = { 'mapping': 'https://www.getambassador.io/reference/configuration#mappings', 'module': 'https://www.getambassador.io/reference/configuration#modules', } # envoy_targets = { # 'route': 'https://envoyproxy.github.io/envoy/configuration/http_conn_man/route_config/route.html', # 'cluster': 'https://envoyproxy.github.io/envoy/configuration/cluster_manager/cluster.html', # } def number_of_workers(): return (multiprocessing.cpu_count() * 2) + 1 class DiagApp (Flask): ambex_pid: int kick: Optional[str] estats: EnvoyStats config_path: Optional[str] snapshot_path: str bootstrap_path: str ads_path: str health_checks: bool no_envoy: bool debugging: bool allow_fs_commands: bool report_action_keys: bool verbose: bool notice_path: str logger: logging.Logger aconf: Config ir: Optional[IR] econf: Optional[EnvoyConfig] diag: Optional[Diagnostics] notices: 'Notices' scout: Scout watcher: 'AmbassadorEventWatcher' stats_updater: Optional[PeriodicTrigger] scout_checker: Optional[PeriodicTrigger] last_request_info: Dict[str, int] last_request_time: Optional[datetime.datetime] latest_snapshot: str banner_endpoint: Optional[str] def setup(self, snapshot_path: str, bootstrap_path: str, ads_path: str, config_path: Optional[str], ambex_pid: int, kick: Optional[str], banner_endpoint: Optional[str], k8s=False, do_checks=True, no_envoy=False, reload=False, debug=False, verbose=False, notices=None, validation_retries=5, allow_fs_commands=False, local_scout=False, report_action_keys=False): self.estats = EnvoyStats() self.health_checks = do_checks self.no_envoy = no_envoy self.debugging = reload self.verbose = verbose self.notice_path = notices self.notices = Notices(self.notice_path) self.notices.reset() self.k8s = k8s self.validation_retries = validation_retries self.allow_fs_commands = allow_fs_commands self.local_scout = local_scout self.report_action_keys = report_action_keys self.banner_endpoint = banner_endpoint # This will raise an exception and crash if you pass it a string. That's intentional. self.ambex_pid = int(ambex_pid) self.kick = kick # This feels like overkill. self.logger = logging.getLogger("ambassador.diagd") self.logger.setLevel(logging.INFO) self.kubestatus = KubeStatus() if debug: self.logger.setLevel(logging.DEBUG) logging.getLogger('ambassador').setLevel(logging.DEBUG) self.config_path = config_path self.bootstrap_path = bootstrap_path self.ads_path = ads_path self.snapshot_path = snapshot_path self.ir = None self.econf = None self.diag = None self.stats_updater = None self.scout_checker = None self.last_request_info = {} self.last_request_time = None # self.scout = Scout(update_frequency=datetime.timedelta(seconds=10)) self.scout = Scout(local_only=self.local_scout) def check_scout(self, what: str) -> None: self.watcher.post("SCOUT", (what, self.ir)) # Get the Flask app defined early. Setup happens later. app = DiagApp(__name__, template_folder=resource_filename(Requirement.parse("ambassador"), "templates")) ######## DECORATORS def standard_handler(f): func_name = getattr(f, '__name__', '<anonymous>') @functools.wraps(f) def wrapper(*args, **kwds): reqid = str(uuid.uuid4()).upper() prefix = "%s: %s \"%s %s\"" % (reqid, request.remote_addr, request.method, request.path) app.logger.info("%s START" % prefix) start = datetime.datetime.now() app.logger.debug("%s handler %s" % (prefix, func_name)) # Default to the exception case result_to_log = "server error" status_to_log = 500 result_log_level = logging.ERROR result = Response(result_to_log, status_to_log) try: result = f(*args, reqid=reqid, **kwds) if not isinstance(result, Response): result = Response(f"Invalid handler result {result}", status_to_log) status_to_log = result.status_code if (status_to_log // 100) == 2: result_log_level = logging.INFO result_to_log = "success" else: result_log_level = logging.ERROR result_to_log = "failure" except Exception as e: app.logger.exception(e) end = datetime.datetime.now() ms = int(((end - start).total_seconds() * 1000) + .5) app.logger.log(result_log_level, "%s %dms %d %s" % (prefix, ms, status_to_log, result_to_log)) return result return wrapper ######## UTILITIES class Notices: def __init__(self, local_config_path: str) -> None: self.local_path = local_config_path self.notices: List[Dict[str, str]] = [] def reset(self): local_notices: List[Dict[str, str]] = [] local_data = '' try: local_stream = open(self.local_path, "r") local_data = local_stream.read() local_notices = json.loads(local_data) except OSError: pass except: local_notices.append({ 'level': 'ERROR', 'message': 'bad local notices: %s' % local_data }) self.notices = local_notices # app.logger.info("Notices: after RESET: %s" % json.dumps(self.notices)) def post(self, notice): # app.logger.debug("Notices: POST %s" % notice) self.notices.append(notice) # app.logger.info("Notices: after POST: %s" % json.dumps(self.notices)) def prepend(self, notice): # app.logger.debug("Notices: PREPEND %s" % notice) self.notices.insert(0, notice) # app.logger.info("Notices: after PREPEND: %s" % json.dumps(self.notices)) def extend(self, notices): for notice in notices: self.post(notice) def td_format(td_object): seconds = int(td_object.total_seconds()) periods = [ ('year', 60*60*24*365), ('month', 60*60*24*30), ('day', 60*60*24), ('hour', 60*60), ('minute', 60), ('second', 1) ] strings = [] for period_name, period_seconds in periods: if seconds > period_seconds: period_value, seconds = divmod(seconds, period_seconds) strings.append("%d %s%s" % (period_value, period_name, "" if (period_value == 1) else "s")) formatted = ", ".join(strings) if not formatted: formatted = "0s" return formatted def interval_format(seconds, normal_format, now_message): if seconds >= 1: return normal_format % td_format(datetime.timedelta(seconds=seconds)) else: return now_message def system_info(app): ir = app.ir debug_mode = False if ir: amod = ir.ambassador_module debug_mode = amod.get('debug_mode', False) app.logger.info(f'DEBUG_MODE {debug_mode}') status_dict = {'config failure': [False, 'no configuration loaded']} env_status = getattr(app.watcher, 'env_status', None) if env_status: status_dict = env_status.to_dict() print(f"status_dict {status_dict}") return { "version": __version__, "hostname": SystemInfo.MyHostName, "ambassador_id": Config.ambassador_id, "ambassador_namespace": Config.ambassador_namespace, "single_namespace": Config.single_namespace, "knative_enabled": os.environ.get('AMBASSADOR_KNATIVE_SUPPORT', '').lower() == 'true', "statsd_enabled": os.environ.get('STATSD_ENABLED', '').lower() == 'true', "endpoints_enabled": Config.enable_endpoints, "cluster_id": os.environ.get('AMBASSADOR_CLUSTER_ID', os.environ.get('AMBASSADOR_SCOUT_ID', "00000000-0000-0000-0000-000000000000")), "boot_time": boot_time, "hr_uptime": td_format(datetime.datetime.now() - boot_time), "latest_snapshot": app.latest_snapshot, "env_good": getattr(app.watcher, 'env_good', False), "env_failures": getattr(app.watcher, 'failure_list', [ 'no IR loaded' ]), "env_status": status_dict, "debug_mode": debug_mode } def envoy_status(estats): since_boot = interval_format(estats.time_since_boot(), "%s", "less than a second") since_update = "Never updated" if estats.time_since_update(): since_update = interval_format(estats.time_since_update(), "%s ago", "within the last second") return { "alive": estats.is_alive(), "ready": estats.is_ready(), "uptime": since_boot, "since_update": since_update } def drop_serializer_key(d: Dict[Any, Any]) -> Dict[Any, Any]: """ Delete the "serialization" key (if present) in any dictionary passed in and return that dictionary. This function is intended to be used as the object_hook value for json.load[s]. """ _ = d.pop("serialization", None) return d @app.route('/_internal/v0/ping', methods=[ 'GET' ]) def handle_ping(): return "ACK\n", 200 @app.route('/_internal/v0/update', methods=[ 'POST' ]) def handle_kubewatch_update(): url = request.args.get('url', None) if not url: app.logger.error("error: update requested with no URL") return "error: update requested with no URL\n", 400 app.logger.info("Update requested: kubewatch, %s" % url) status, info = app.watcher.post('CONFIG', ( 'kw', url )) return info, status @app.route('/_internal/v0/watt', methods=[ 'POST' ]) def handle_watt_update(): url = request.args.get('url', None) if not url: app.logger.error("error: watt update requested with no URL") return "error: watt update requested with no URL\n", 400 app.logger.info("Update requested: watt, %s" % url) status, info = app.watcher.post('CONFIG', ( 'watt', url )) return info, status @app.route('/_internal/v0/fs', methods=[ 'POST' ]) def handle_fs(): path = request.args.get('path', None) if not path: app.logger.error("error: update requested with no PATH") return "error: update requested with no PATH\n", 400 app.logger.info("Update requested from %s" % path) status, info = app.watcher.post('CONFIG_FS', path) return info, status @app.route('/_internal/v0/events', methods=[ 'GET' ]) def handle_events(): if not app.local_scout: return 'Local Scout is not enabled\n', 400 event_dump = [ ( x['local_scout_timestamp'], x['mode'], x['action'], x ) for x in app.scout._scout.events ] app.logger.info(f'Event dump {event_dump}') return jsonify(event_dump) @app.route('/ambassador/v0/favicon.ico', methods=[ 'GET' ]) def favicon(): template_path = resource_filename(Requirement.parse("ambassador"), "templates") return send_from_directory(template_path, "favicon.ico") @app.route('/ambassador/v0/check_alive', methods=[ 'GET' ]) def check_alive(): status = envoy_status(app.estats) if status['alive']: return "ambassador liveness check OK (%s)\n" % status['uptime'], 200 else: return "ambassador seems to have died (%s)\n" % status['uptime'], 503 @app.route('/ambassador/v0/check_ready', methods=[ 'GET' ]) def check_ready(): if not (app.ir and app.diag): return "ambassador waiting for config\n", 503 status = envoy_status(app.estats) if status['ready']: return "ambassador readiness check OK (%s)\n" % status['since_update'], 200 else: return "ambassador not ready (%s)\n" % status['since_update'], 503 @app.route('/ambassador/v0/diag/', methods=[ 'GET' ]) @standard_handler def show_overview(reqid=None): app.logger.debug("OV %s - showing overview" % reqid) diag = app.diag if app.verbose: app.logger.debug("OV %s: DIAG" % reqid) app.logger.debug("%s" % json.dumps(diag.as_dict(), sort_keys=True, indent=4)) ov = diag.overview(request, app.estats) if app.verbose: app.logger.debug("OV %s: OV" % reqid) app.logger.debug("%s" % json.dumps(ov, sort_keys=True, indent=4)) app.logger.debug("OV %s: collecting errors" % reqid) ddict = collect_errors_and_notices(request, reqid, "overview", diag) banner_content = None if app.banner_endpoint and app.ir and app.ir.edge_stack_allowed: try: response = requests.get(app.banner_endpoint) if response.status_code == 200: banner_content = response.text except Exception as e: app.logger.error("could not get banner_content: %s" % e) tvars = dict(system=system_info(app), envoy_status=envoy_status(app.estats), loginfo=app.estats.loginfo, notices=app.notices.notices, banner_content=banner_content, **ov, **ddict) patch_client = request.args.get('patch_client', None) if request.args.get('json', None): key = request.args.get('filter', None) if key: return jsonify(tvars.get(key, None)) elif patch_client: # Assume this is the Admin UI. Recursively drop all "serialization" # keys. This avoids leaking secrets and generally makes the # snapshot a lot smaller without losing information that the Admin # UI cares about. We do this below by setting the object_hook # parameter of the json.loads(...) call. # Get the previous full representation cached_tvars_json = tvars_cache.get(patch_client, dict()) # Serialize the tvars into a json-string using the same jsonify Flask serializer, then load the json object response_content = json.loads(flask_json.dumps(tvars), object_hook=drop_serializer_key) # Diff between the previous representation and the current full representation (http://jsonpatch.com/) patch = jsonpatch.make_patch(cached_tvars_json, response_content) # Save the current full representation in memory tvars_cache[patch_client] = response_content # Return only the diff return Response(patch.to_string(), mimetype="application/json") else: return jsonify(tvars) else: app.check_scout("overview") return Response(render_template("overview.html", **tvars)) def collect_errors_and_notices(request, reqid, what: str, diag: Diagnostics) -> Dict: loglevel = request.args.get('loglevel', None) notice = None if loglevel: app.logger.debug("%s %s -- requesting loglevel %s" % (what, reqid, loglevel)) if not app.estats.update_log_levels(time.time(), level=loglevel): notice = { 'level': 'WARNING', 'message': "Could not update log level!" } # else: # return redirect("/ambassador/v0/diag/", code=302) # We need to grab errors and notices from diag.as_dict(), process the errors so # they work for the HTML rendering, and post the notices to app.notices. Then we # return the dict representation that our caller should work with. ddict = diag.as_dict() # app.logger.debug("ddict %s" % json.dumps(ddict, indent=4, sort_keys=True)) derrors = ddict.pop('errors', {}) errors = [] for err_key, err_list in derrors.items(): if err_key == "-global-": err_key = "" for err in err_list: errors.append((err_key, err[ 'error' ])) dnotices = ddict.pop('notices', {}) # Make sure that anything about the loglevel gets folded into this set. if notice: app.notices.prepend(notice) for notice_key, notice_list in dnotices.items(): for notice in notice_list: app.notices.post({'level': 'NOTICE', 'message': "%s: %s" % (notice_key, notice)}) ddict['errors'] = errors return ddict @app.route('/ambassador/v0/diag/<path:source>', methods=[ 'GET' ]) @standard_handler def show_intermediate(source=None, reqid=None): app.logger.debug("SRC %s - getting intermediate for '%s'" % (reqid, source)) diag = app.diag method = request.args.get('method', None) resource = request.args.get('resource', None) result = diag.lookup(request, source, app.estats) if app.verbose: app.logger.debug("RESULT %s" % json.dumps(result, sort_keys=True, indent=4)) ddict = collect_errors_and_notices(request, reqid, "detail %s" % source, diag) tvars = dict(system=system_info(app), envoy_status=envoy_status(app.estats), loginfo=app.estats.loginfo, notices=app.notices.notices, method=method, resource=resource, **result, **ddict) if request.args.get('json', None): key = request.args.get('filter', None) if key: return jsonify(tvars.get(key, None)) else: return jsonify(tvars) else: app.check_scout("detail: %s" % source) return Response(render_template("diag.html", **tvars)) @app.template_filter('sort_by_key') def sort_by_key(objects): return sorted(objects, key=lambda x: x['key']) @app.template_filter('pretty_json') def pretty_json(obj): if isinstance(obj, dict): obj = dict(**obj) keys_to_drop = [ key for key in obj.keys() if key.startswith('_') ] for key in keys_to_drop: del(obj[key]) return json.dumps(obj, indent=4, sort_keys=True) @app.template_filter('sort_clusters_by_service') def sort_clusters_by_service(clusters): return sorted(clusters, key=lambda x: x['service']) # return sorted([ c for c in clusters.values() ], key=lambda x: x['service']) @app.template_filter('source_lookup') def source_lookup(name, sources): app.logger.info("%s => sources %s" % (name, sources)) source = sources.get(name, {}) app.logger.info("%s => source %s" % (name, source)) return source.get('_source', name) @app.route('/metrics', methods=['GET']) @standard_handler def get_prometheus_metrics(*args, **kwargs): return app.estats.get_prometheus_state() def bool_fmt(b: bool) -> str: return 'T' if b else 'F' class StatusInfo: def __init__(self) -> None: self.status = True self.specifics: List[Tuple[bool, str]] = [] def failure(self, message: str) -> None: self.status = False self.specifics.append((False, message)) def OK(self, message: str) -> None: self.specifics.append((True, message)) def to_dict(self) -> Dict[str, Union[bool, List[Tuple[bool, str]]]]: return { 'status': self.status, 'specifics': self.specifics } class SystemStatus: def __init__(self) -> None: self.status: Dict[str, StatusInfo] = {} def failure(self, key: str, message: str) -> None: self.info_for_key(key).failure(message) def OK(self, key: str, message: str) -> None: self.info_for_key(key).OK(message) def info_for_key(self, key) -> StatusInfo: if key not in self.status: self.status[key] = StatusInfo() return self.status[key] def to_dict(self) -> Dict[str, Dict[str, Union[bool, List[Tuple[bool, str]]]]]: return { key: info.to_dict() for key, info in self.status.items() } class KubeStatus: pool: concurrent.futures.ProcessPoolExecutor def __init__(self) -> None: self.live: Dict[str, bool] = {} self.current_status: Dict[str, str] = {} self.pool = concurrent.futures.ProcessPoolExecutor(max_workers=5) def mark_live(self, kind: str, name: str, namespace: str) -> None: key = f"{kind}/{name}.{namespace}" print(f"KubeStatus MASTER {os.getpid()}: mark_live {key}") self.live[key] = True def prune(self) -> None: drop: List[str] = [] for key in self.current_status.keys(): if not self.live.get(key, False): drop.append(key) for key in drop: print(f"KubeStatus MASTER {os.getpid()}: prune {key}") del(self.current_status[key]) self.live = {} def post(self, kind: str, name: str, namespace: str, text: str) -> None: key = f"{kind}/{name}.{namespace}" extant = self.current_status.get(key, None) if extant == text: print(f"KubeStatus MASTER {os.getpid()}: {key} == {text}") else: print(f"KubeStatus MASTER {os.getpid()}: {key} needs {text}") # For now we're going to assume that this works. self.current_status[key] = text f = self.pool.submit(kubestatus_update, kind, name, namespace, text) f.add_done_callback(kubestatus_update_done) def kubestatus_update(kind: str, name: str, namespace: str, text: str) -> str: cmd = [ 'kubestatus', kind, '-f', f'metadata.name={name}', '-n', namespace, '-u', '/dev/fd/0' ] print(f"KubeStatus UPDATE {os.getpid()}: running command: {cmd}") try: rc = subprocess.run(cmd, input=text.encode('utf-8'), timeout=5) if rc.returncode == 0: return f"{name}.{namespace}: update OK" else: return f"{name}.{namespace}: error {rc.returncode}" except subprocess.TimeoutExpired as e: return f"{name}.{namespace}: timed out" def kubestatus_update_done(f: concurrent.futures.Future) -> None: print(f"KubeStatus DONE {os.getpid()}: result {f.result()}") class AmbassadorEventWatcher(threading.Thread): # The key for 'Actions' is chimed - chimed_ok - env_good. This will make more sense # if you read through the _load_ir method. Actions = { 'F-F-F': ( 'unhealthy', True ), # make sure the first chime always gets out 'F-F-T': ( 'now-healthy', True ), # make sure the first chime always gets out 'F-T-F': ( 'now-unhealthy', True ), # this is actually impossible 'F-T-T': ( 'healthy', True ), # this is actually impossible 'T-F-F': ( 'unhealthy', False ), 'T-F-T': ( 'now-healthy', True ), 'T-T-F': ( 'now-unhealthy', True ), 'T-T-T': ( 'update', False ), } def __init__(self, app: DiagApp) -> None: super().__init__(name="AEW", daemon=True) self.app = app self.logger = self.app.logger self.events: queue.Queue = queue.Queue() self.chimed = False # Have we ever sent a chime about the environment? self.last_chime = False # What was the status of our last chime? (starts as False) self.env_good = False # Is our environment currently believed to be OK? self.failure_list: List[str] = [ 'unhealthy at boot' ] # What's making our environment not OK? def post(self, cmd: str, arg: Union[str, Tuple[str, Optional[IR]]]) -> Tuple[int, str]: rqueue: queue.Queue = queue.Queue() self.events.put((cmd, arg, rqueue)) return rqueue.get() def update_estats(self) -> None: self.post('ESTATS', '') def run(self): self.logger.info("starting Scout checker") self.app.scout_checker = PeriodicTrigger(lambda: self.check_scout("checkin"), period=86400) # Yup, one day. self.logger.info("starting event watcher") while True: cmd, arg, rqueue = self.events.get() # self.logger.info("EVENT: %s" % cmd) if cmd == 'ESTATS': # self.logger.info("updating estats") try: self._respond(rqueue, 200, 'updating') self.app.estats.update() except Exception as e: self.logger.error("could not update estats: %s" % e) self.logger.exception(e) self._respond(rqueue, 500, 'Envoy stats update failed') elif cmd == 'CONFIG_FS': try: self.load_config_fs(rqueue, arg) except Exception as e: self.logger.error("could not reconfigure: %s" % e) self.logger.exception(e) self._respond(rqueue, 500, 'configuration from filesystem failed') elif cmd == 'CONFIG': version, url = arg try: if version == 'kw': self.load_config_kubewatch(rqueue, url) elif version == 'watt': self.load_config_watt(rqueue, url) else: raise RuntimeError("config from %s not supported" % version) except Exception as e: self.logger.error("could not reconfigure: %s" % e) self.logger.exception(e) self._respond(rqueue, 500, 'configuration failed') elif cmd == 'SCOUT': try: self._respond(rqueue, 200, 'checking Scout') self.check_scout(*arg) except Exception as e: self.logger.error("could not reconfigure: %s" % e) self.logger.exception(e) self._respond(rqueue, 500, 'scout check failed') else: self.logger.error(f"unknown event type: '{cmd}' '{arg}'") self._respond(rqueue, 400, f"unknown event type '{cmd}' '{arg}'") def _respond(self, rqueue: queue.Queue, status: int, info='') -> None: self.logger.debug("responding to query with %s %s" % (status, info)) rqueue.put((status, info)) def load_config_fs(self, rqueue: queue.Queue, path: str) -> None: self.logger.info("loading configuration from disk: %s" % path) # The "path" here can just be a path, but it can also be a command for testing, # if the user has chosen to allow that. if self.app.allow_fs_commands and (':' in path): pfx, rest = path.split(':', 1) if pfx.lower() == 'cmd': fields = rest.split(':', 1) cmd = fields[0].upper() args = fields[1:] if (len(fields) > 1) else None if cmd.upper() == 'CHIME': self.logger.info('CMD: Chiming') self.chime() self._respond(rqueue, 200, 'Chimed') elif cmd.upper() == 'CHIME_RESET': self.chimed = False self.last_chime = False self.env_good = False self.app.scout.reset_events() self.app.scout.report(mode="boot", action="boot1", no_cache=True) self.logger.info('CMD: Reset chime state') self._respond(rqueue, 200, 'CMD: Reset chime state') elif cmd.upper() == 'SCOUT_CACHE_RESET': self.app.scout.reset_cache_time() self.logger.info('CMD: Reset Scout cache time') self._respond(rqueue, 200, 'CMD: Reset Scout cache time') elif cmd.upper() == 'ENV_OK': self.env_good = True self.failure_list = [] self.logger.info('CMD: Marked environment good') self._respond(rqueue, 200, 'CMD: Marked environment good') elif cmd.upper() == 'ENV_BAD': self.env_good = False self.failure_list = [ 'failure forced' ] self.logger.info('CMD: Marked environment bad') self._respond(rqueue, 200, 'CMD: Marked environment bad') else: self.logger.info(f'CMD: no such command "{cmd}"') self._respond(rqueue, 400, f'CMD: no such command "{cmd}"') return else: self.logger.info(f'CONFIG_FS: invalid prefix "{pfx}"') self._respond(rqueue, 400, f'CONFIG_FS: invalid prefix "{pfx}"') return snapshot = re.sub(r'[^A-Za-z0-9_-]', '_', path) scc = FSSecretHandler(app.logger, path, app.snapshot_path, "0") aconf = Config() fetcher = ResourceFetcher(app.logger, aconf) fetcher.load_from_filesystem(path, k8s=app.k8s, recurse=True) if not fetcher.elements: self.logger.debug("no configuration resources found at %s" % path) # self._respond(rqueue, 204, 'ignoring empty configuration') # return self._load_ir(rqueue, aconf, fetcher, scc, snapshot) def load_config_kubewatch(self, rqueue: queue.Queue, url: str): snapshot = url.split('/')[-1] ss_path = os.path.join(app.snapshot_path, "snapshot-tmp.yaml") self.logger.info("copying configuration: kubewatch, %s to %s" % (url, ss_path)) # Grab the serialization, and save it to disk too. elements: List[str] = [] serialization = load_url_contents(self.logger, "%s/services" % url, stream2=open(ss_path, "w")) if serialization: elements.append(serialization) else: self.logger.debug("no services loaded from snapshot %s" % snapshot) if Config.enable_endpoints: serialization = load_url_contents(self.logger, "%s/endpoints" % url, stream2=open(ss_path, "a")) if serialization: elements.append(serialization) else: self.logger.debug("no endpoints loaded from snapshot %s" % snapshot) serialization = "---\n".join(elements) if not serialization: self.logger.debug("no data loaded from snapshot %s" % snapshot) # We never used to return here. I'm not sure if that's really correct? # self._respond(rqueue, 204, 'ignoring: no data loaded from snapshot %s' % snapshot) # return scc = KubewatchSecretHandler(app.logger, url, app.snapshot_path, snapshot) aconf = Config() fetcher = ResourceFetcher(app.logger, aconf) fetcher.parse_yaml(serialization, k8s=True) if not fetcher.elements: self.logger.debug("no configuration found in snapshot %s" % snapshot) # Don't actually bail here. If they send over a valid config that happens # to have nothing for us, it's still a legit config. # self._respond(rqueue, 204, 'ignoring: no configuration found in snapshot %s' % snapshot) # return self._load_ir(rqueue, aconf, fetcher, scc, snapshot) def load_config_watt(self, rqueue: queue.Queue, url: str): snapshot = url.split('/')[-1] ss_path = os.path.join(app.snapshot_path, "snapshot-tmp.yaml") self.logger.info("copying configuration: watt, %s to %s" % (url, ss_path)) # Grab the serialization, and save it to disk too. serialization = load_url_contents(self.logger, url, stream2=open(ss_path, "w")) if not serialization: self.logger.debug("no data loaded from snapshot %s" % snapshot) # We never used to return here. I'm not sure if that's really correct? # self._respond(rqueue, 204, 'ignoring: no data loaded from snapshot %s' % snapshot) # return # Weirdly, we don't need a special WattSecretHandler: parse_watt knows how to handle # the secrets that watt sends. scc = SecretHandler(app.logger, url, app.snapshot_path, snapshot) aconf = Config() fetcher = ResourceFetcher(app.logger, aconf) if serialization: fetcher.parse_watt(serialization) if not fetcher.elements: self.logger.debug("no configuration found in snapshot %s" % snapshot) # Don't actually bail here. If they send over a valid config that happens # to have nothing for us, it's still a legit config. # self._respond(rqueue, 204, 'ignoring: no configuration found in snapshot %s' % snapshot) # return self._load_ir(rqueue, aconf, fetcher, scc, snapshot) def _load_ir(self, rqueue: queue.Queue, aconf: Config, fetcher: ResourceFetcher, secret_handler: SecretHandler, snapshot: str) -> None: aconf.load_all(fetcher.sorted()) aconf_path = os.path.join(app.snapshot_path, "aconf-tmp.json") open(aconf_path, "w").write(aconf.as_json()) ir = IR(aconf, secret_handler=secret_handler) ir_path = os.path.join(app.snapshot_path, "ir-tmp.json") open(ir_path, "w").write(ir.as_json()) econf = EnvoyConfig.generate(ir, "V2") diag = Diagnostics(ir, econf) bootstrap_config, ads_config = econf.split_config() if not self.validate_envoy_config(config=ads_config, retries=self.app.validation_retries): self.logger.info("no updates were performed due to invalid envoy configuration, continuing with current configuration...") # Don't use app.check_scout; it will deadlock. self.check_scout("attempted bad update") self._respond(rqueue, 500, 'ignoring: invalid Envoy configuration in snapshot %s' % snapshot) return snapcount = int(os.environ.get('AMBASSADOR_SNAPSHOT_COUNT', "4")) snaplist: List[Tuple[str, str]] = [] if snapcount > 0: self.logger.debug("rotating snapshots for snapshot %s" % snapshot) # If snapcount is 4, this range statement becomes range(-4, -1) # which gives [ -4, -3, -2 ], which the list comprehension turns # into [ ( "-3", "-4" ), ( "-2", "-3" ), ( "-1", "-2" ) ]... # which is the list of suffixes to rename to rotate the snapshots. snaplist += [ (str(x+1), str(x)) for x in range(-1 * snapcount, -1) ] # After dealing with that, we need to rotate the current file into -1. snaplist.append(( '', '-1' )) # Whether or not we do any rotation, we need to cycle in the '-tmp' file. snaplist.append(( '-tmp', '' )) for from_suffix, to_suffix in snaplist: for fmt in [ "aconf{}.json", "econf{}.json", "ir{}.json", "snapshot{}.yaml" ]: from_path = os.path.join(app.snapshot_path, fmt.format(from_suffix)) to_path = os.path.join(app.snapshot_path, fmt.format(to_suffix)) try: self.logger.debug("rotate: %s -> %s" % (from_path, to_path)) os.rename(from_path, to_path) except IOError as e: self.logger.debug("skip %s -> %s: %s" % (from_path, to_path, e)) pass except Exception as e: self.logger.debug("could not rename %s -> %s: %s" % (from_path, to_path, e)) app.latest_snapshot = snapshot self.logger.info("saving Envoy configuration for snapshot %s" % snapshot) with open(app.bootstrap_path, "w") as output: output.write(json.dumps(bootstrap_config, sort_keys=True, indent=4)) with open(app.ads_path, "w") as output: output.write(json.dumps(ads_config, sort_keys=True, indent=4)) app.aconf = aconf app.ir = ir app.econf = econf app.diag = diag if app.kick: self.logger.info("running '%s'" % app.kick) os.system(app.kick) elif app.ambex_pid != 0: self.logger.info("notifying PID %d ambex" % app.ambex_pid) os.kill(app.ambex_pid, signal.SIGHUP) # don't worry about TCPMappings yet mappings = app.aconf.get_config('mappings') if mappings: for mapping_name, mapping in mappings.items(): app.kubestatus.mark_live("Mapping", mapping_name, mapping.get('namespace', Config.ambassador_namespace)) app.kubestatus.prune() if app.ir.k8s_status_updates: update_count = 0 for name in app.ir.k8s_status_updates.keys(): update_count += 1 # Strip off any namespace in the name. resource_name = name.split('.', 1)[0] kind, namespace, update = app.ir.k8s_status_updates[name] text = json.dumps(update) self.logger.info(f"K8s status update: {kind} {resource_name}.{namespace}, {text}...") app.kubestatus.post(kind, resource_name, namespace, text) self.logger.info("configuration updated from snapshot %s" % snapshot) self._respond(rqueue, 200, 'configuration updated from snapshot %s' % snapshot) if app.health_checks and not app.stats_updater: app.logger.info("starting Envoy status updater") app.stats_updater = PeriodicTrigger(app.watcher.update_estats, period=5) # Check our environment... self.check_environment() self.chime() def chime(self): # In general, our reports here should be action "update", and they should honor the # Scout cache, but we need to tweak that depending on whether we've done this before # and on whether the environment looks OK. already_chimed = bool_fmt(self.chimed) was_ok = bool_fmt(self.last_chime) now_ok = bool_fmt(self.env_good) # Poor man's state machine... action_key = f'{already_chimed}-{was_ok}-{now_ok}' action, no_cache = AmbassadorEventWatcher.Actions[action_key] self.logger.debug(f'CHIME: {action_key}') chime_args = { 'no_cache': no_cache, 'failures': self.failure_list } if self.app.report_action_keys: chime_args['action_key'] = action_key # Don't use app.check_scout; it will deadlock. self.check_scout(action, **chime_args) # Remember that we have now chimed... self.chimed = True # ...and remember what we sent for that chime. self.last_chime = self.env_good def check_environment(self, ir: Optional[IR]=None) -> None: env_good = True chime_failures = {} env_status = SystemStatus() error_count = 0 tls_count = 0 mapping_count = 0 if not ir: ir = app.ir if not ir: chime_failures['no config loaded'] = True env_good = False else: if not ir.aconf: chime_failures['completely empty config'] = True env_good = False else: for err_key, err_list in ir.aconf.errors.items(): if err_key == "-global-": err_key = "" for err in err_list: error_count += 1 err_text = err['error'] self.app.logger.info(f'error {err_key} {err_text}') if err_text.find('CRD') >= 0: if err_text.find('core') >= 0: chime_failures['core CRDs'] = True env_status.failure("CRDs", "Core CRD type definitions are missing") else: chime_failures['other CRDs'] = True env_status.failure("CRDs", "Resolver CRD type definitions are missing") env_good = False elif err_text.find('TLS') >= 0: chime_failures['TLS errors'] = True env_status.failure('TLS', err_text) env_good = False for context in ir.tls_contexts: if context: tls_count += 1 break for group in ir.groups.values(): for mapping in group.mappings: pfx = mapping.get('prefix', None) name = mapping.get('name', None) if pfx: if not pfx.startswith('/ambassador/v0') or not name.startswith('internal_'): mapping_count += 1 if error_count: env_status.failure('Error check', f'{error_count} total error{'' if (error_count == 1) else 's'} logged') env_good = False else: env_status.OK('Error check', "No errors logged") if tls_count: env_status.OK('TLS', f'{tls_count} TLSContext{' is' if (tls_count == 1) else 's are'} active') else: chime_failures['no TLS contexts'] = True env_status.failure('TLS', "No TLSContexts are active") env_good = False if mapping_count: env_status.OK('Mappings', f'{mapping_count} Mapping{' is' if (mapping_count == 1) else 's are'} active') else: chime_failures['no Mappings'] = True env_status.failure('Mappings', "No Mappings are active") env_good = False failure_list: List[str] = [] if not env_good: failure_list = list(sorted(chime_failures.keys())) self.env_good = env_good self.env_status = env_status self.failure_list = failure_list def check_scout(self, what: str, no_cache: Optional[bool]=False, ir: Optional[IR]=None, failures: Optional[List[str]]=None, action_key: Optional[str]=None) -> None: now = datetime.datetime.now() uptime = now - boot_time hr_uptime = td_format(uptime) if not ir: ir = app.ir self.app.notices.reset() scout_args = { "uptime": int(uptime.total_seconds()), "hr_uptime": hr_uptime } if failures: scout_args['failures'] = failures if action_key: scout_args['action_key'] = action_key if ir: self.app.logger.debug("check_scout: we have an IR") if not os.environ.get("AMBASSADOR_DISABLE_FEATURES", None): self.app.logger.debug("check_scout: including features") feat = ir.features() request_data = app.estats.stats.get('requests', None) if request_data: self.app.logger.debug("check_scout: including requests") for rkey in request_data.keys(): cur = request_data[rkey] prev = app.last_request_info.get(rkey, 0) feat[f'request_{rkey}_count'] = max(cur - prev, 0) lrt = app.last_request_time or boot_time since_lrt = now - lrt elapsed = since_lrt.total_seconds() hr_elapsed = td_format(since_lrt) app.last_request_time = now app.last_request_info = request_data feat['request_elapsed'] = elapsed feat['request_hr_elapsed'] = hr_elapsed scout_args["features"] = feat scout_result = self.app.scout.report(mode="diagd", action=what, no_cache=no_cache, **scout_args) scout_notices = scout_result.pop('notices', []) global_loglevel = self.app.logger.getEffectiveLevel() self.app.logger.debug(f'Scout section: global loglevel {global_loglevel}') for notice in scout_notices: notice_level_name = notice.get('level') or 'INFO' notice_level = logging.getLevelName(notice_level_name) if notice_level >= global_loglevel: self.app.logger.debug(f'Scout section: include {notice}') self.app.notices.post(notice) else: self.app.logger.debug(f'Scout section: skip {notice}') self.app.logger.info("Scout reports %s" % json.dumps(scout_result)) self.app.logger.info("Scout notices: %s" % json.dumps(scout_notices)) self.app.logger.debug("App notices after scout: %s" % json.dumps(app.notices.notices)) def validate_envoy_config(self, config, retries) -> bool: if self.app.no_envoy: self.app.logger.debug("Skipping validation") return True # We want to keep the original config untouched validation_config = copy.deepcopy(config) # Envoy fails to validate with @type field in envoy config, so removing that validation_config.pop('@type') config_json = json.dumps(validation_config, sort_keys=True, indent=4) econf_validation_path = os.path.join(app.snapshot_path, "econf-tmp.json") with open(econf_validation_path, "w") as output: output.write(config_json) command = ['envoy', '--config-path', econf_validation_path, '--mode', 'validate'] odict = { 'exit_code': 0, 'output': '' } # Try to validate the Envoy config. Short circuit and fall through # immediately on concrete success or failure, and retry (up to the # limit) on timeout. timeout = 5 for retry in range(retries): try: odict['output'] = subprocess.check_output(command, stderr=subprocess.STDOUT, timeout=timeout) odict['exit_code'] = 0 break except subprocess.CalledProcessError as e: odict['exit_code'] = e.returncode odict['output'] = e.output break except subprocess.TimeoutExpired as e: odict['exit_code'] = 1 odict['output'] = e.output self.logger.warn("envoy configuration validation timed out after {} seconds{}\n{}", timeout, ', retrying...' if retry < retries - 1 else '', e.output) continue if odict['exit_code'] == 0: self.logger.info("successfully validated the resulting envoy configuration, continuing...") return True try: decoded_error = odict['output'].decode('utf-8') odict['output'] = decoded_error except: pass self.logger.error("{}\ncould not validate the envoy configuration above after {} retries, failed with error \n{}\nAborting update...".format(config_json, retries, odict['output'])) return False class StandaloneApplication(gunicorn.app.base.BaseApplication): def __init__(self, app, options=None): self.options = options or {} self.application = app super(StandaloneApplication, self).__init__() # Boot chime. This is basically the earliest point at which we can consider an Ambassador # to be "running". scout_result = self.application.scout.report(mode="boot", action="boot1", no_cache=True) self.application.logger.info(f'BOOT: Scout result {json.dumps(scout_result)}') def load_config(self): config = dict([(key, value) for key, value in iteritems(self.options) if key in self.cfg.settings and value is not None]) for key, value in iteritems(config): self.cfg.set(key.lower(), value) def load(self): # This is a little weird, but whatever. self.application.watcher = AmbassadorEventWatcher(self.application) self.application.watcher.start() if self.application.config_path: self.application.watcher.post("CONFIG_FS", self.application.config_path) return self.application def _main(snapshot_path=None, bootstrap_path=None, ads_path=None, *, dev_magic=False, config_path=None, ambex_pid=0, kick=None, banner_endpoint="http://127.0.0.1:8500/banner", k8s=False, no_checks=False, no_envoy=False, reload=False, debug=False, verbose=False, workers=None, port=Constants.DIAG_PORT, host='0.0.0.0', notices=None, validation_retries=5, allow_fs_commands=False, local_scout=False, report_action_keys=False): """ Run the diagnostic daemon. :param snapshot_path: Path to directory in which to save configuration snapshots and dynamic secrets :param bootstrap_path: Path to which to write bootstrap Envoy configuration :param ads_path: Path to which to write ADS Envoy configuration :param config_path: Optional configuration path to scan for Ambassador YAML files :param k8s: If True, assume config_path contains Kubernetes resources (only relevant with config_path) :param ambex_pid: Optional PID to signal with HUP after updating Envoy configuration :param kick: Optional command to run after updating Envoy configuration :param banner_endpoint: Optional endpoint of extra banner to include :param no_checks: If True, don't do Envoy-cluster health checking :param no_envoy: If True, don't interact with Envoy at all :param reload: If True, run Flask in debug mode for live reloading :param debug: If True, do debug logging :param dev_magic: If True, override a bunch of things for Datawire dev-loop stuff :param verbose: If True, do really verbose debug logging :param workers: Number of workers; default is based on the number of CPUs present :param host: Interface on which to listen :param port: Port on which to listen :param notices: Optional file to read for local notices :param validation_retries: Number of times to retry Envoy configuration validation after a timeout :param allow_fs_commands: If true, allow CONFIG_FS to support debug/testing commands :param local_scout: Don't talk to remote Scout at all; keep everything purely local :param report_action_keys: Report action keys when chiming """ if dev_magic: # Override the world. os.environ['SCOUT_HOST'] = '127.0.0.1:9999' os.environ['SCOUT_HTTPS'] = 'no' no_checks = True no_envoy = True os.makedirs('/tmp/snapshots', mode=0o755, exist_ok=True) snapshot_path = '/tmp/snapshots' bootstrap_path = '/tmp/boot.json' ads_path = '/tmp/ads.json' port = 9998 allow_fs_commands = True local_scout = True report_action_keys = True if no_envoy: no_checks = True # Create the application itself. app.setup(snapshot_path, bootstrap_path, ads_path, config_path, ambex_pid, kick, banner_endpoint, k8s, not no_checks, no_envoy, reload, debug, verbose, notices, validation_retries, allow_fs_commands, local_scout, report_action_keys) if not workers: workers = number_of_workers() gunicorn_config = { 'bind': '%s:%s' % (host, port), # 'workers': 1, 'threads': workers, } app.logger.info("thread count %d, listening on %s" % (gunicorn_config['threads'], gunicorn_config['bind'])) StandaloneApplication(app, gunicorn_config).run() def main(): clize.run(_main) if __name__ == "__main__": main()
#!python # Copyright 2018 Datawire. 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 import copy import subprocess from typing import Any, Callable, Dict, List, Optional, Tuple, Union, TYPE_CHECKING import datetime import functools import json import logging import multiprocessing import os import queue import re import signal import threading import time import uuid import requests import jsonpatch from expiringdict import ExpiringDict import concurrent.futures from pkg_resources import Requirement, resource_filename import clize from clize import Parameter from flask import Flask, render_template, send_from_directory, request, jsonify, Response from flask import json as flask_json import gunicorn.app.base from gunicorn.six import iteritems from ambassador import Config, IR, EnvoyConfig, Diagnostics, Scout, Version from ambassador.utils import SystemInfo, PeriodicTrigger, SavedSecret, load_url_contents from ambassador.utils import SecretHandler, KubewatchSecretHandler, FSSecretHandler from ambassador.config.resourcefetcher import ResourceFetcher from ambassador.diagnostics import EnvoyStats from ambassador.constants import Constants if TYPE_CHECKING: from ambassador.ir.irtlscontext import IRTLSContext __version__ = Version boot_time = datetime.datetime.now() tvars_cache = ExpiringDict(max_len=10, max_age_seconds=60) logging.basicConfig( level=logging.INFO, format="%%(asctime)s diagd %s [P%%(process)dT%%(threadName)s] %%(levelname)s: %%(message)s" % __version__, datefmt="%Y-%m-%d %H:%M:%S" ) # Shut up Werkzeug's standard request logs -- they're just too noisy. logging.getLogger("werkzeug").setLevel(logging.CRITICAL) # Likewise make requests a bit quieter. logging.getLogger("urllib3").setLevel(logging.WARNING) logging.getLogger("requests").setLevel(logging.WARNING) ambassador_targets = { 'mapping': 'https://www.getambassador.io/reference/configuration#mappings', 'module': 'https://www.getambassador.io/reference/configuration#modules', } # envoy_targets = { # 'route': 'https://envoyproxy.github.io/envoy/configuration/http_conn_man/route_config/route.html', # 'cluster': 'https://envoyproxy.github.io/envoy/configuration/cluster_manager/cluster.html', # } def number_of_workers(): return (multiprocessing.cpu_count() * 2) + 1 class DiagApp (Flask): ambex_pid: int kick: Optional[str] estats: EnvoyStats config_path: Optional[str] snapshot_path: str bootstrap_path: str ads_path: str health_checks: bool no_envoy: bool debugging: bool allow_fs_commands: bool report_action_keys: bool verbose: bool notice_path: str logger: logging.Logger aconf: Config ir: Optional[IR] econf: Optional[EnvoyConfig] diag: Optional[Diagnostics] notices: 'Notices' scout: Scout watcher: 'AmbassadorEventWatcher' stats_updater: Optional[PeriodicTrigger] scout_checker: Optional[PeriodicTrigger] last_request_info: Dict[str, int] last_request_time: Optional[datetime.datetime] latest_snapshot: str banner_endpoint: Optional[str] def setup(self, snapshot_path: str, bootstrap_path: str, ads_path: str, config_path: Optional[str], ambex_pid: int, kick: Optional[str], banner_endpoint: Optional[str], k8s=False, do_checks=True, no_envoy=False, reload=False, debug=False, verbose=False, notices=None, validation_retries=5, allow_fs_commands=False, local_scout=False, report_action_keys=False): self.estats = EnvoyStats() self.health_checks = do_checks self.no_envoy = no_envoy self.debugging = reload self.verbose = verbose self.notice_path = notices self.notices = Notices(self.notice_path) self.notices.reset() self.k8s = k8s self.validation_retries = validation_retries self.allow_fs_commands = allow_fs_commands self.local_scout = local_scout self.report_action_keys = report_action_keys self.banner_endpoint = banner_endpoint # This will raise an exception and crash if you pass it a string. That's intentional. self.ambex_pid = int(ambex_pid) self.kick = kick # This feels like overkill. self.logger = logging.getLogger("ambassador.diagd") self.logger.setLevel(logging.INFO) self.kubestatus = KubeStatus() if debug: self.logger.setLevel(logging.DEBUG) logging.getLogger('ambassador').setLevel(logging.DEBUG) self.config_path = config_path self.bootstrap_path = bootstrap_path self.ads_path = ads_path self.snapshot_path = snapshot_path self.ir = None self.econf = None self.diag = None self.stats_updater = None self.scout_checker = None self.last_request_info = {} self.last_request_time = None # self.scout = Scout(update_frequency=datetime.timedelta(seconds=10)) self.scout = Scout(local_only=self.local_scout) def check_scout(self, what: str) -> None: self.watcher.post("SCOUT", (what, self.ir)) # Get the Flask app defined early. Setup happens later. app = DiagApp(__name__, template_folder=resource_filename(Requirement.parse("ambassador"), "templates")) ######## DECORATORS def standard_handler(f): func_name = getattr(f, '__name__', '<anonymous>') @functools.wraps(f) def wrapper(*args, **kwds): reqid = str(uuid.uuid4()).upper() prefix = "%s: %s \"%s %s\"" % (reqid, request.remote_addr, request.method, request.path) app.logger.info("%s START" % prefix) start = datetime.datetime.now() app.logger.debug("%s handler %s" % (prefix, func_name)) # Default to the exception case result_to_log = "server error" status_to_log = 500 result_log_level = logging.ERROR result = Response(result_to_log, status_to_log) try: result = f(*args, reqid=reqid, **kwds) if not isinstance(result, Response): result = Response(f"Invalid handler result {result}", status_to_log) status_to_log = result.status_code if (status_to_log // 100) == 2: result_log_level = logging.INFO result_to_log = "success" else: result_log_level = logging.ERROR result_to_log = "failure" except Exception as e: app.logger.exception(e) end = datetime.datetime.now() ms = int(((end - start).total_seconds() * 1000) + .5) app.logger.log(result_log_level, "%s %dms %d %s" % (prefix, ms, status_to_log, result_to_log)) return result return wrapper ######## UTILITIES class Notices: def __init__(self, local_config_path: str) -> None: self.local_path = local_config_path self.notices: List[Dict[str, str]] = [] def reset(self): local_notices: List[Dict[str, str]] = [] local_data = '' try: local_stream = open(self.local_path, "r") local_data = local_stream.read() local_notices = json.loads(local_data) except OSError: pass except: local_notices.append({ 'level': 'ERROR', 'message': 'bad local notices: %s' % local_data }) self.notices = local_notices # app.logger.info("Notices: after RESET: %s" % json.dumps(self.notices)) def post(self, notice): # app.logger.debug("Notices: POST %s" % notice) self.notices.append(notice) # app.logger.info("Notices: after POST: %s" % json.dumps(self.notices)) def prepend(self, notice): # app.logger.debug("Notices: PREPEND %s" % notice) self.notices.insert(0, notice) # app.logger.info("Notices: after PREPEND: %s" % json.dumps(self.notices)) def extend(self, notices): for notice in notices: self.post(notice) def td_format(td_object): seconds = int(td_object.total_seconds()) periods = [ ('year', 60*60*24*365), ('month', 60*60*24*30), ('day', 60*60*24), ('hour', 60*60), ('minute', 60), ('second', 1) ] strings = [] for period_name, period_seconds in periods: if seconds > period_seconds: period_value, seconds = divmod(seconds, period_seconds) strings.append("%d %s%s" % (period_value, period_name, "" if (period_value == 1) else "s")) formatted = ", ".join(strings) if not formatted: formatted = "0s" return formatted def interval_format(seconds, normal_format, now_message): if seconds >= 1: return normal_format % td_format(datetime.timedelta(seconds=seconds)) else: return now_message def system_info(app): ir = app.ir debug_mode = False if ir: amod = ir.ambassador_module debug_mode = amod.get('debug_mode', False) app.logger.info(f'DEBUG_MODE {debug_mode}') status_dict = {'config failure': [False, 'no configuration loaded']} env_status = getattr(app.watcher, 'env_status', None) if env_status: status_dict = env_status.to_dict() print(f"status_dict {status_dict}") return { "version": __version__, "hostname": SystemInfo.MyHostName, "ambassador_id": Config.ambassador_id, "ambassador_namespace": Config.ambassador_namespace, "single_namespace": Config.single_namespace, "knative_enabled": os.environ.get('AMBASSADOR_KNATIVE_SUPPORT', '').lower() == 'true', "statsd_enabled": os.environ.get('STATSD_ENABLED', '').lower() == 'true', "endpoints_enabled": Config.enable_endpoints, "cluster_id": os.environ.get('AMBASSADOR_CLUSTER_ID', os.environ.get('AMBASSADOR_SCOUT_ID', "00000000-0000-0000-0000-000000000000")), "boot_time": boot_time, "hr_uptime": td_format(datetime.datetime.now() - boot_time), "latest_snapshot": app.latest_snapshot, "env_good": getattr(app.watcher, 'env_good', False), "env_failures": getattr(app.watcher, 'failure_list', [ 'no IR loaded' ]), "env_status": status_dict, "debug_mode": debug_mode } def envoy_status(estats): since_boot = interval_format(estats.time_since_boot(), "%s", "less than a second") since_update = "Never updated" if estats.time_since_update(): since_update = interval_format(estats.time_since_update(), "%s ago", "within the last second") return { "alive": estats.is_alive(), "ready": estats.is_ready(), "uptime": since_boot, "since_update": since_update } def drop_serializer_key(d: Dict[Any, Any]) -> Dict[Any, Any]: """ Delete the "serialization" key (if present) in any dictionary passed in and return that dictionary. This function is intended to be used as the object_hook value for json.load[s]. """ _ = d.pop("serialization", None) return d @app.route('/_internal/v0/ping', methods=[ 'GET' ]) def handle_ping(): return "ACK\n", 200 @app.route('/_internal/v0/update', methods=[ 'POST' ]) def handle_kubewatch_update(): url = request.args.get('url', None) if not url: app.logger.error("error: update requested with no URL") return "error: update requested with no URL\n", 400 app.logger.info("Update requested: kubewatch, %s" % url) status, info = app.watcher.post('CONFIG', ( 'kw', url )) return info, status @app.route('/_internal/v0/watt', methods=[ 'POST' ]) def handle_watt_update(): url = request.args.get('url', None) if not url: app.logger.error("error: watt update requested with no URL") return "error: watt update requested with no URL\n", 400 app.logger.info("Update requested: watt, %s" % url) status, info = app.watcher.post('CONFIG', ( 'watt', url )) return info, status @app.route('/_internal/v0/fs', methods=[ 'POST' ]) def handle_fs(): path = request.args.get('path', None) if not path: app.logger.error("error: update requested with no PATH") return "error: update requested with no PATH\n", 400 app.logger.info("Update requested from %s" % path) status, info = app.watcher.post('CONFIG_FS', path) return info, status @app.route('/_internal/v0/events', methods=[ 'GET' ]) def handle_events(): if not app.local_scout: return 'Local Scout is not enabled\n', 400 event_dump = [ ( x['local_scout_timestamp'], x['mode'], x['action'], x ) for x in app.scout._scout.events ] app.logger.info(f'Event dump {event_dump}') return jsonify(event_dump) @app.route('/ambassador/v0/favicon.ico', methods=[ 'GET' ]) def favicon(): template_path = resource_filename(Requirement.parse("ambassador"), "templates") return send_from_directory(template_path, "favicon.ico") @app.route('/ambassador/v0/check_alive', methods=[ 'GET' ]) def check_alive(): status = envoy_status(app.estats) if status['alive']: return "ambassador liveness check OK (%s)\n" % status['uptime'], 200 else: return "ambassador seems to have died (%s)\n" % status['uptime'], 503 @app.route('/ambassador/v0/check_ready', methods=[ 'GET' ]) def check_ready(): if not (app.ir and app.diag): return "ambassador waiting for config\n", 503 status = envoy_status(app.estats) if status['ready']: return "ambassador readiness check OK (%s)\n" % status['since_update'], 200 else: return "ambassador not ready (%s)\n" % status['since_update'], 503 @app.route('/ambassador/v0/diag/', methods=[ 'GET' ]) @standard_handler def show_overview(reqid=None): app.logger.debug("OV %s - showing overview" % reqid) diag = app.diag if app.verbose: app.logger.debug("OV %s: DIAG" % reqid) app.logger.debug("%s" % json.dumps(diag.as_dict(), sort_keys=True, indent=4)) ov = diag.overview(request, app.estats) if app.verbose: app.logger.debug("OV %s: OV" % reqid) app.logger.debug("%s" % json.dumps(ov, sort_keys=True, indent=4)) app.logger.debug("OV %s: collecting errors" % reqid) ddict = collect_errors_and_notices(request, reqid, "overview", diag) banner_content = None if app.banner_endpoint and app.ir and app.ir.edge_stack_allowed: try: response = requests.get(app.banner_endpoint) if response.status_code == 200: banner_content = response.text except Exception as e: app.logger.error("could not get banner_content: %s" % e) tvars = dict(system=system_info(app), envoy_status=envoy_status(app.estats), loginfo=app.estats.loginfo, notices=app.notices.notices, banner_content=banner_content, **ov, **ddict) patch_client = request.args.get('patch_client', None) if request.args.get('json', None): key = request.args.get('filter', None) if key: return jsonify(tvars.get(key, None)) elif patch_client: # Assume this is the Admin UI. Recursively drop all "serialization" # keys. This avoids leaking secrets and generally makes the # snapshot a lot smaller without losing information that the Admin # UI cares about. We do this below by setting the object_hook # parameter of the json.loads(...) call. # Get the previous full representation cached_tvars_json = tvars_cache.get(patch_client, dict()) # Serialize the tvars into a json-string using the same jsonify Flask serializer, then load the json object response_content = json.loads(flask_json.dumps(tvars), object_hook=drop_serializer_key) # Diff between the previous representation and the current full representation (http://jsonpatch.com/) patch = jsonpatch.make_patch(cached_tvars_json, response_content) # Save the current full representation in memory tvars_cache[patch_client] = response_content # Return only the diff return Response(patch.to_string(), mimetype="application/json") else: return jsonify(tvars) else: app.check_scout("overview") return Response(render_template("overview.html", **tvars)) def collect_errors_and_notices(request, reqid, what: str, diag: Diagnostics) -> Dict: loglevel = request.args.get('loglevel', None) notice = None if loglevel: app.logger.debug("%s %s -- requesting loglevel %s" % (what, reqid, loglevel)) if not app.estats.update_log_levels(time.time(), level=loglevel): notice = { 'level': 'WARNING', 'message': "Could not update log level!" } # else: # return redirect("/ambassador/v0/diag/", code=302) # We need to grab errors and notices from diag.as_dict(), process the errors so # they work for the HTML rendering, and post the notices to app.notices. Then we # return the dict representation that our caller should work with. ddict = diag.as_dict() # app.logger.debug("ddict %s" % json.dumps(ddict, indent=4, sort_keys=True)) derrors = ddict.pop('errors', {}) errors = [] for err_key, err_list in derrors.items(): if err_key == "-global-": err_key = "" for err in err_list: errors.append((err_key, err[ 'error' ])) dnotices = ddict.pop('notices', {}) # Make sure that anything about the loglevel gets folded into this set. if notice: app.notices.prepend(notice) for notice_key, notice_list in dnotices.items(): for notice in notice_list: app.notices.post({'level': 'NOTICE', 'message': "%s: %s" % (notice_key, notice)}) ddict['errors'] = errors return ddict @app.route('/ambassador/v0/diag/<path:source>', methods=[ 'GET' ]) @standard_handler def show_intermediate(source=None, reqid=None): app.logger.debug("SRC %s - getting intermediate for '%s'" % (reqid, source)) diag = app.diag method = request.args.get('method', None) resource = request.args.get('resource', None) result = diag.lookup(request, source, app.estats) if app.verbose: app.logger.debug("RESULT %s" % json.dumps(result, sort_keys=True, indent=4)) ddict = collect_errors_and_notices(request, reqid, "detail %s" % source, diag) tvars = dict(system=system_info(app), envoy_status=envoy_status(app.estats), loginfo=app.estats.loginfo, notices=app.notices.notices, method=method, resource=resource, **result, **ddict) if request.args.get('json', None): key = request.args.get('filter', None) if key: return jsonify(tvars.get(key, None)) else: return jsonify(tvars) else: app.check_scout("detail: %s" % source) return Response(render_template("diag.html", **tvars)) @app.template_filter('sort_by_key') def sort_by_key(objects): return sorted(objects, key=lambda x: x['key']) @app.template_filter('pretty_json') def pretty_json(obj): if isinstance(obj, dict): obj = dict(**obj) keys_to_drop = [ key for key in obj.keys() if key.startswith('_') ] for key in keys_to_drop: del(obj[key]) return json.dumps(obj, indent=4, sort_keys=True) @app.template_filter('sort_clusters_by_service') def sort_clusters_by_service(clusters): return sorted(clusters, key=lambda x: x['service']) # return sorted([ c for c in clusters.values() ], key=lambda x: x['service']) @app.template_filter('source_lookup') def source_lookup(name, sources): app.logger.info("%s => sources %s" % (name, sources)) source = sources.get(name, {}) app.logger.info("%s => source %s" % (name, source)) return source.get('_source', name) @app.route('/metrics', methods=['GET']) @standard_handler def get_prometheus_metrics(*args, **kwargs): return app.estats.get_prometheus_state() def bool_fmt(b: bool) -> str: return 'T' if b else 'F' class StatusInfo: def __init__(self) -> None: self.status = True self.specifics: List[Tuple[bool, str]] = [] def failure(self, message: str) -> None: self.status = False self.specifics.append((False, message)) def OK(self, message: str) -> None: self.specifics.append((True, message)) def to_dict(self) -> Dict[str, Union[bool, List[Tuple[bool, str]]]]: return { 'status': self.status, 'specifics': self.specifics } class SystemStatus: def __init__(self) -> None: self.status: Dict[str, StatusInfo] = {} def failure(self, key: str, message: str) -> None: self.info_for_key(key).failure(message) def OK(self, key: str, message: str) -> None: self.info_for_key(key).OK(message) def info_for_key(self, key) -> StatusInfo: if key not in self.status: self.status[key] = StatusInfo() return self.status[key] def to_dict(self) -> Dict[str, Dict[str, Union[bool, List[Tuple[bool, str]]]]]: return { key: info.to_dict() for key, info in self.status.items() } class KubeStatus: pool: concurrent.futures.ProcessPoolExecutor def __init__(self) -> None: self.live: Dict[str, bool] = {} self.current_status: Dict[str, str] = {} self.pool = concurrent.futures.ProcessPoolExecutor(max_workers=5) def mark_live(self, kind: str, name: str, namespace: str) -> None: key = f"{kind}/{name}.{namespace}" print(f"KubeStatus MASTER {os.getpid()}: mark_live {key}") self.live[key] = True def prune(self) -> None: drop: List[str] = [] for key in self.current_status.keys(): if not self.live.get(key, False): drop.append(key) for key in drop: print(f"KubeStatus MASTER {os.getpid()}: prune {key}") del(self.current_status[key]) self.live = {} def post(self, kind: str, name: str, namespace: str, text: str) -> None: key = f"{kind}/{name}.{namespace}" extant = self.current_status.get(key, None) if extant == text: print(f"KubeStatus MASTER {os.getpid()}: {key} == {text}") else: print(f"KubeStatus MASTER {os.getpid()}: {key} needs {text}") # For now we're going to assume that this works. self.current_status[key] = text f = self.pool.submit(kubestatus_update, kind, name, namespace, text) f.add_done_callback(kubestatus_update_done) def kubestatus_update(kind: str, name: str, namespace: str, text: str) -> str: cmd = [ 'kubestatus', kind, '-f', f'metadata.name={name}', '-n', namespace, '-u', '/dev/fd/0' ] print(f"KubeStatus UPDATE {os.getpid()}: running command: {cmd}") try: rc = subprocess.run(cmd, input=text.encode('utf-8'), timeout=5) if rc.returncode == 0: return f"{name}.{namespace}: update OK" else: return f"{name}.{namespace}: error {rc.returncode}" except subprocess.TimeoutExpired as e: return f"{name}.{namespace}: timed out" def kubestatus_update_done(f: concurrent.futures.Future) -> None: print(f"KubeStatus DONE {os.getpid()}: result {f.result()}") class AmbassadorEventWatcher(threading.Thread): # The key for 'Actions' is chimed - chimed_ok - env_good. This will make more sense # if you read through the _load_ir method. Actions = { 'F-F-F': ( 'unhealthy', True ), # make sure the first chime always gets out 'F-F-T': ( 'now-healthy', True ), # make sure the first chime always gets out 'F-T-F': ( 'now-unhealthy', True ), # this is actually impossible 'F-T-T': ( 'healthy', True ), # this is actually impossible 'T-F-F': ( 'unhealthy', False ), 'T-F-T': ( 'now-healthy', True ), 'T-T-F': ( 'now-unhealthy', True ), 'T-T-T': ( 'update', False ), } def __init__(self, app: DiagApp) -> None: super().__init__(name="AEW", daemon=True) self.app = app self.logger = self.app.logger self.events: queue.Queue = queue.Queue() self.chimed = False # Have we ever sent a chime about the environment? self.last_chime = False # What was the status of our last chime? (starts as False) self.env_good = False # Is our environment currently believed to be OK? self.failure_list: List[str] = [ 'unhealthy at boot' ] # What's making our environment not OK? def post(self, cmd: str, arg: Union[str, Tuple[str, Optional[IR]]]) -> Tuple[int, str]: rqueue: queue.Queue = queue.Queue() self.events.put((cmd, arg, rqueue)) return rqueue.get() def update_estats(self) -> None: self.post('ESTATS', '') def run(self): self.logger.info("starting Scout checker") self.app.scout_checker = PeriodicTrigger(lambda: self.check_scout("checkin"), period=86400) # Yup, one day. self.logger.info("starting event watcher") while True: cmd, arg, rqueue = self.events.get() # self.logger.info("EVENT: %s" % cmd) if cmd == 'ESTATS': # self.logger.info("updating estats") try: self._respond(rqueue, 200, 'updating') self.app.estats.update() except Exception as e: self.logger.error("could not update estats: %s" % e) self.logger.exception(e) self._respond(rqueue, 500, 'Envoy stats update failed') elif cmd == 'CONFIG_FS': try: self.load_config_fs(rqueue, arg) except Exception as e: self.logger.error("could not reconfigure: %s" % e) self.logger.exception(e) self._respond(rqueue, 500, 'configuration from filesystem failed') elif cmd == 'CONFIG': version, url = arg try: if version == 'kw': self.load_config_kubewatch(rqueue, url) elif version == 'watt': self.load_config_watt(rqueue, url) else: raise RuntimeError("config from %s not supported" % version) except Exception as e: self.logger.error("could not reconfigure: %s" % e) self.logger.exception(e) self._respond(rqueue, 500, 'configuration failed') elif cmd == 'SCOUT': try: self._respond(rqueue, 200, 'checking Scout') self.check_scout(*arg) except Exception as e: self.logger.error("could not reconfigure: %s" % e) self.logger.exception(e) self._respond(rqueue, 500, 'scout check failed') else: self.logger.error(f"unknown event type: '{cmd}' '{arg}'") self._respond(rqueue, 400, f"unknown event type '{cmd}' '{arg}'") def _respond(self, rqueue: queue.Queue, status: int, info='') -> None: self.logger.debug("responding to query with %s %s" % (status, info)) rqueue.put((status, info)) def load_config_fs(self, rqueue: queue.Queue, path: str) -> None: self.logger.info("loading configuration from disk: %s" % path) # The "path" here can just be a path, but it can also be a command for testing, # if the user has chosen to allow that. if self.app.allow_fs_commands and (':' in path): pfx, rest = path.split(':', 1) if pfx.lower() == 'cmd': fields = rest.split(':', 1) cmd = fields[0].upper() args = fields[1:] if (len(fields) > 1) else None if cmd.upper() == 'CHIME': self.logger.info('CMD: Chiming') self.chime() self._respond(rqueue, 200, 'Chimed') elif cmd.upper() == 'CHIME_RESET': self.chimed = False self.last_chime = False self.env_good = False self.app.scout.reset_events() self.app.scout.report(mode="boot", action="boot1", no_cache=True) self.logger.info('CMD: Reset chime state') self._respond(rqueue, 200, 'CMD: Reset chime state') elif cmd.upper() == 'SCOUT_CACHE_RESET': self.app.scout.reset_cache_time() self.logger.info('CMD: Reset Scout cache time') self._respond(rqueue, 200, 'CMD: Reset Scout cache time') elif cmd.upper() == 'ENV_OK': self.env_good = True self.failure_list = [] self.logger.info('CMD: Marked environment good') self._respond(rqueue, 200, 'CMD: Marked environment good') elif cmd.upper() == 'ENV_BAD': self.env_good = False self.failure_list = [ 'failure forced' ] self.logger.info('CMD: Marked environment bad') self._respond(rqueue, 200, 'CMD: Marked environment bad') else: self.logger.info(f'CMD: no such command "{cmd}"') self._respond(rqueue, 400, f'CMD: no such command "{cmd}"') return else: self.logger.info(f'CONFIG_FS: invalid prefix "{pfx}"') self._respond(rqueue, 400, f'CONFIG_FS: invalid prefix "{pfx}"') return snapshot = re.sub(r'[^A-Za-z0-9_-]', '_', path) scc = FSSecretHandler(app.logger, path, app.snapshot_path, "0") aconf = Config() fetcher = ResourceFetcher(app.logger, aconf) fetcher.load_from_filesystem(path, k8s=app.k8s, recurse=True) if not fetcher.elements: self.logger.debug("no configuration resources found at %s" % path) # self._respond(rqueue, 204, 'ignoring empty configuration') # return self._load_ir(rqueue, aconf, fetcher, scc, snapshot) def load_config_kubewatch(self, rqueue: queue.Queue, url: str): snapshot = url.split('/')[-1] ss_path = os.path.join(app.snapshot_path, "snapshot-tmp.yaml") self.logger.info("copying configuration: kubewatch, %s to %s" % (url, ss_path)) # Grab the serialization, and save it to disk too. elements: List[str] = [] serialization = load_url_contents(self.logger, "%s/services" % url, stream2=open(ss_path, "w")) if serialization: elements.append(serialization) else: self.logger.debug("no services loaded from snapshot %s" % snapshot) if Config.enable_endpoints: serialization = load_url_contents(self.logger, "%s/endpoints" % url, stream2=open(ss_path, "a")) if serialization: elements.append(serialization) else: self.logger.debug("no endpoints loaded from snapshot %s" % snapshot) serialization = "---\n".join(elements) if not serialization: self.logger.debug("no data loaded from snapshot %s" % snapshot) # We never used to return here. I'm not sure if that's really correct? # self._respond(rqueue, 204, 'ignoring: no data loaded from snapshot %s' % snapshot) # return scc = KubewatchSecretHandler(app.logger, url, app.snapshot_path, snapshot) aconf = Config() fetcher = ResourceFetcher(app.logger, aconf) fetcher.parse_yaml(serialization, k8s=True) if not fetcher.elements: self.logger.debug("no configuration found in snapshot %s" % snapshot) # Don't actually bail here. If they send over a valid config that happens # to have nothing for us, it's still a legit config. # self._respond(rqueue, 204, 'ignoring: no configuration found in snapshot %s' % snapshot) # return self._load_ir(rqueue, aconf, fetcher, scc, snapshot) def load_config_watt(self, rqueue: queue.Queue, url: str): snapshot = url.split('/')[-1] ss_path = os.path.join(app.snapshot_path, "snapshot-tmp.yaml") self.logger.info("copying configuration: watt, %s to %s" % (url, ss_path)) # Grab the serialization, and save it to disk too. serialization = load_url_contents(self.logger, url, stream2=open(ss_path, "w")) if not serialization: self.logger.debug("no data loaded from snapshot %s" % snapshot) # We never used to return here. I'm not sure if that's really correct? # self._respond(rqueue, 204, 'ignoring: no data loaded from snapshot %s' % snapshot) # return # Weirdly, we don't need a special WattSecretHandler: parse_watt knows how to handle # the secrets that watt sends. scc = SecretHandler(app.logger, url, app.snapshot_path, snapshot) aconf = Config() fetcher = ResourceFetcher(app.logger, aconf) if serialization: fetcher.parse_watt(serialization) if not fetcher.elements: self.logger.debug("no configuration found in snapshot %s" % snapshot) # Don't actually bail here. If they send over a valid config that happens # to have nothing for us, it's still a legit config. # self._respond(rqueue, 204, 'ignoring: no configuration found in snapshot %s' % snapshot) # return self._load_ir(rqueue, aconf, fetcher, scc, snapshot) def _load_ir(self, rqueue: queue.Queue, aconf: Config, fetcher: ResourceFetcher, secret_handler: SecretHandler, snapshot: str) -> None: aconf.load_all(fetcher.sorted()) aconf_path = os.path.join(app.snapshot_path, "aconf-tmp.json") open(aconf_path, "w").write(aconf.as_json()) ir = IR(aconf, secret_handler=secret_handler) ir_path = os.path.join(app.snapshot_path, "ir-tmp.json") open(ir_path, "w").write(ir.as_json()) econf = EnvoyConfig.generate(ir, "V2") diag = Diagnostics(ir, econf) bootstrap_config, ads_config = econf.split_config() if not self.validate_envoy_config(config=ads_config, retries=self.app.validation_retries): self.logger.info("no updates were performed due to invalid envoy configuration, continuing with current configuration...") # Don't use app.check_scout; it will deadlock. self.check_scout("attempted bad update") self._respond(rqueue, 500, 'ignoring: invalid Envoy configuration in snapshot %s' % snapshot) return snapcount = int(os.environ.get('AMBASSADOR_SNAPSHOT_COUNT', "4")) snaplist: List[Tuple[str, str]] = [] if snapcount > 0: self.logger.debug("rotating snapshots for snapshot %s" % snapshot) # If snapcount is 4, this range statement becomes range(-4, -1) # which gives [ -4, -3, -2 ], which the list comprehension turns # into [ ( "-3", "-4" ), ( "-2", "-3" ), ( "-1", "-2" ) ]... # which is the list of suffixes to rename to rotate the snapshots. snaplist += [ (str(x+1), str(x)) for x in range(-1 * snapcount, -1) ] # After dealing with that, we need to rotate the current file into -1. snaplist.append(( '', '-1' )) # Whether or not we do any rotation, we need to cycle in the '-tmp' file. snaplist.append(( '-tmp', '' )) for from_suffix, to_suffix in snaplist: for fmt in [ "aconf{}.json", "econf{}.json", "ir{}.json", "snapshot{}.yaml" ]: from_path = os.path.join(app.snapshot_path, fmt.format(from_suffix)) to_path = os.path.join(app.snapshot_path, fmt.format(to_suffix)) try: self.logger.debug("rotate: %s -> %s" % (from_path, to_path)) os.rename(from_path, to_path) except IOError as e: self.logger.debug("skip %s -> %s: %s" % (from_path, to_path, e)) pass except Exception as e: self.logger.debug("could not rename %s -> %s: %s" % (from_path, to_path, e)) app.latest_snapshot = snapshot self.logger.info("saving Envoy configuration for snapshot %s" % snapshot) with open(app.bootstrap_path, "w") as output: output.write(json.dumps(bootstrap_config, sort_keys=True, indent=4)) with open(app.ads_path, "w") as output: output.write(json.dumps(ads_config, sort_keys=True, indent=4)) app.aconf = aconf app.ir = ir app.econf = econf app.diag = diag if app.kick: self.logger.info("running '%s'" % app.kick) os.system(app.kick) elif app.ambex_pid != 0: self.logger.info("notifying PID %d ambex" % app.ambex_pid) os.kill(app.ambex_pid, signal.SIGHUP) # don't worry about TCPMappings yet mappings = app.aconf.get_config('mappings') if mappings: for mapping_name, mapping in mappings.items(): app.kubestatus.mark_live("Mapping", mapping_name, mapping.get('namespace', Config.ambassador_namespace)) app.kubestatus.prune() if app.ir.k8s_status_updates: update_count = 0 for name in app.ir.k8s_status_updates.keys(): update_count += 1 # Strip off any namespace in the name. resource_name = name.split('.', 1)[0] kind, namespace, update = app.ir.k8s_status_updates[name] text = json.dumps(update) self.logger.info(f"K8s status update: {kind} {resource_name}.{namespace}, {text}...") app.kubestatus.post(kind, resource_name, namespace, text) self.logger.info("configuration updated from snapshot %s" % snapshot) self._respond(rqueue, 200, 'configuration updated from snapshot %s' % snapshot) if app.health_checks and not app.stats_updater: app.logger.info("starting Envoy status updater") app.stats_updater = PeriodicTrigger(app.watcher.update_estats, period=5) # Check our environment... self.check_environment() self.chime() def chime(self): # In general, our reports here should be action "update", and they should honor the # Scout cache, but we need to tweak that depending on whether we've done this before # and on whether the environment looks OK. already_chimed = bool_fmt(self.chimed) was_ok = bool_fmt(self.last_chime) now_ok = bool_fmt(self.env_good) # Poor man's state machine... action_key = f'{already_chimed}-{was_ok}-{now_ok}' action, no_cache = AmbassadorEventWatcher.Actions[action_key] self.logger.debug(f'CHIME: {action_key}') chime_args = { 'no_cache': no_cache, 'failures': self.failure_list } if self.app.report_action_keys: chime_args['action_key'] = action_key # Don't use app.check_scout; it will deadlock. self.check_scout(action, **chime_args) # Remember that we have now chimed... self.chimed = True # ...and remember what we sent for that chime. self.last_chime = self.env_good def check_environment(self, ir: Optional[IR]=None) -> None: env_good = True chime_failures = {} env_status = SystemStatus() error_count = 0 tls_count = 0 mapping_count = 0 if not ir: ir = app.ir if not ir: chime_failures['no config loaded'] = True env_good = False else: if not ir.aconf: chime_failures['completely empty config'] = True env_good = False else: for err_key, err_list in ir.aconf.errors.items(): if err_key == "-global-": err_key = "" for err in err_list: error_count += 1 err_text = err['error'] self.app.logger.info(f'error {err_key} {err_text}') if err_text.find('CRD') >= 0: if err_text.find('core') >= 0: chime_failures['core CRDs'] = True env_status.failure("CRDs", "Core CRD type definitions are missing") else: chime_failures['other CRDs'] = True env_status.failure("CRDs", "Resolver CRD type definitions are missing") env_good = False elif err_text.find('TLS') >= 0: chime_failures['TLS errors'] = True env_status.failure('TLS', err_text) env_good = False for context in ir.tls_contexts: if context: tls_count += 1 break for group in ir.groups.values(): for mapping in group.mappings: pfx = mapping.get('prefix', None) name = mapping.get('name', None) if pfx: if not pfx.startswith('/ambassador/v0') or not name.startswith('internal_'): mapping_count += 1 if error_count: env_status.failure('Error check', f'{error_count} total error{"" if (error_count == 1) else "s"} logged') env_good = False else: env_status.OK('Error check', "No errors logged") if tls_count: env_status.OK('TLS', f'{tls_count} TLSContext{" is" if (tls_count == 1) else "s are"} active') else: chime_failures['no TLS contexts'] = True env_status.failure('TLS', "No TLSContexts are active") env_good = False if mapping_count: env_status.OK('Mappings', f'{mapping_count} Mapping{" is" if (mapping_count == 1) else "s are"} active') else: chime_failures['no Mappings'] = True env_status.failure('Mappings', "No Mappings are active") env_good = False failure_list: List[str] = [] if not env_good: failure_list = list(sorted(chime_failures.keys())) self.env_good = env_good self.env_status = env_status self.failure_list = failure_list def check_scout(self, what: str, no_cache: Optional[bool]=False, ir: Optional[IR]=None, failures: Optional[List[str]]=None, action_key: Optional[str]=None) -> None: now = datetime.datetime.now() uptime = now - boot_time hr_uptime = td_format(uptime) if not ir: ir = app.ir self.app.notices.reset() scout_args = { "uptime": int(uptime.total_seconds()), "hr_uptime": hr_uptime } if failures: scout_args['failures'] = failures if action_key: scout_args['action_key'] = action_key if ir: self.app.logger.debug("check_scout: we have an IR") if not os.environ.get("AMBASSADOR_DISABLE_FEATURES", None): self.app.logger.debug("check_scout: including features") feat = ir.features() request_data = app.estats.stats.get('requests', None) if request_data: self.app.logger.debug("check_scout: including requests") for rkey in request_data.keys(): cur = request_data[rkey] prev = app.last_request_info.get(rkey, 0) feat[f'request_{rkey}_count'] = max(cur - prev, 0) lrt = app.last_request_time or boot_time since_lrt = now - lrt elapsed = since_lrt.total_seconds() hr_elapsed = td_format(since_lrt) app.last_request_time = now app.last_request_info = request_data feat['request_elapsed'] = elapsed feat['request_hr_elapsed'] = hr_elapsed scout_args["features"] = feat scout_result = self.app.scout.report(mode="diagd", action=what, no_cache=no_cache, **scout_args) scout_notices = scout_result.pop('notices', []) global_loglevel = self.app.logger.getEffectiveLevel() self.app.logger.debug(f'Scout section: global loglevel {global_loglevel}') for notice in scout_notices: notice_level_name = notice.get('level') or 'INFO' notice_level = logging.getLevelName(notice_level_name) if notice_level >= global_loglevel: self.app.logger.debug(f'Scout section: include {notice}') self.app.notices.post(notice) else: self.app.logger.debug(f'Scout section: skip {notice}') self.app.logger.info("Scout reports %s" % json.dumps(scout_result)) self.app.logger.info("Scout notices: %s" % json.dumps(scout_notices)) self.app.logger.debug("App notices after scout: %s" % json.dumps(app.notices.notices)) def validate_envoy_config(self, config, retries) -> bool: if self.app.no_envoy: self.app.logger.debug("Skipping validation") return True # We want to keep the original config untouched validation_config = copy.deepcopy(config) # Envoy fails to validate with @type field in envoy config, so removing that validation_config.pop('@type') config_json = json.dumps(validation_config, sort_keys=True, indent=4) econf_validation_path = os.path.join(app.snapshot_path, "econf-tmp.json") with open(econf_validation_path, "w") as output: output.write(config_json) command = ['envoy', '--config-path', econf_validation_path, '--mode', 'validate'] odict = { 'exit_code': 0, 'output': '' } # Try to validate the Envoy config. Short circuit and fall through # immediately on concrete success or failure, and retry (up to the # limit) on timeout. timeout = 5 for retry in range(retries): try: odict['output'] = subprocess.check_output(command, stderr=subprocess.STDOUT, timeout=timeout) odict['exit_code'] = 0 break except subprocess.CalledProcessError as e: odict['exit_code'] = e.returncode odict['output'] = e.output break except subprocess.TimeoutExpired as e: odict['exit_code'] = 1 odict['output'] = e.output self.logger.warn("envoy configuration validation timed out after {} seconds{}\n{}", timeout, ', retrying...' if retry < retries - 1 else '', e.output) continue if odict['exit_code'] == 0: self.logger.info("successfully validated the resulting envoy configuration, continuing...") return True try: decoded_error = odict['output'].decode('utf-8') odict['output'] = decoded_error except: pass self.logger.error("{}\ncould not validate the envoy configuration above after {} retries, failed with error \n{}\nAborting update...".format(config_json, retries, odict['output'])) return False class StandaloneApplication(gunicorn.app.base.BaseApplication): def __init__(self, app, options=None): self.options = options or {} self.application = app super(StandaloneApplication, self).__init__() # Boot chime. This is basically the earliest point at which we can consider an Ambassador # to be "running". scout_result = self.application.scout.report(mode="boot", action="boot1", no_cache=True) self.application.logger.info(f'BOOT: Scout result {json.dumps(scout_result)}') def load_config(self): config = dict([(key, value) for key, value in iteritems(self.options) if key in self.cfg.settings and value is not None]) for key, value in iteritems(config): self.cfg.set(key.lower(), value) def load(self): # This is a little weird, but whatever. self.application.watcher = AmbassadorEventWatcher(self.application) self.application.watcher.start() if self.application.config_path: self.application.watcher.post("CONFIG_FS", self.application.config_path) return self.application def _main(snapshot_path=None, bootstrap_path=None, ads_path=None, *, dev_magic=False, config_path=None, ambex_pid=0, kick=None, banner_endpoint="http://127.0.0.1:8500/banner", k8s=False, no_checks=False, no_envoy=False, reload=False, debug=False, verbose=False, workers=None, port=Constants.DIAG_PORT, host='0.0.0.0', notices=None, validation_retries=5, allow_fs_commands=False, local_scout=False, report_action_keys=False): """ Run the diagnostic daemon. :param snapshot_path: Path to directory in which to save configuration snapshots and dynamic secrets :param bootstrap_path: Path to which to write bootstrap Envoy configuration :param ads_path: Path to which to write ADS Envoy configuration :param config_path: Optional configuration path to scan for Ambassador YAML files :param k8s: If True, assume config_path contains Kubernetes resources (only relevant with config_path) :param ambex_pid: Optional PID to signal with HUP after updating Envoy configuration :param kick: Optional command to run after updating Envoy configuration :param banner_endpoint: Optional endpoint of extra banner to include :param no_checks: If True, don't do Envoy-cluster health checking :param no_envoy: If True, don't interact with Envoy at all :param reload: If True, run Flask in debug mode for live reloading :param debug: If True, do debug logging :param dev_magic: If True, override a bunch of things for Datawire dev-loop stuff :param verbose: If True, do really verbose debug logging :param workers: Number of workers; default is based on the number of CPUs present :param host: Interface on which to listen :param port: Port on which to listen :param notices: Optional file to read for local notices :param validation_retries: Number of times to retry Envoy configuration validation after a timeout :param allow_fs_commands: If true, allow CONFIG_FS to support debug/testing commands :param local_scout: Don't talk to remote Scout at all; keep everything purely local :param report_action_keys: Report action keys when chiming """ if dev_magic: # Override the world. os.environ['SCOUT_HOST'] = '127.0.0.1:9999' os.environ['SCOUT_HTTPS'] = 'no' no_checks = True no_envoy = True os.makedirs('/tmp/snapshots', mode=0o755, exist_ok=True) snapshot_path = '/tmp/snapshots' bootstrap_path = '/tmp/boot.json' ads_path = '/tmp/ads.json' port = 9998 allow_fs_commands = True local_scout = True report_action_keys = True if no_envoy: no_checks = True # Create the application itself. app.setup(snapshot_path, bootstrap_path, ads_path, config_path, ambex_pid, kick, banner_endpoint, k8s, not no_checks, no_envoy, reload, debug, verbose, notices, validation_retries, allow_fs_commands, local_scout, report_action_keys) if not workers: workers = number_of_workers() gunicorn_config = { 'bind': '%s:%s' % (host, port), # 'workers': 1, 'threads': workers, } app.logger.info("thread count %d, listening on %s" % (gunicorn_config['threads'], gunicorn_config['bind'])) StandaloneApplication(app, gunicorn_config).run() def main(): clize.run(_main) if __name__ == "__main__": main()
import json import logging import os from typing import List, Tuple, Dict from antlr4 import * from qualitymeter.gen.javaLabeled.JavaLexer import JavaLexer from qualitymeter.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled from .pullup_field_identification_utils import InfoExtractorListener, get_list_of_files, prettify, print_prettified # A constant denoting output directory __OUT_DIR = r'.\output' # A constant to show if we are going to backup extracted info or not __BACKING = True # A list of all classes held for back-up __allClasses = [] # A dictionary to speed up class look ups using class name __userDefined = {} # A dictionary to store parent classes and their children __parentCache = {} # Declare a name for our logger __logger = None # Create a type object for reports Tuple(field name, access level, identical, same access, *list) T_REPORT = Tuple[str, int, bool, bool, List[Tuple[str, int, bool, int, str, str]], str, str] def initialize(logger: logging.Logger, output_dir, backup=False, log_level=logging.DEBUG): global __logger global __OUT_DIR __logger = logger __OUT_DIR = output_dir if not os.path.isdir(__OUT_DIR): os.makedirs(__OUT_DIR) __logger.setLevel(log_level) __BACKING = backup def __initialize(log_level=logging.DEBUG): """ Initializes an output directory and a logger object """ global __logger if not os.path.isdir(__OUT_DIR): os.makedirs(__OUT_DIR) logging.basicConfig(filename=os.path.join(__OUT_DIR, 'app.log'), filemode='w', format='[%(levelname)s] %(asctime)s | %(message)s') __logger = logging.getLogger() __logger.setLevel(log_level) def analyze(path: str) -> Dict[str, List[T_REPORT]]: """ Analyzes the code base and returns a list of possible "pull-up field" candidates. :param path: Source path of the codebase or address of a backup.json file :return: A dictionary of kind <"parent class name", "refactoring opportunity"> """ # Pull globals in global __userDefined global __parentCache global __allClasses global __logger # Reset the globals __userDefined = {} __parentCache = {} __allClasses = [] # Index and parse the files if it is a directory if os.path.isdir(path): _scrape_directory(path) # Restore from backup if it is a backup elif os.path.basename(path) == 'backup.json': _restore_backup(path) # Log an error otherwise else: __logger.error('Invalid path.') print('Invalid path!') return {} # Discover the opportunities result = {} # Analyze ONLY if the parent is defined within this project for item in __parentCache: if item not in __userDefined: continue tmp = _detect_pullup(__parentCache[item]) tmp.extend(__userDefined[item]) if len(tmp) > 0: result[item] = tmp return result def _scrape_directory(path: str): """ Index all of the .java files and feed it to parser :param path: path to the codebase directory """ global __logger # Get a list of .java files files = get_list_of_files(path) # Logs print(f'Number of files detected: {len(files)}') __logger.info(f'Detected {len(files)} files. Proceeding to parse') print('Proceeding to parse...') # Parse the files and update the globals _parse_files(files) print('Finished parsing. Analyzing the data...') __logger.info('Finished parsing. Analyzing the data...') def _restore_backup(path: str): """ Read the backup file and restore class information. :param path: path to the backup.json """ # Pull globals in global __userDefined global __parentCache global __allClasses global __logger # Load the backup.json into program __logger.info('Reading backup file.') with open(path, 'r', encoding='utf-8') as backup_file: __allClasses = json.load(backup_file) __logger.info('Decoding backups.') # Update globals for item in __allClasses: # Update search cache if item['name'] not in __userDefined: __userDefined[item['name']] = (item['path'], item['package']) else: __logger.warning(f'Duplicate class detected: {item['name']}') # Keep track of classes and their immediate children if 'parent' in item: parent_name = item['parent'] if parent_name in __parentCache: __parentCache[parent_name].append(item) else: __parentCache[parent_name] = [item] __allClasses = [] __logger.info('Backup restored successfully') def _parse_files(file_list: List[str]): """ Parse all of the .java files in the specified directory and all of its subdirectories and updates the global parameters. :param file_list: List of .java file paths """ # Pull globals in global __userDefined global __parentCache global __allClasses global __logger # Initiate a walker walker = ParseTreeWalker() # Iterate over all of the indexed .java files and parse them for file in file_list: tree = None # Generic ANTLR stuff try: input_stream = FileStream(file, encoding="utf-8") lexer = JavaLexer(input_stream) stream = CommonTokenStream(lexer) parser = JavaParserLabeled(stream) tree = parser.compilationUnit() except Exception as e: __logger.error(f'File "{file}" is broken', exc_info=True) continue # Initiate a custom listener extractor = InfoExtractorListener() # Walk the tree using listener walker.walk(extractor, tree) # Update globals for item in extractor.return_indexed_classes(): # Update search cache item['path'] = file if item['name'] not in __userDefined: __userDefined[item['name']] = (item['path'], item['package']) else: __logger.warning(f'Duplicate class detected: {item['name']}') if __BACKING: __allClasses.append(item) # Keep track of classes and their immediate children if 'parent' in item: parent_name = item['parent'] if parent_name in __parentCache: __parentCache[parent_name].append(item) else: __parentCache[parent_name] = [item] if __BACKING: print('Backing up data...') tmp_path = os.path.join(__OUT_DIR, 'backup.json') __logger.info(f'Creating a backup file at "{tmp_path}"') with open(tmp_path, 'w', encoding='utf-8') as file: json.dump(__allClasses, file, indent=2) __logger.info('Finished backing up.') __allClasses = [] def _detect_pullup(classes: List[Dict]) -> List[T_REPORT]: """ Analyze a list of sibling classes and return a pull-up field refactoring opportunity report. :param classes: A list of sibling classes :return: A list of refactoring opportunity reports """ class_count = len(classes) # Keep track of class count # Return an empty list if there are no siblings if class_count == 1: return [] # Calculate the intersection of fields within siblings 1 and 2 duplicates = classes[0]['fields'].keys() & classes[1]['fields'].keys() # Return an empty list if there are no intersection if len(duplicates) == 0: return [] # Keep doing that with the rest of siblings if class_count > 2: index = 2 while index < class_count: duplicates &= classes[index]['fields'].keys() if len(duplicates) == 0: return [] index += 1 # If you reach here, it means that you have a few duplicate entries in your siblings result = [] # Initialize an actual result list # For each of the duplicate fields extract necessary information from classes itself # and add it to the report for item in duplicates: report = [] access_flag = True final_flag = True final_lookbehind = classes[0]['fields'][item][1] access_level = classes[0]['fields'][item][2] for dic in classes: tmp = dic['fields'][item] report.append((dic['name'], tmp[0], tmp[1], tmp[2], dic['path'], dic['package'])) if final_lookbehind != tmp[1]: final_flag = False if access_level != tmp[2]: access_flag = False if tmp[2] < access_level: access_level = tmp[2] # Add the report to results result.append((item, access_level, access_flag & final_flag, access_flag, report)) return result if __name__ == '__main__': __initialize() # Get the code base address from user directory = input('Please enter your code base address:\n') # Analyze the codebase and get the result and then prettify it final_result = prettify(analyze(directory), logger=__logger) # Print prettified suggestions print_prettified(final_result, 0, logger=__logger) # Put the full output in a file out_path = os.path.join(__OUT_DIR, 'output.json') __logger.info(f'Saving the result inside "{out_path}"') with open(out_path, 'w', encoding='utf-8') as file: json.dump(final_result, file, indent=2)
import json import logging import os from typing import List, Tuple, Dict from antlr4 import * from qualitymeter.gen.javaLabeled.JavaLexer import JavaLexer from qualitymeter.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled from .pullup_field_identification_utils import InfoExtractorListener, get_list_of_files, prettify, print_prettified # A constant denoting output directory __OUT_DIR = r'.\output' # A constant to show if we are going to backup extracted info or not __BACKING = True # A list of all classes held for back-up __allClasses = [] # A dictionary to speed up class look ups using class name __userDefined = {} # A dictionary to store parent classes and their children __parentCache = {} # Declare a name for our logger __logger = None # Create a type object for reports Tuple(field name, access level, identical, same access, *list) T_REPORT = Tuple[str, int, bool, bool, List[Tuple[str, int, bool, int, str, str]], str, str] def initialize(logger: logging.Logger, output_dir, backup=False, log_level=logging.DEBUG): global __logger global __OUT_DIR __logger = logger __OUT_DIR = output_dir if not os.path.isdir(__OUT_DIR): os.makedirs(__OUT_DIR) __logger.setLevel(log_level) __BACKING = backup def __initialize(log_level=logging.DEBUG): """ Initializes an output directory and a logger object """ global __logger if not os.path.isdir(__OUT_DIR): os.makedirs(__OUT_DIR) logging.basicConfig(filename=os.path.join(__OUT_DIR, 'app.log'), filemode='w', format='[%(levelname)s] %(asctime)s | %(message)s') __logger = logging.getLogger() __logger.setLevel(log_level) def analyze(path: str) -> Dict[str, List[T_REPORT]]: """ Analyzes the code base and returns a list of possible "pull-up field" candidates. :param path: Source path of the codebase or address of a backup.json file :return: A dictionary of kind <"parent class name", "refactoring opportunity"> """ # Pull globals in global __userDefined global __parentCache global __allClasses global __logger # Reset the globals __userDefined = {} __parentCache = {} __allClasses = [] # Index and parse the files if it is a directory if os.path.isdir(path): _scrape_directory(path) # Restore from backup if it is a backup elif os.path.basename(path) == 'backup.json': _restore_backup(path) # Log an error otherwise else: __logger.error('Invalid path.') print('Invalid path!') return {} # Discover the opportunities result = {} # Analyze ONLY if the parent is defined within this project for item in __parentCache: if item not in __userDefined: continue tmp = _detect_pullup(__parentCache[item]) tmp.extend(__userDefined[item]) if len(tmp) > 0: result[item] = tmp return result def _scrape_directory(path: str): """ Index all of the .java files and feed it to parser :param path: path to the codebase directory """ global __logger # Get a list of .java files files = get_list_of_files(path) # Logs print(f'Number of files detected: {len(files)}') __logger.info(f'Detected {len(files)} files. Proceeding to parse') print('Proceeding to parse...') # Parse the files and update the globals _parse_files(files) print('Finished parsing. Analyzing the data...') __logger.info('Finished parsing. Analyzing the data...') def _restore_backup(path: str): """ Read the backup file and restore class information. :param path: path to the backup.json """ # Pull globals in global __userDefined global __parentCache global __allClasses global __logger # Load the backup.json into program __logger.info('Reading backup file.') with open(path, 'r', encoding='utf-8') as backup_file: __allClasses = json.load(backup_file) __logger.info('Decoding backups.') # Update globals for item in __allClasses: # Update search cache if item['name'] not in __userDefined: __userDefined[item['name']] = (item['path'], item['package']) else: __logger.warning(f'Duplicate class detected: {item["name"]}') # Keep track of classes and their immediate children if 'parent' in item: parent_name = item['parent'] if parent_name in __parentCache: __parentCache[parent_name].append(item) else: __parentCache[parent_name] = [item] __allClasses = [] __logger.info('Backup restored successfully') def _parse_files(file_list: List[str]): """ Parse all of the .java files in the specified directory and all of its subdirectories and updates the global parameters. :param file_list: List of .java file paths """ # Pull globals in global __userDefined global __parentCache global __allClasses global __logger # Initiate a walker walker = ParseTreeWalker() # Iterate over all of the indexed .java files and parse them for file in file_list: tree = None # Generic ANTLR stuff try: input_stream = FileStream(file, encoding="utf-8") lexer = JavaLexer(input_stream) stream = CommonTokenStream(lexer) parser = JavaParserLabeled(stream) tree = parser.compilationUnit() except Exception as e: __logger.error(f'File "{file}" is broken', exc_info=True) continue # Initiate a custom listener extractor = InfoExtractorListener() # Walk the tree using listener walker.walk(extractor, tree) # Update globals for item in extractor.return_indexed_classes(): # Update search cache item['path'] = file if item['name'] not in __userDefined: __userDefined[item['name']] = (item['path'], item['package']) else: __logger.warning(f'Duplicate class detected: {item["name"]}') if __BACKING: __allClasses.append(item) # Keep track of classes and their immediate children if 'parent' in item: parent_name = item['parent'] if parent_name in __parentCache: __parentCache[parent_name].append(item) else: __parentCache[parent_name] = [item] if __BACKING: print('Backing up data...') tmp_path = os.path.join(__OUT_DIR, 'backup.json') __logger.info(f'Creating a backup file at "{tmp_path}"') with open(tmp_path, 'w', encoding='utf-8') as file: json.dump(__allClasses, file, indent=2) __logger.info('Finished backing up.') __allClasses = [] def _detect_pullup(classes: List[Dict]) -> List[T_REPORT]: """ Analyze a list of sibling classes and return a pull-up field refactoring opportunity report. :param classes: A list of sibling classes :return: A list of refactoring opportunity reports """ class_count = len(classes) # Keep track of class count # Return an empty list if there are no siblings if class_count == 1: return [] # Calculate the intersection of fields within siblings 1 and 2 duplicates = classes[0]['fields'].keys() & classes[1]['fields'].keys() # Return an empty list if there are no intersection if len(duplicates) == 0: return [] # Keep doing that with the rest of siblings if class_count > 2: index = 2 while index < class_count: duplicates &= classes[index]['fields'].keys() if len(duplicates) == 0: return [] index += 1 # If you reach here, it means that you have a few duplicate entries in your siblings result = [] # Initialize an actual result list # For each of the duplicate fields extract necessary information from classes itself # and add it to the report for item in duplicates: report = [] access_flag = True final_flag = True final_lookbehind = classes[0]['fields'][item][1] access_level = classes[0]['fields'][item][2] for dic in classes: tmp = dic['fields'][item] report.append((dic['name'], tmp[0], tmp[1], tmp[2], dic['path'], dic['package'])) if final_lookbehind != tmp[1]: final_flag = False if access_level != tmp[2]: access_flag = False if tmp[2] < access_level: access_level = tmp[2] # Add the report to results result.append((item, access_level, access_flag & final_flag, access_flag, report)) return result if __name__ == '__main__': __initialize() # Get the code base address from user directory = input('Please enter your code base address:\n') # Analyze the codebase and get the result and then prettify it final_result = prettify(analyze(directory), logger=__logger) # Print prettified suggestions print_prettified(final_result, 0, logger=__logger) # Put the full output in a file out_path = os.path.join(__OUT_DIR, 'output.json') __logger.info(f'Saving the result inside "{out_path}"') with open(out_path, 'w', encoding='utf-8') as file: json.dump(final_result, file, indent=2)
import torch from apex import amp from math import ceil import random import PIL from tqdm import tqdm #torch.multiprocessing.set_start_method('spawn', force=True) import os,sys,inspect current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) urbangan_dir = os.path.dirname(current_dir) sys.path.insert(0, urbangan_dir) from tools.options import Options from tools.engine import Engine from tools.logger import Logger from tools.utils import get_confusion_matrix from models.segmentor.models.segmentor import Segmentor from models.segmentor_plus.models.segmentor import Segmentor as SegmentorPlus from inplace_abn import InPlaceABN, InPlaceABNSync from data.base_dataset import get_transform #torch.autograd.set_detect_anomaly(True) class SegmentorTrainer: def __init__(self, opt): self.opt = opt["segmentor"] self.tgt_dataset_opt = opt["extra_dataset"] self.all_opt = opt if self.opt.advent or self.opt.duo: assert self.tgt_dataset_opt.dataset is not None print(f"Target pairs for duo/advent training are loaded from [{self.tgt_dataset_opt.dataset}] dataset") def step_model(self, data, global_iteration, log): # try: # import pdb; pdb.set_trace() if self.opt.advent or self.opt.duo: tgt_data = self.next_tgt_batch() self.opt_s.zero_grad() if self.opt.advent: loss, pred_data, delta = self.segmentor(data, tgt_data, global_iteration=global_iteration, log=log, mode='segmentor_advent', hard=False) else: loss, _, delta = self.segmentor(data, global_iteration=global_iteration, log=log, mode='segmentor', hard=False) loss = self.engine.all_reduce_tensor(loss) if self.opt.use_amp: with amp.scale_loss(loss, self.opt_s) as scaled_loss: scaled_loss.backward() else: loss.backward() if self.opt.duo: loss, _, _ = self.segmentor(tgt_data, global_iteration=global_iteration, log=log, mode='segmentor', hard=False, suffix="_for_duo") loss = self.engine.all_reduce_tensor(loss) if self.opt.use_amp: with amp.scale_loss(loss, self.opt_s) as scaled_loss: scaled_loss.backward() else: loss.backward() self.opt_s.step() if self.opt.advent: self.opt_d.zero_grad() loss = self.segmentor({}, pred_data=pred_data, global_iteration=global_iteration, log=log, mode='discriminator_advent') loss = self.engine.all_reduce_tensor(loss) if self.opt.use_amp: with amp.scale_loss(loss, self.opt_d) as scaled_loss: scaled_loss.backward() else: loss.backward() self.opt_d.step() # record delta for synthetic dataset sampler if self.opt.synthetic_dataset and not self.opt.semi: self.train_dataset.set_batch_delta(delta) # print("allocated", torch.cuda.memory_allocated()) # print("cached", torch.cuda.memory_cached()) # torch.cuda.empty_cache() # import pdb; pdb.set_trace() # except: # print("error at iteration", global_iteration) # import pdb; pdb.set_trace() def slide_pred(self, data, window_size): img = data["img"] b, c, h, w = img.shape pred_sem_seg = torch.zeros((b, self.opt.num_semantics, h, w)).cuda() pred_sem_count = torch.zeros((h, w)).cuda() min_overlap = 1 / 3 win_h, win_w = window_size win_rows = int(ceil((h - win_h) / (win_h * (1 - min_overlap)))) + 1 win_cols = int(ceil((w - win_w) / (win_w * (1 - min_overlap)))) + 1 overlap_h = 1 - (h - win_h) / (win_h * (win_rows - 1)) if win_rows > 1 else 0 overlap_w = 1 - (w - win_w) / (win_w * (win_cols - 1)) if win_cols > 1 else 0 stride_h = (1 - overlap_h) * win_h stride_w = (1 - overlap_w) * win_w for row in range(win_rows): for col in range(win_cols): x1 = int(col * stride_w) y1 = int(row * stride_h) x2 = x1 + win_w y2 = y1 + win_h slide_data = {"img": img[:, :, y1:y2, x1:x2]} pred = self.segmentor(slide_data, mode='inference', hard=False) pred_sem_seg[:, :, y1:y2, x1:x2] = pred["sem_seg"] pred_sem_count[y1:y2, x1:x2] += 1 pred_sem_seg /= pred_sem_count return {"sem_seg": pred_sem_seg} def eval_model(self, data, global_iteration, log): if self.opt.slide_eval: pred_seg = self.slide_pred(data, window_size=self.opt.fixed_crop) if self.opt.multi_scale_eval: if self.opt.aspect_ratio > 1: size = [self.opt.fixed_crop[0], int(self.opt.fixed_crop[0] * self.opt.aspect_ratio)] else: size = [int(self.opt.fixed_crop[1] / self.opt.aspect_ratio), self.opt.fixed_crop[1]] small_data = {"img": torch.nn.functional.interpolate(data["img"], size=size, mode="bilinear")} pred_small_seg = self.slide_pred(small_data, window_size=self.opt.fixed_crop) resized_seg = torch.nn.functional.interpolate(pred_small_seg["sem_seg"], size=data["img"].shape[-2:], mode="bilinear") pred_seg["sem_seg"] = (pred_seg["sem_seg"] + resized_seg) / 2 else: pred_seg = self.segmentor(data, global_iteration=global_iteration, mode='inference', hard=False) pred_sem_seg = pred_seg["sem_seg"] sem_index_pred = pred_sem_seg.max(dim=1, keepdim=True)[1] if "flat_seg" in data and not 0 in data["flat_seg"].size(): real_sem_seg = data["flat_seg"].unsqueeze(1).cuda() sem_index_real = data["flat_seg"].unsqueeze(1).cuda() else: real_sem_seg = data["sem_seg"].cuda() sem_index_real = real_sem_seg.max(dim=1, keepdim=True)[1] if log: self.segmentor_on_one_gpu.logger.log_img("segmentor/val/img", data["img"][:16].cpu(), 4, global_iteration, normalize=True, range=(-1, 1)) self.segmentor_on_one_gpu.logger.log_semantic_seg("segmentor/val/real", real_sem_seg[:16].cpu(), 4, global_iteration) self.segmentor_on_one_gpu.logger.log_semantic_seg("segmentor/val/pred", pred_sem_seg[:16].cpu(), 4, global_iteration) confusion_matrix = get_confusion_matrix(sem_index_real, sem_index_pred, self.opt.num_semantics) return confusion_matrix def update_learning_rate(self, global_iteration, min_lr=1e-6): total_iterations = int(self.opt.niter * self.dataset_size / self.opt.batch_size) lr = max(self.opt.lr * ((1 - float(global_iteration) / total_iterations) ** (self.opt.power)), min_lr) if self.opt.plus: self.opt_s.param_groups[0]['lr'] = 0.1 * lr self.opt_s.param_groups[1]['lr'] = lr else: self.opt_s.param_groups[0]['lr'] = lr if self.opt.advent: advent_lr = max(self.opt.advent_lr * ((1 - float(global_iteration) / total_iterations) ** (self.opt.power)), min_lr) self.opt_d.param_groups[0]['lr'] = advent_lr return lr def next_tgt_batch(self): try: return next(self.loader_iter_tgt) except StopIteration: self.loader_iter_tgt = iter(self.target_dataloader) return next(self.loader_iter_tgt) def preprocess_data(self, data): if self.opt.sample_fixed_crop is not None: # new_img = [] # new_sem = [] h = int(self.opt.dim) w = int(self.opt.dim * self.opt.aspect_ratio) h_crop = self.opt.sample_fixed_crop[0] w_crop = self.opt.sample_fixed_crop[1] max_zoom = 1. # self.opt.max_zoom zoom = self.opt.min_zoom + random.random() * (max_zoom - self.opt.min_zoom) h_scaled = int(h * zoom) w_scaled = int(w * zoom) scale = (h_scaled, w_scaled) assert h_scaled - h_crop >= 0 assert w_scaled - w_crop >= 0 top_crop = int(random.random() * (h_scaled - h_crop)) left_crop = int(random.random() * (w_scaled - w_crop)) data["img"] = torch.nn.functional.interpolate(data["img"], size=scale, mode="bilinear") data["img"] = data["img"][:, :, top_crop:top_crop + h_crop, left_crop:left_crop + w_crop] data["sem_seg"] = torch.nn.functional.interpolate(data["sem_seg"], size=scale, mode="nearest") data["sem_seg"] = data["sem_seg"][:, :, top_crop:top_crop + h_crop, left_crop:left_crop + w_crop] return data if self.opt.sample_random_crop: h = int(self.opt.dim) w = int(self.opt.dim * self.opt.aspect_ratio) max_zoom = self.opt.max_zoom zoom = self.opt.min_zoom + random.random() * (max_zoom - self.opt.min_zoom) h_scaled = int(h * zoom) w_scaled = int(w * zoom) scale = (h_scaled, w_scaled) assert h_scaled - h >= 0 assert w_scaled - w >= 0 top_crop = int(random.random() * (h_scaled - h)) left_crop = int(random.random() * (w_scaled - w)) data["img"] = torch.nn.functional.interpolate(data["img"], size=scale, mode="bilinear") data["img"] = data["img"][:, :, top_crop:top_crop + h, left_crop:left_crop + w] data["sem_seg"] = torch.nn.functional.interpolate(data["sem_seg"], size=scale, mode="nearest") data["sem_seg"] = data["sem_seg"][:, :, top_crop:top_crop + h, left_crop:left_crop + w] return data else: return data def run(self): with Engine(self.opt) as engine: self.engine = engine self.train_dataset = engine.create_dataset(self.all_opt, load_seg=True, load_img=True, is_synthetic=self.opt.synthetic_dataset, is_semi=self.opt.semi) self.train_dataloader, self.datasampler = engine.create_dataloader(self.train_dataset, self.opt.batch_size, self.opt.num_workers, is_train=True, is_synthetic=self.opt.synthetic_dataset) if self.opt.advent or self.opt.duo: self.target_dataset = engine.create_dataset(self.tgt_dataset_opt, load_seg=True, load_img=True) self.target_dataloader, self.target_datasampler = engine.create_dataloader(self.target_dataset, self.opt.batch_size, self.opt.num_workers, True) self.loader_iter_tgt = iter(self.target_dataloader) eval_opt = self.opt if self.opt.eval_dataset == "base" else self.tgt_dataset_opt self.valid_dataset = engine.create_dataset(eval_opt, load_seg=True, load_img=True, phase="valid") eval_batch_size = self.opt.force_eval_batch_size if self.opt.force_eval_batch_size is not None else self.opt.batch_size if not self.opt.no_eval: self.valid_dataloader, _ = engine.create_dataloader(self.valid_dataset, eval_batch_size, self.opt.num_workers, False) is_main = self.opt.local_rank == 0 logger = Logger(self.opt) if is_main else None if self.opt.plus: self.segmentor_on_one_gpu = SegmentorPlus(self.opt, is_train=True, is_main=is_main, logger=logger, distributed=self.engine.distributed) else: self.segmentor_on_one_gpu = Segmentor(self.opt, is_train=True, is_main=is_main, logger=logger, distributed=self.engine.distributed) self.opt_s = self.segmentor_on_one_gpu.opt_s self.opt_d = self.segmentor_on_one_gpu.opt_d if self.opt.use_amp: optimizer = [self.opt_s, self.opt_d] if self.opt.advent else self.opt_s self.segmentor_on_one_gpu, optimizer = amp.initialize(self.segmentor_on_one_gpu, optimizer, opt_level=self.opt.amp_level) self.segmentor_on_one_gpu.apply(lambda x: cast_running_stats(x, self.engine.distributed)) self.segmentor = engine.data_parallel(self.segmentor_on_one_gpu) self.segmentor.train() if self.opt.cont_train: start_epoch = self.opt.which_iter else: start_epoch = 0 end_epoch = self.opt.niter self.dataset_size = len(self.train_dataset) * self.opt.batch_size if self.opt.synthetic_dataset else len(self.train_dataset) global_iteration = start_epoch * int(self.dataset_size / self.opt.batch_size) for epoch in range(start_epoch, end_epoch): if self.engine.distributed: self.datasampler.set_epoch(epoch) if self.opt.advent: self.target_datasampler.set_epoch(epoch) for i, data_i in enumerate(self.train_dataloader): global_iteration += 1 log = global_iteration % self.opt.log_freq == 0 and is_main data_i = self.preprocess_data(data_i) self.step_model(data_i, global_iteration, log=log) lr = self.update_learning_rate(global_iteration) if log: self.segmentor_on_one_gpu.logger.log_scalar("segmentor/learning_rate", lr, global_iteration) print(f"[Ep{epoch}/{end_epoch}] Iteration {i + 1:05d}/{int(self.dataset_size / self.opt.batch_size):05d}") # update sampling weights of synthetic dataset if self.opt.synthetic_dataset and not self.opt.semi: self.train_dataset.update_sampler(logger=logger, log=is_main, global_iteration=global_iteration) if self.opt.save_freq > 0 and epoch % self.opt.save_freq == 0 and is_main: self.segmentor_on_one_gpu.save_model(epoch, latest=False) if self.opt.save_latest_freq > 0 and epoch % self.opt.save_latest_freq == 0 and is_main: self.segmentor_on_one_gpu.save_model(epoch, latest=True) if epoch % self.opt.eval_freq == 0 and not self.opt.no_eval: self.segmentor.eval() with torch.no_grad(): confusion_matrix = torch.zeros((self.opt.num_semantics, self.opt.num_semantics)).cuda() for i, data_i in tqdm(enumerate(self.valid_dataloader), desc='eval', total=len(self.valid_dataloader)): confusion_matrix += self.eval_model(data_i, global_iteration, log=i == 0) confusion_matrix = self.engine.all_reduce_tensor(confusion_matrix, norm=False) pos = confusion_matrix.sum(dim=1) res = confusion_matrix.sum(dim=0) tp = torch.diag(confusion_matrix) iou = (tp / torch.max(torch.Tensor([1.0]).to(pos.get_device()), pos + res - tp)) mean_iou = iou.mean() pos_eval = pos[self.opt.eval_idx] res_eval = confusion_matrix[self.opt.eval_idx].sum(dim=0)[self.opt.eval_idx] tp_eval = tp[self.opt.eval_idx] iou_eval = (tp_eval / torch.max(torch.Tensor([1.0]).to(pos.get_device()), pos_eval + res_eval - tp_eval)) mean_iou_eval = iou_eval.mean() if is_main: self.segmentor_on_one_gpu.logger.log_scalar("segmentor/val/mean_iou", mean_iou, global_iteration) self.segmentor_on_one_gpu.logger.log_scalar("segmentor/val/mean_iou_eval", mean_iou_eval, global_iteration) for i in range(len(iou)): self.segmentor_on_one_gpu.logger.log_scalar(f"segmentor/val/iou/{self.opt.semantic_labels[i].replace(" ", "_")}", iou[i], global_iteration) self.segmentor_on_one_gpu.logger.log_confusion_matrix("segmentor/val/confusion_matrix", confusion_matrix.cpu(), global_iteration) self.segmentor.train() print('Training was successfully finished.') def cast_running_stats(m, distributed): ABN = InPlaceABNSync if distributed else InPlaceABN if isinstance(m, ABN): m.running_mean = m.running_mean.float() m.running_var = m.running_var.float() if __name__ == "__main__": opt = Options().parse(load_segmentor=True, load_seg_generator=True, load_img_generator=True, load_extra_dataset=True, save=True) SegmentorTrainer(opt).run()
import torch from apex import amp from math import ceil import random import PIL from tqdm import tqdm #torch.multiprocessing.set_start_method('spawn', force=True) import os,sys,inspect current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) urbangan_dir = os.path.dirname(current_dir) sys.path.insert(0, urbangan_dir) from tools.options import Options from tools.engine import Engine from tools.logger import Logger from tools.utils import get_confusion_matrix from models.segmentor.models.segmentor import Segmentor from models.segmentor_plus.models.segmentor import Segmentor as SegmentorPlus from inplace_abn import InPlaceABN, InPlaceABNSync from data.base_dataset import get_transform #torch.autograd.set_detect_anomaly(True) class SegmentorTrainer: def __init__(self, opt): self.opt = opt["segmentor"] self.tgt_dataset_opt = opt["extra_dataset"] self.all_opt = opt if self.opt.advent or self.opt.duo: assert self.tgt_dataset_opt.dataset is not None print(f"Target pairs for duo/advent training are loaded from [{self.tgt_dataset_opt.dataset}] dataset") def step_model(self, data, global_iteration, log): # try: # import pdb; pdb.set_trace() if self.opt.advent or self.opt.duo: tgt_data = self.next_tgt_batch() self.opt_s.zero_grad() if self.opt.advent: loss, pred_data, delta = self.segmentor(data, tgt_data, global_iteration=global_iteration, log=log, mode='segmentor_advent', hard=False) else: loss, _, delta = self.segmentor(data, global_iteration=global_iteration, log=log, mode='segmentor', hard=False) loss = self.engine.all_reduce_tensor(loss) if self.opt.use_amp: with amp.scale_loss(loss, self.opt_s) as scaled_loss: scaled_loss.backward() else: loss.backward() if self.opt.duo: loss, _, _ = self.segmentor(tgt_data, global_iteration=global_iteration, log=log, mode='segmentor', hard=False, suffix="_for_duo") loss = self.engine.all_reduce_tensor(loss) if self.opt.use_amp: with amp.scale_loss(loss, self.opt_s) as scaled_loss: scaled_loss.backward() else: loss.backward() self.opt_s.step() if self.opt.advent: self.opt_d.zero_grad() loss = self.segmentor({}, pred_data=pred_data, global_iteration=global_iteration, log=log, mode='discriminator_advent') loss = self.engine.all_reduce_tensor(loss) if self.opt.use_amp: with amp.scale_loss(loss, self.opt_d) as scaled_loss: scaled_loss.backward() else: loss.backward() self.opt_d.step() # record delta for synthetic dataset sampler if self.opt.synthetic_dataset and not self.opt.semi: self.train_dataset.set_batch_delta(delta) # print("allocated", torch.cuda.memory_allocated()) # print("cached", torch.cuda.memory_cached()) # torch.cuda.empty_cache() # import pdb; pdb.set_trace() # except: # print("error at iteration", global_iteration) # import pdb; pdb.set_trace() def slide_pred(self, data, window_size): img = data["img"] b, c, h, w = img.shape pred_sem_seg = torch.zeros((b, self.opt.num_semantics, h, w)).cuda() pred_sem_count = torch.zeros((h, w)).cuda() min_overlap = 1 / 3 win_h, win_w = window_size win_rows = int(ceil((h - win_h) / (win_h * (1 - min_overlap)))) + 1 win_cols = int(ceil((w - win_w) / (win_w * (1 - min_overlap)))) + 1 overlap_h = 1 - (h - win_h) / (win_h * (win_rows - 1)) if win_rows > 1 else 0 overlap_w = 1 - (w - win_w) / (win_w * (win_cols - 1)) if win_cols > 1 else 0 stride_h = (1 - overlap_h) * win_h stride_w = (1 - overlap_w) * win_w for row in range(win_rows): for col in range(win_cols): x1 = int(col * stride_w) y1 = int(row * stride_h) x2 = x1 + win_w y2 = y1 + win_h slide_data = {"img": img[:, :, y1:y2, x1:x2]} pred = self.segmentor(slide_data, mode='inference', hard=False) pred_sem_seg[:, :, y1:y2, x1:x2] = pred["sem_seg"] pred_sem_count[y1:y2, x1:x2] += 1 pred_sem_seg /= pred_sem_count return {"sem_seg": pred_sem_seg} def eval_model(self, data, global_iteration, log): if self.opt.slide_eval: pred_seg = self.slide_pred(data, window_size=self.opt.fixed_crop) if self.opt.multi_scale_eval: if self.opt.aspect_ratio > 1: size = [self.opt.fixed_crop[0], int(self.opt.fixed_crop[0] * self.opt.aspect_ratio)] else: size = [int(self.opt.fixed_crop[1] / self.opt.aspect_ratio), self.opt.fixed_crop[1]] small_data = {"img": torch.nn.functional.interpolate(data["img"], size=size, mode="bilinear")} pred_small_seg = self.slide_pred(small_data, window_size=self.opt.fixed_crop) resized_seg = torch.nn.functional.interpolate(pred_small_seg["sem_seg"], size=data["img"].shape[-2:], mode="bilinear") pred_seg["sem_seg"] = (pred_seg["sem_seg"] + resized_seg) / 2 else: pred_seg = self.segmentor(data, global_iteration=global_iteration, mode='inference', hard=False) pred_sem_seg = pred_seg["sem_seg"] sem_index_pred = pred_sem_seg.max(dim=1, keepdim=True)[1] if "flat_seg" in data and not 0 in data["flat_seg"].size(): real_sem_seg = data["flat_seg"].unsqueeze(1).cuda() sem_index_real = data["flat_seg"].unsqueeze(1).cuda() else: real_sem_seg = data["sem_seg"].cuda() sem_index_real = real_sem_seg.max(dim=1, keepdim=True)[1] if log: self.segmentor_on_one_gpu.logger.log_img("segmentor/val/img", data["img"][:16].cpu(), 4, global_iteration, normalize=True, range=(-1, 1)) self.segmentor_on_one_gpu.logger.log_semantic_seg("segmentor/val/real", real_sem_seg[:16].cpu(), 4, global_iteration) self.segmentor_on_one_gpu.logger.log_semantic_seg("segmentor/val/pred", pred_sem_seg[:16].cpu(), 4, global_iteration) confusion_matrix = get_confusion_matrix(sem_index_real, sem_index_pred, self.opt.num_semantics) return confusion_matrix def update_learning_rate(self, global_iteration, min_lr=1e-6): total_iterations = int(self.opt.niter * self.dataset_size / self.opt.batch_size) lr = max(self.opt.lr * ((1 - float(global_iteration) / total_iterations) ** (self.opt.power)), min_lr) if self.opt.plus: self.opt_s.param_groups[0]['lr'] = 0.1 * lr self.opt_s.param_groups[1]['lr'] = lr else: self.opt_s.param_groups[0]['lr'] = lr if self.opt.advent: advent_lr = max(self.opt.advent_lr * ((1 - float(global_iteration) / total_iterations) ** (self.opt.power)), min_lr) self.opt_d.param_groups[0]['lr'] = advent_lr return lr def next_tgt_batch(self): try: return next(self.loader_iter_tgt) except StopIteration: self.loader_iter_tgt = iter(self.target_dataloader) return next(self.loader_iter_tgt) def preprocess_data(self, data): if self.opt.sample_fixed_crop is not None: # new_img = [] # new_sem = [] h = int(self.opt.dim) w = int(self.opt.dim * self.opt.aspect_ratio) h_crop = self.opt.sample_fixed_crop[0] w_crop = self.opt.sample_fixed_crop[1] max_zoom = 1. # self.opt.max_zoom zoom = self.opt.min_zoom + random.random() * (max_zoom - self.opt.min_zoom) h_scaled = int(h * zoom) w_scaled = int(w * zoom) scale = (h_scaled, w_scaled) assert h_scaled - h_crop >= 0 assert w_scaled - w_crop >= 0 top_crop = int(random.random() * (h_scaled - h_crop)) left_crop = int(random.random() * (w_scaled - w_crop)) data["img"] = torch.nn.functional.interpolate(data["img"], size=scale, mode="bilinear") data["img"] = data["img"][:, :, top_crop:top_crop + h_crop, left_crop:left_crop + w_crop] data["sem_seg"] = torch.nn.functional.interpolate(data["sem_seg"], size=scale, mode="nearest") data["sem_seg"] = data["sem_seg"][:, :, top_crop:top_crop + h_crop, left_crop:left_crop + w_crop] return data if self.opt.sample_random_crop: h = int(self.opt.dim) w = int(self.opt.dim * self.opt.aspect_ratio) max_zoom = self.opt.max_zoom zoom = self.opt.min_zoom + random.random() * (max_zoom - self.opt.min_zoom) h_scaled = int(h * zoom) w_scaled = int(w * zoom) scale = (h_scaled, w_scaled) assert h_scaled - h >= 0 assert w_scaled - w >= 0 top_crop = int(random.random() * (h_scaled - h)) left_crop = int(random.random() * (w_scaled - w)) data["img"] = torch.nn.functional.interpolate(data["img"], size=scale, mode="bilinear") data["img"] = data["img"][:, :, top_crop:top_crop + h, left_crop:left_crop + w] data["sem_seg"] = torch.nn.functional.interpolate(data["sem_seg"], size=scale, mode="nearest") data["sem_seg"] = data["sem_seg"][:, :, top_crop:top_crop + h, left_crop:left_crop + w] return data else: return data def run(self): with Engine(self.opt) as engine: self.engine = engine self.train_dataset = engine.create_dataset(self.all_opt, load_seg=True, load_img=True, is_synthetic=self.opt.synthetic_dataset, is_semi=self.opt.semi) self.train_dataloader, self.datasampler = engine.create_dataloader(self.train_dataset, self.opt.batch_size, self.opt.num_workers, is_train=True, is_synthetic=self.opt.synthetic_dataset) if self.opt.advent or self.opt.duo: self.target_dataset = engine.create_dataset(self.tgt_dataset_opt, load_seg=True, load_img=True) self.target_dataloader, self.target_datasampler = engine.create_dataloader(self.target_dataset, self.opt.batch_size, self.opt.num_workers, True) self.loader_iter_tgt = iter(self.target_dataloader) eval_opt = self.opt if self.opt.eval_dataset == "base" else self.tgt_dataset_opt self.valid_dataset = engine.create_dataset(eval_opt, load_seg=True, load_img=True, phase="valid") eval_batch_size = self.opt.force_eval_batch_size if self.opt.force_eval_batch_size is not None else self.opt.batch_size if not self.opt.no_eval: self.valid_dataloader, _ = engine.create_dataloader(self.valid_dataset, eval_batch_size, self.opt.num_workers, False) is_main = self.opt.local_rank == 0 logger = Logger(self.opt) if is_main else None if self.opt.plus: self.segmentor_on_one_gpu = SegmentorPlus(self.opt, is_train=True, is_main=is_main, logger=logger, distributed=self.engine.distributed) else: self.segmentor_on_one_gpu = Segmentor(self.opt, is_train=True, is_main=is_main, logger=logger, distributed=self.engine.distributed) self.opt_s = self.segmentor_on_one_gpu.opt_s self.opt_d = self.segmentor_on_one_gpu.opt_d if self.opt.use_amp: optimizer = [self.opt_s, self.opt_d] if self.opt.advent else self.opt_s self.segmentor_on_one_gpu, optimizer = amp.initialize(self.segmentor_on_one_gpu, optimizer, opt_level=self.opt.amp_level) self.segmentor_on_one_gpu.apply(lambda x: cast_running_stats(x, self.engine.distributed)) self.segmentor = engine.data_parallel(self.segmentor_on_one_gpu) self.segmentor.train() if self.opt.cont_train: start_epoch = self.opt.which_iter else: start_epoch = 0 end_epoch = self.opt.niter self.dataset_size = len(self.train_dataset) * self.opt.batch_size if self.opt.synthetic_dataset else len(self.train_dataset) global_iteration = start_epoch * int(self.dataset_size / self.opt.batch_size) for epoch in range(start_epoch, end_epoch): if self.engine.distributed: self.datasampler.set_epoch(epoch) if self.opt.advent: self.target_datasampler.set_epoch(epoch) for i, data_i in enumerate(self.train_dataloader): global_iteration += 1 log = global_iteration % self.opt.log_freq == 0 and is_main data_i = self.preprocess_data(data_i) self.step_model(data_i, global_iteration, log=log) lr = self.update_learning_rate(global_iteration) if log: self.segmentor_on_one_gpu.logger.log_scalar("segmentor/learning_rate", lr, global_iteration) print(f"[Ep{epoch}/{end_epoch}] Iteration {i + 1:05d}/{int(self.dataset_size / self.opt.batch_size):05d}") # update sampling weights of synthetic dataset if self.opt.synthetic_dataset and not self.opt.semi: self.train_dataset.update_sampler(logger=logger, log=is_main, global_iteration=global_iteration) if self.opt.save_freq > 0 and epoch % self.opt.save_freq == 0 and is_main: self.segmentor_on_one_gpu.save_model(epoch, latest=False) if self.opt.save_latest_freq > 0 and epoch % self.opt.save_latest_freq == 0 and is_main: self.segmentor_on_one_gpu.save_model(epoch, latest=True) if epoch % self.opt.eval_freq == 0 and not self.opt.no_eval: self.segmentor.eval() with torch.no_grad(): confusion_matrix = torch.zeros((self.opt.num_semantics, self.opt.num_semantics)).cuda() for i, data_i in tqdm(enumerate(self.valid_dataloader), desc='eval', total=len(self.valid_dataloader)): confusion_matrix += self.eval_model(data_i, global_iteration, log=i == 0) confusion_matrix = self.engine.all_reduce_tensor(confusion_matrix, norm=False) pos = confusion_matrix.sum(dim=1) res = confusion_matrix.sum(dim=0) tp = torch.diag(confusion_matrix) iou = (tp / torch.max(torch.Tensor([1.0]).to(pos.get_device()), pos + res - tp)) mean_iou = iou.mean() pos_eval = pos[self.opt.eval_idx] res_eval = confusion_matrix[self.opt.eval_idx].sum(dim=0)[self.opt.eval_idx] tp_eval = tp[self.opt.eval_idx] iou_eval = (tp_eval / torch.max(torch.Tensor([1.0]).to(pos.get_device()), pos_eval + res_eval - tp_eval)) mean_iou_eval = iou_eval.mean() if is_main: self.segmentor_on_one_gpu.logger.log_scalar("segmentor/val/mean_iou", mean_iou, global_iteration) self.segmentor_on_one_gpu.logger.log_scalar("segmentor/val/mean_iou_eval", mean_iou_eval, global_iteration) for i in range(len(iou)): self.segmentor_on_one_gpu.logger.log_scalar(f"segmentor/val/iou/{self.opt.semantic_labels[i].replace(' ', '_')}", iou[i], global_iteration) self.segmentor_on_one_gpu.logger.log_confusion_matrix("segmentor/val/confusion_matrix", confusion_matrix.cpu(), global_iteration) self.segmentor.train() print('Training was successfully finished.') def cast_running_stats(m, distributed): ABN = InPlaceABNSync if distributed else InPlaceABN if isinstance(m, ABN): m.running_mean = m.running_mean.float() m.running_var = m.running_var.float() if __name__ == "__main__": opt = Options().parse(load_segmentor=True, load_seg_generator=True, load_img_generator=True, load_extra_dataset=True, save=True) SegmentorTrainer(opt).run()
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import copy import os import warnings from dataclasses import dataclass, field from textwrap import dedent from typing import Callable, Dict, List, Optional, Set, Tuple, Union from omegaconf import DictConfig, OmegaConf from hydra import MissingConfigException from hydra._internal.config_repository import IConfigRepository from hydra.core.config_store import ConfigStore from hydra.core.default_element import ( ConfigDefault, DefaultsTreeNode, GroupDefault, InputDefault, ResultDefault, VirtualRoot, ) from hydra.core.object_type import ObjectType from hydra.core.override_parser.types import Override from hydra.errors import ConfigCompositionException from .deprecation_warning import deprecation_warning cs = ConfigStore.instance() cs.store(name="_dummy_empty_config_", node={}, provider="hydra") @dataclass class Deletion: name: Optional[str] used: bool = field(default=False, compare=False) @dataclass class OverrideMetadata: external_override: bool containing_config_path: Optional[str] = None used: bool = False relative_key: Optional[str] = None @dataclass class Overrides: override_choices: Dict[str, Optional[Union[str, List[str]]]] override_metadata: Dict[str, OverrideMetadata] append_group_defaults: List[GroupDefault] config_overrides: List[Override] known_choices: Dict[str, Optional[str]] known_choices_per_group: Dict[str, Set[str]] deletions: Dict[str, Deletion] def __init__(self, repo: IConfigRepository, overrides_list: List[Override]) -> None: self.override_choices = {} self.override_metadata = {} self.append_group_defaults = [] self.config_overrides = [] self.deletions = {} self.known_choices = {} self.known_choices_per_group = {} for override in overrides_list: if override.is_sweep_override(): continue is_group = repo.group_exists(override.key_or_group) value = override.value() is_dict = isinstance(override.value(), dict) if is_dict or not is_group: self.config_overrides.append(override) elif override.is_force_add(): # This could probably be made to work if there is a compelling use case. raise ConfigCompositionException( f"force-add of config groups is not supported: '{override.input_line}'" ) elif override.is_delete(): key = override.get_key_element()[1:] value = override.value() if value is not None and not isinstance(value, str): raise ValueError( f"Config group override deletion value must be a string : {override}" ) self.deletions[key] = Deletion(name=value) elif not isinstance(value, (str, list)): raise ValueError( f"Config group override must be a string or a list. Got {type(value).__name__}" ) elif override.is_add(): self.append_group_defaults.append( GroupDefault( group=override.key_or_group, package=override.package, value=value, external_append=True, ) ) else: key = override.get_key_element() self.override_choices[key] = value self.override_metadata[key] = OverrideMetadata(external_override=True) def add_override(self, parent_config_path: str, default: GroupDefault) -> None: assert default.override key = default.get_override_key() if key not in self.override_choices: self.override_choices[key] = default.value self.override_metadata[key] = OverrideMetadata( external_override=False, containing_config_path=parent_config_path, relative_key=default.get_relative_override_key(), ) def is_overridden(self, default: InputDefault) -> bool: if isinstance(default, GroupDefault): return default.get_override_key() in self.override_choices return False def override_default_option(self, default: GroupDefault) -> None: key = default.get_override_key() if key in self.override_choices: if isinstance(default, GroupDefault): default.value = self.override_choices[key] default.config_name_overridden = True self.override_metadata[key].used = True def ensure_overrides_used(self) -> None: for key, meta in self.override_metadata.items(): if not meta.used: group = key.split("@")[0] choices = ( self.known_choices_per_group[group] if group in self.known_choices_per_group else set() ) if len(choices) > 1: msg = ( f"Could not override '{key}'." f"\nDid you mean to override one of {", ".join(sorted(list(choices)))}?" ) elif len(choices) == 1: msg = ( f"Could not override '{key}'." f"\nDid you mean to override {copy.copy(choices).pop()}?" ) elif len(choices) == 0: msg = f"Could not override '{key}'. No match in the defaults list." else: assert False if meta.containing_config_path is not None: msg = f"In '{meta.containing_config_path}': {msg}" if meta.external_override: msg += f"\nTo append to your default list use +{key}={self.override_choices[key]}" raise ConfigCompositionException(msg) def ensure_deletions_used(self) -> None: for key, deletion in self.deletions.items(): if not deletion.used: desc = f"{key}={deletion.name}" if deletion.name is not None else key msg = f"Could not delete '{desc}'. No match in the defaults list" raise ConfigCompositionException(msg) def set_known_choice(self, default: InputDefault) -> None: if isinstance(default, GroupDefault): key = default.get_override_key() if key not in self.known_choices: self.known_choices[key] = default.get_name() else: prev = self.known_choices[key] if default.get_name() != prev: raise ConfigCompositionException( f"Multiple values for {key}." f" To override a value use 'override {key}: {prev}'" ) group = default.get_group_path() if group not in self.known_choices_per_group: self.known_choices_per_group[group] = set() self.known_choices_per_group[group].add(key) def is_deleted(self, default: InputDefault) -> bool: if not isinstance(default, GroupDefault): return False key = default.get_override_key() if key in self.deletions: deletion = self.deletions[key] if deletion.name is None: return True else: return deletion.name == default.get_name() return False def delete(self, default: InputDefault) -> None: assert isinstance(default, GroupDefault) default.deleted = True key = default.get_override_key() self.deletions[key].used = True @dataclass class DefaultsList: defaults: List[ResultDefault] defaults_tree: DefaultsTreeNode config_overrides: List[Override] overrides: Overrides def _validate_self( containing_node: InputDefault, defaults: List[InputDefault], has_config_content: bool, ) -> bool: # check that self is present only once has_self = False has_non_override = False for d in defaults: if not d.is_override(): has_non_override = True if d.is_self(): if has_self: raise ConfigCompositionException( f"Duplicate _self_ defined in {containing_node.get_config_path()}" ) has_self = True if not has_self and has_non_override or len(defaults) == 0: # This check is here to make the migration from Hydra 1.0 to Hydra 1.1 smoother and should be removed in 1.2 # The warning should be removed in 1.2 if containing_node.primary and has_config_content and has_non_override: msg = ( f"In '{containing_node.get_config_path()}': Defaults list is missing `_self_`. " f"See https://hydra.cc/docs/upgrades/1.0_to_1.1/default_composition_order for more information" ) if os.environ.get("SELF_WARNING_AS_ERROR") == "1": raise ConfigCompositionException(msg) warnings.warn(msg, UserWarning) defaults.append(ConfigDefault(path="_self_")) return not has_self def update_package_header(repo: IConfigRepository, node: InputDefault) -> None: if node.is_missing(): return # This loads the same config loaded in _create_defaults_tree # To avoid loading it twice, the repo implementation is expected to cache loaded configs loaded = repo.load_config(config_path=node.get_config_path()) if loaded is not None: node.set_package_header(loaded.header["package"]) def _expand_virtual_root( repo: IConfigRepository, root: DefaultsTreeNode, overrides: Overrides, skip_missing: bool, ) -> DefaultsTreeNode: children: List[Union[DefaultsTreeNode, InputDefault]] = [] assert root.children is not None for d in reversed(root.children): assert isinstance(d, InputDefault) new_root = DefaultsTreeNode(node=d, parent=root) d.update_parent("", "") subtree = _create_defaults_tree_impl( repo=repo, root=new_root, is_root_config=d.primary, skip_missing=skip_missing, interpolated_subtree=False, overrides=overrides, ) if subtree.children is None: children.append(d) else: children.append(subtree) if len(children) > 0: root.children = list(reversed(children)) return root def _check_not_missing( repo: IConfigRepository, default: InputDefault, skip_missing: bool, ) -> bool: path = default.get_config_path() if path.endswith("???"): if skip_missing: return True if isinstance(default, GroupDefault): group_path = default.get_group_path() options = repo.get_group_options( group_path, results_filter=ObjectType.CONFIG, ) opt_list = "\n".join(["\t" + x for x in options]) msg = dedent( f"""\ You must specify '{group_path}', e.g, {group_path}=<OPTION> Available options: """ ) raise ConfigCompositionException(msg + opt_list) elif isinstance(default, ConfigDefault): raise ValueError(f"Missing ConfigDefault is not supported : {path}") else: assert False return False def _create_interpolation_map( overrides: Overrides, defaults_list: List[InputDefault], self_added: bool, ) -> DictConfig: known_choices = OmegaConf.create(overrides.known_choices) known_choices.defaults = [] for d in defaults_list: if self_added and d.is_self(): continue if isinstance(d, ConfigDefault): known_choices.defaults.append(d.get_config_path()) elif isinstance(d, GroupDefault): known_choices.defaults.append({d.get_override_key(): d.value}) return known_choices def _create_defaults_tree( repo: IConfigRepository, root: DefaultsTreeNode, is_root_config: bool, skip_missing: bool, interpolated_subtree: bool, overrides: Overrides, ) -> DefaultsTreeNode: ret = _create_defaults_tree_impl( repo=repo, root=root, is_root_config=is_root_config, skip_missing=skip_missing, interpolated_subtree=interpolated_subtree, overrides=overrides, ) return ret def _update_overrides( defaults_list: List[InputDefault], overrides: Overrides, parent: InputDefault, interpolated_subtree: bool, ) -> None: seen_override = False last_override_seen = None for d in defaults_list: if d.is_self(): continue d.update_parent(parent.get_group_path(), parent.get_final_package()) legacy_hydra_override = False if isinstance(d, GroupDefault): assert d.group is not None legacy_hydra_override = not d.is_override() and d.group.startswith("hydra/") if seen_override and not ( d.is_override() or d.is_external_append() or legacy_hydra_override ): assert isinstance(last_override_seen, GroupDefault) pcp = parent.get_config_path() okey = last_override_seen.get_override_key() oval = last_override_seen.get_name() raise ConfigCompositionException( dedent( f"""\ In {pcp}: Override '{okey} : {oval}' is defined before '{d.get_override_key()}: {d.get_name()}'. Overrides must be at the end of the defaults list""" ) ) if isinstance(d, GroupDefault): if legacy_hydra_override: # DEPRECATED: remove in 1.2 d.override = True url = "https://hydra.cc/docs/next/upgrades/1.0_to_1.1/defaults_list_override" msg = dedent( f"""\ In {parent.get_config_path()}: Invalid overriding of {d.group}: Default list overrides requires 'override' keyword. See {url} for more information. """ ) deprecation_warning(msg) if d.override: if not legacy_hydra_override: seen_override = True last_override_seen = d if interpolated_subtree: # Since interpolations are deferred for until all the config groups are already set, # Their subtree may not contain config group overrides raise ConfigCompositionException( dedent( f"""\ {parent.get_config_path()}: Default List Overrides are not allowed in the subtree of an in interpolated config group (override {d.get_override_key()}={d.get_name()}). """ ) ) overrides.add_override(parent.get_config_path(), d) def _has_config_content(cfg: DictConfig) -> bool: if cfg._is_none() or cfg._is_missing(): return False for key in cfg.keys(): if not OmegaConf.is_missing(cfg, key): return True return False def _create_defaults_tree_impl( repo: IConfigRepository, root: DefaultsTreeNode, is_root_config: bool, skip_missing: bool, interpolated_subtree: bool, overrides: Overrides, ) -> DefaultsTreeNode: parent = root.node children: List[Union[InputDefault, DefaultsTreeNode]] = [] if parent.is_virtual(): if is_root_config: return _expand_virtual_root(repo, root, overrides, skip_missing) else: return root if is_root_config: root.node.update_parent("", "") if not repo.config_exists(root.node.get_config_path()): config_not_found_error(repo=repo, tree=root) update_package_header(repo=repo, node=parent) if overrides.is_deleted(parent): overrides.delete(parent) return root overrides.set_known_choice(parent) if parent.get_name() is None: return root if _check_not_missing(repo=repo, default=parent, skip_missing=skip_missing): return root path = parent.get_config_path() loaded = repo.load_config(config_path=path) if loaded is None: if parent.is_optional(): assert isinstance(parent, (GroupDefault, ConfigDefault)) parent.deleted = True return root config_not_found_error(repo=repo, tree=root) assert loaded is not None defaults_list = copy.deepcopy(loaded.defaults_list) if defaults_list is None: defaults_list = [] self_added = False if ( len(defaults_list) > 0 or is_root_config and len(overrides.append_group_defaults) > 0 ): has_config_content = isinstance( loaded.config, DictConfig ) and _has_config_content(loaded.config) self_added = _validate_self( containing_node=parent, defaults=defaults_list, has_config_content=has_config_content, ) if is_root_config: defaults_list.extend(overrides.append_group_defaults) _update_overrides(defaults_list, overrides, parent, interpolated_subtree) def add_child( child_list: List[Union[InputDefault, DefaultsTreeNode]], new_root_: DefaultsTreeNode, ) -> None: subtree_ = _create_defaults_tree_impl( repo=repo, root=new_root_, is_root_config=False, interpolated_subtree=interpolated_subtree, skip_missing=skip_missing, overrides=overrides, ) if subtree_.children is None: child_list.append(new_root_.node) else: child_list.append(subtree_) for d in reversed(defaults_list): if d.is_self(): d.update_parent(root.node.parent_base_dir, root.node.get_package()) children.append(d) else: if d.is_override(): continue d.update_parent(parent.get_group_path(), parent.get_final_package()) if overrides.is_overridden(d): assert isinstance(d, GroupDefault) overrides.override_default_option(d) if isinstance(d, GroupDefault) and d.is_options(): # overriding may change from options to name if d.is_options(): for item in reversed(d.get_options()): if "${" in item: raise ConfigCompositionException( f"In '{path}': Defaults List interpolation is not supported in options list items" ) assert d.group is not None node = ConfigDefault( path=d.group + "/" + item, package=d.package, optional=d.is_optional(), ) node.update_parent( parent.get_group_path(), parent.get_final_package() ) new_root = DefaultsTreeNode(node=node, parent=root) add_child(children, new_root) else: new_root = DefaultsTreeNode(node=d, parent=root) add_child(children, new_root) else: if d.is_interpolation(): children.append(d) continue new_root = DefaultsTreeNode(node=d, parent=root) add_child(children, new_root) # processed deferred interpolations known_choices = _create_interpolation_map(overrides, defaults_list, self_added) for idx, dd in enumerate(children): if isinstance(dd, InputDefault) and dd.is_interpolation(): dd.resolve_interpolation(known_choices) new_root = DefaultsTreeNode(node=dd, parent=root) dd.update_parent(parent.get_group_path(), parent.get_final_package()) subtree = _create_defaults_tree_impl( repo=repo, root=new_root, is_root_config=False, skip_missing=skip_missing, interpolated_subtree=True, overrides=overrides, ) if subtree.children is not None: children[idx] = subtree if len(children) > 0: root.children = list(reversed(children)) return root def _create_result_default( tree: Optional[DefaultsTreeNode], node: InputDefault ) -> Optional[ResultDefault]: if node.is_virtual(): return None if node.get_name() is None: return None res = ResultDefault() if node.is_self(): assert tree is not None res.config_path = tree.node.get_config_path() res.is_self = True pn = tree.parent_node() if pn is not None: res.parent = pn.get_config_path() else: res.parent = None res.package = tree.node.get_final_package() res.primary = tree.node.primary else: res.config_path = node.get_config_path() if tree is not None: res.parent = tree.node.get_config_path() res.package = node.get_final_package() if isinstance(node, GroupDefault): res.override_key = node.get_override_key() res.primary = node.primary if res.config_path == "_dummy_empty_config_": return None return res def _dfs_walk( tree: DefaultsTreeNode, operator: Callable[[Optional[DefaultsTreeNode], InputDefault], None], ) -> None: if tree.children is None or len(tree.children) == 0: operator(tree.parent, tree.node) else: for child in tree.children: if isinstance(child, InputDefault): operator(tree, child) else: assert isinstance(child, DefaultsTreeNode) _dfs_walk(tree=child, operator=operator) def _tree_to_list( tree: DefaultsTreeNode, ) -> List[ResultDefault]: class Collector: def __init__(self) -> None: self.output: List[ResultDefault] = [] def __call__( self, tree_node: Optional[DefaultsTreeNode], node: InputDefault ) -> None: if node.is_deleted(): return if node.is_missing(): return rd = _create_result_default(tree=tree_node, node=node) if rd is not None: self.output.append(rd) visitor = Collector() _dfs_walk(tree, visitor) return visitor.output def _create_root(config_name: Optional[str], with_hydra: bool) -> DefaultsTreeNode: primary: InputDefault if config_name is None: primary = ConfigDefault(path="_dummy_empty_config_", primary=True) else: primary = ConfigDefault(path=config_name, primary=True) if with_hydra: root = DefaultsTreeNode( node=VirtualRoot(), children=[ConfigDefault(path="hydra/config"), primary], ) else: root = DefaultsTreeNode(node=primary) return root def ensure_no_duplicates_in_list(result: List[ResultDefault]) -> None: keys = set() for item in result: if not item.is_self: key = item.override_key if key is not None: if key in keys: raise ConfigCompositionException( f"{key} appears more than once in the final defaults list" ) keys.add(key) def _create_defaults_list( repo: IConfigRepository, config_name: Optional[str], overrides: Overrides, prepend_hydra: bool, skip_missing: bool, ) -> Tuple[List[ResultDefault], DefaultsTreeNode]: root = _create_root(config_name=config_name, with_hydra=prepend_hydra) defaults_tree = _create_defaults_tree( repo=repo, root=root, overrides=overrides, is_root_config=True, interpolated_subtree=False, skip_missing=skip_missing, ) output = _tree_to_list(tree=defaults_tree) ensure_no_duplicates_in_list(output) return output, defaults_tree def create_defaults_list( repo: IConfigRepository, config_name: Optional[str], overrides_list: List[Override], prepend_hydra: bool, skip_missing: bool, ) -> DefaultsList: """ :param repo: :param config_name: :param overrides_list: :param prepend_hydra: :param skip_missing: True to skip config group with the value '???' and not fail on them. Useful when sweeping. :return: """ overrides = Overrides(repo=repo, overrides_list=overrides_list) defaults, tree = _create_defaults_list( repo, config_name, overrides, prepend_hydra=prepend_hydra, skip_missing=skip_missing, ) overrides.ensure_overrides_used() overrides.ensure_deletions_used() return DefaultsList( defaults=defaults, config_overrides=overrides.config_overrides, defaults_tree=tree, overrides=overrides, ) def config_not_found_error(repo: IConfigRepository, tree: DefaultsTreeNode) -> None: element = tree.node options = None group = None if isinstance(element, GroupDefault): group = element.get_group_path() options = repo.get_group_options(group, ObjectType.CONFIG) if element.primary: msg = dedent( f"""\ Cannot find primary config '{element.get_config_path()}'. Check that it's in your config search path. """ ) else: parent = tree.parent.node if tree.parent is not None else None if isinstance(element, GroupDefault): msg = f"Could not find '{element.get_config_path()}'\n" if options is not None and len(options) > 0: opt_list = "\n".join(["\t" + x for x in options]) msg = f"{msg}\nAvailable options in '{group}':\n" + opt_list else: msg = dedent( f"""\ Could not load '{element.get_config_path()}'. """ ) if parent is not None: msg = f"In '{parent.get_config_path()}': {msg}" descs = [] for src in repo.get_sources(): descs.append(f"\t{repr(src)}") lines = "\n".join(descs) msg += "\nConfig search path:" + f"\n{lines}" raise MissingConfigException( missing_cfg_file=element.get_config_path(), message=msg, options=options, )
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import copy import os import warnings from dataclasses import dataclass, field from textwrap import dedent from typing import Callable, Dict, List, Optional, Set, Tuple, Union from omegaconf import DictConfig, OmegaConf from hydra import MissingConfigException from hydra._internal.config_repository import IConfigRepository from hydra.core.config_store import ConfigStore from hydra.core.default_element import ( ConfigDefault, DefaultsTreeNode, GroupDefault, InputDefault, ResultDefault, VirtualRoot, ) from hydra.core.object_type import ObjectType from hydra.core.override_parser.types import Override from hydra.errors import ConfigCompositionException from .deprecation_warning import deprecation_warning cs = ConfigStore.instance() cs.store(name="_dummy_empty_config_", node={}, provider="hydra") @dataclass class Deletion: name: Optional[str] used: bool = field(default=False, compare=False) @dataclass class OverrideMetadata: external_override: bool containing_config_path: Optional[str] = None used: bool = False relative_key: Optional[str] = None @dataclass class Overrides: override_choices: Dict[str, Optional[Union[str, List[str]]]] override_metadata: Dict[str, OverrideMetadata] append_group_defaults: List[GroupDefault] config_overrides: List[Override] known_choices: Dict[str, Optional[str]] known_choices_per_group: Dict[str, Set[str]] deletions: Dict[str, Deletion] def __init__(self, repo: IConfigRepository, overrides_list: List[Override]) -> None: self.override_choices = {} self.override_metadata = {} self.append_group_defaults = [] self.config_overrides = [] self.deletions = {} self.known_choices = {} self.known_choices_per_group = {} for override in overrides_list: if override.is_sweep_override(): continue is_group = repo.group_exists(override.key_or_group) value = override.value() is_dict = isinstance(override.value(), dict) if is_dict or not is_group: self.config_overrides.append(override) elif override.is_force_add(): # This could probably be made to work if there is a compelling use case. raise ConfigCompositionException( f"force-add of config groups is not supported: '{override.input_line}'" ) elif override.is_delete(): key = override.get_key_element()[1:] value = override.value() if value is not None and not isinstance(value, str): raise ValueError( f"Config group override deletion value must be a string : {override}" ) self.deletions[key] = Deletion(name=value) elif not isinstance(value, (str, list)): raise ValueError( f"Config group override must be a string or a list. Got {type(value).__name__}" ) elif override.is_add(): self.append_group_defaults.append( GroupDefault( group=override.key_or_group, package=override.package, value=value, external_append=True, ) ) else: key = override.get_key_element() self.override_choices[key] = value self.override_metadata[key] = OverrideMetadata(external_override=True) def add_override(self, parent_config_path: str, default: GroupDefault) -> None: assert default.override key = default.get_override_key() if key not in self.override_choices: self.override_choices[key] = default.value self.override_metadata[key] = OverrideMetadata( external_override=False, containing_config_path=parent_config_path, relative_key=default.get_relative_override_key(), ) def is_overridden(self, default: InputDefault) -> bool: if isinstance(default, GroupDefault): return default.get_override_key() in self.override_choices return False def override_default_option(self, default: GroupDefault) -> None: key = default.get_override_key() if key in self.override_choices: if isinstance(default, GroupDefault): default.value = self.override_choices[key] default.config_name_overridden = True self.override_metadata[key].used = True def ensure_overrides_used(self) -> None: for key, meta in self.override_metadata.items(): if not meta.used: group = key.split("@")[0] choices = ( self.known_choices_per_group[group] if group in self.known_choices_per_group else set() ) if len(choices) > 1: msg = ( f"Could not override '{key}'." f"\nDid you mean to override one of {', '.join(sorted(list(choices)))}?" ) elif len(choices) == 1: msg = ( f"Could not override '{key}'." f"\nDid you mean to override {copy.copy(choices).pop()}?" ) elif len(choices) == 0: msg = f"Could not override '{key}'. No match in the defaults list." else: assert False if meta.containing_config_path is not None: msg = f"In '{meta.containing_config_path}': {msg}" if meta.external_override: msg += f"\nTo append to your default list use +{key}={self.override_choices[key]}" raise ConfigCompositionException(msg) def ensure_deletions_used(self) -> None: for key, deletion in self.deletions.items(): if not deletion.used: desc = f"{key}={deletion.name}" if deletion.name is not None else key msg = f"Could not delete '{desc}'. No match in the defaults list" raise ConfigCompositionException(msg) def set_known_choice(self, default: InputDefault) -> None: if isinstance(default, GroupDefault): key = default.get_override_key() if key not in self.known_choices: self.known_choices[key] = default.get_name() else: prev = self.known_choices[key] if default.get_name() != prev: raise ConfigCompositionException( f"Multiple values for {key}." f" To override a value use 'override {key}: {prev}'" ) group = default.get_group_path() if group not in self.known_choices_per_group: self.known_choices_per_group[group] = set() self.known_choices_per_group[group].add(key) def is_deleted(self, default: InputDefault) -> bool: if not isinstance(default, GroupDefault): return False key = default.get_override_key() if key in self.deletions: deletion = self.deletions[key] if deletion.name is None: return True else: return deletion.name == default.get_name() return False def delete(self, default: InputDefault) -> None: assert isinstance(default, GroupDefault) default.deleted = True key = default.get_override_key() self.deletions[key].used = True @dataclass class DefaultsList: defaults: List[ResultDefault] defaults_tree: DefaultsTreeNode config_overrides: List[Override] overrides: Overrides def _validate_self( containing_node: InputDefault, defaults: List[InputDefault], has_config_content: bool, ) -> bool: # check that self is present only once has_self = False has_non_override = False for d in defaults: if not d.is_override(): has_non_override = True if d.is_self(): if has_self: raise ConfigCompositionException( f"Duplicate _self_ defined in {containing_node.get_config_path()}" ) has_self = True if not has_self and has_non_override or len(defaults) == 0: # This check is here to make the migration from Hydra 1.0 to Hydra 1.1 smoother and should be removed in 1.2 # The warning should be removed in 1.2 if containing_node.primary and has_config_content and has_non_override: msg = ( f"In '{containing_node.get_config_path()}': Defaults list is missing `_self_`. " f"See https://hydra.cc/docs/upgrades/1.0_to_1.1/default_composition_order for more information" ) if os.environ.get("SELF_WARNING_AS_ERROR") == "1": raise ConfigCompositionException(msg) warnings.warn(msg, UserWarning) defaults.append(ConfigDefault(path="_self_")) return not has_self def update_package_header(repo: IConfigRepository, node: InputDefault) -> None: if node.is_missing(): return # This loads the same config loaded in _create_defaults_tree # To avoid loading it twice, the repo implementation is expected to cache loaded configs loaded = repo.load_config(config_path=node.get_config_path()) if loaded is not None: node.set_package_header(loaded.header["package"]) def _expand_virtual_root( repo: IConfigRepository, root: DefaultsTreeNode, overrides: Overrides, skip_missing: bool, ) -> DefaultsTreeNode: children: List[Union[DefaultsTreeNode, InputDefault]] = [] assert root.children is not None for d in reversed(root.children): assert isinstance(d, InputDefault) new_root = DefaultsTreeNode(node=d, parent=root) d.update_parent("", "") subtree = _create_defaults_tree_impl( repo=repo, root=new_root, is_root_config=d.primary, skip_missing=skip_missing, interpolated_subtree=False, overrides=overrides, ) if subtree.children is None: children.append(d) else: children.append(subtree) if len(children) > 0: root.children = list(reversed(children)) return root def _check_not_missing( repo: IConfigRepository, default: InputDefault, skip_missing: bool, ) -> bool: path = default.get_config_path() if path.endswith("???"): if skip_missing: return True if isinstance(default, GroupDefault): group_path = default.get_group_path() options = repo.get_group_options( group_path, results_filter=ObjectType.CONFIG, ) opt_list = "\n".join(["\t" + x for x in options]) msg = dedent( f"""\ You must specify '{group_path}', e.g, {group_path}=<OPTION> Available options: """ ) raise ConfigCompositionException(msg + opt_list) elif isinstance(default, ConfigDefault): raise ValueError(f"Missing ConfigDefault is not supported : {path}") else: assert False return False def _create_interpolation_map( overrides: Overrides, defaults_list: List[InputDefault], self_added: bool, ) -> DictConfig: known_choices = OmegaConf.create(overrides.known_choices) known_choices.defaults = [] for d in defaults_list: if self_added and d.is_self(): continue if isinstance(d, ConfigDefault): known_choices.defaults.append(d.get_config_path()) elif isinstance(d, GroupDefault): known_choices.defaults.append({d.get_override_key(): d.value}) return known_choices def _create_defaults_tree( repo: IConfigRepository, root: DefaultsTreeNode, is_root_config: bool, skip_missing: bool, interpolated_subtree: bool, overrides: Overrides, ) -> DefaultsTreeNode: ret = _create_defaults_tree_impl( repo=repo, root=root, is_root_config=is_root_config, skip_missing=skip_missing, interpolated_subtree=interpolated_subtree, overrides=overrides, ) return ret def _update_overrides( defaults_list: List[InputDefault], overrides: Overrides, parent: InputDefault, interpolated_subtree: bool, ) -> None: seen_override = False last_override_seen = None for d in defaults_list: if d.is_self(): continue d.update_parent(parent.get_group_path(), parent.get_final_package()) legacy_hydra_override = False if isinstance(d, GroupDefault): assert d.group is not None legacy_hydra_override = not d.is_override() and d.group.startswith("hydra/") if seen_override and not ( d.is_override() or d.is_external_append() or legacy_hydra_override ): assert isinstance(last_override_seen, GroupDefault) pcp = parent.get_config_path() okey = last_override_seen.get_override_key() oval = last_override_seen.get_name() raise ConfigCompositionException( dedent( f"""\ In {pcp}: Override '{okey} : {oval}' is defined before '{d.get_override_key()}: {d.get_name()}'. Overrides must be at the end of the defaults list""" ) ) if isinstance(d, GroupDefault): if legacy_hydra_override: # DEPRECATED: remove in 1.2 d.override = True url = "https://hydra.cc/docs/next/upgrades/1.0_to_1.1/defaults_list_override" msg = dedent( f"""\ In {parent.get_config_path()}: Invalid overriding of {d.group}: Default list overrides requires 'override' keyword. See {url} for more information. """ ) deprecation_warning(msg) if d.override: if not legacy_hydra_override: seen_override = True last_override_seen = d if interpolated_subtree: # Since interpolations are deferred for until all the config groups are already set, # Their subtree may not contain config group overrides raise ConfigCompositionException( dedent( f"""\ {parent.get_config_path()}: Default List Overrides are not allowed in the subtree of an in interpolated config group (override {d.get_override_key()}={d.get_name()}). """ ) ) overrides.add_override(parent.get_config_path(), d) def _has_config_content(cfg: DictConfig) -> bool: if cfg._is_none() or cfg._is_missing(): return False for key in cfg.keys(): if not OmegaConf.is_missing(cfg, key): return True return False def _create_defaults_tree_impl( repo: IConfigRepository, root: DefaultsTreeNode, is_root_config: bool, skip_missing: bool, interpolated_subtree: bool, overrides: Overrides, ) -> DefaultsTreeNode: parent = root.node children: List[Union[InputDefault, DefaultsTreeNode]] = [] if parent.is_virtual(): if is_root_config: return _expand_virtual_root(repo, root, overrides, skip_missing) else: return root if is_root_config: root.node.update_parent("", "") if not repo.config_exists(root.node.get_config_path()): config_not_found_error(repo=repo, tree=root) update_package_header(repo=repo, node=parent) if overrides.is_deleted(parent): overrides.delete(parent) return root overrides.set_known_choice(parent) if parent.get_name() is None: return root if _check_not_missing(repo=repo, default=parent, skip_missing=skip_missing): return root path = parent.get_config_path() loaded = repo.load_config(config_path=path) if loaded is None: if parent.is_optional(): assert isinstance(parent, (GroupDefault, ConfigDefault)) parent.deleted = True return root config_not_found_error(repo=repo, tree=root) assert loaded is not None defaults_list = copy.deepcopy(loaded.defaults_list) if defaults_list is None: defaults_list = [] self_added = False if ( len(defaults_list) > 0 or is_root_config and len(overrides.append_group_defaults) > 0 ): has_config_content = isinstance( loaded.config, DictConfig ) and _has_config_content(loaded.config) self_added = _validate_self( containing_node=parent, defaults=defaults_list, has_config_content=has_config_content, ) if is_root_config: defaults_list.extend(overrides.append_group_defaults) _update_overrides(defaults_list, overrides, parent, interpolated_subtree) def add_child( child_list: List[Union[InputDefault, DefaultsTreeNode]], new_root_: DefaultsTreeNode, ) -> None: subtree_ = _create_defaults_tree_impl( repo=repo, root=new_root_, is_root_config=False, interpolated_subtree=interpolated_subtree, skip_missing=skip_missing, overrides=overrides, ) if subtree_.children is None: child_list.append(new_root_.node) else: child_list.append(subtree_) for d in reversed(defaults_list): if d.is_self(): d.update_parent(root.node.parent_base_dir, root.node.get_package()) children.append(d) else: if d.is_override(): continue d.update_parent(parent.get_group_path(), parent.get_final_package()) if overrides.is_overridden(d): assert isinstance(d, GroupDefault) overrides.override_default_option(d) if isinstance(d, GroupDefault) and d.is_options(): # overriding may change from options to name if d.is_options(): for item in reversed(d.get_options()): if "${" in item: raise ConfigCompositionException( f"In '{path}': Defaults List interpolation is not supported in options list items" ) assert d.group is not None node = ConfigDefault( path=d.group + "/" + item, package=d.package, optional=d.is_optional(), ) node.update_parent( parent.get_group_path(), parent.get_final_package() ) new_root = DefaultsTreeNode(node=node, parent=root) add_child(children, new_root) else: new_root = DefaultsTreeNode(node=d, parent=root) add_child(children, new_root) else: if d.is_interpolation(): children.append(d) continue new_root = DefaultsTreeNode(node=d, parent=root) add_child(children, new_root) # processed deferred interpolations known_choices = _create_interpolation_map(overrides, defaults_list, self_added) for idx, dd in enumerate(children): if isinstance(dd, InputDefault) and dd.is_interpolation(): dd.resolve_interpolation(known_choices) new_root = DefaultsTreeNode(node=dd, parent=root) dd.update_parent(parent.get_group_path(), parent.get_final_package()) subtree = _create_defaults_tree_impl( repo=repo, root=new_root, is_root_config=False, skip_missing=skip_missing, interpolated_subtree=True, overrides=overrides, ) if subtree.children is not None: children[idx] = subtree if len(children) > 0: root.children = list(reversed(children)) return root def _create_result_default( tree: Optional[DefaultsTreeNode], node: InputDefault ) -> Optional[ResultDefault]: if node.is_virtual(): return None if node.get_name() is None: return None res = ResultDefault() if node.is_self(): assert tree is not None res.config_path = tree.node.get_config_path() res.is_self = True pn = tree.parent_node() if pn is not None: res.parent = pn.get_config_path() else: res.parent = None res.package = tree.node.get_final_package() res.primary = tree.node.primary else: res.config_path = node.get_config_path() if tree is not None: res.parent = tree.node.get_config_path() res.package = node.get_final_package() if isinstance(node, GroupDefault): res.override_key = node.get_override_key() res.primary = node.primary if res.config_path == "_dummy_empty_config_": return None return res def _dfs_walk( tree: DefaultsTreeNode, operator: Callable[[Optional[DefaultsTreeNode], InputDefault], None], ) -> None: if tree.children is None or len(tree.children) == 0: operator(tree.parent, tree.node) else: for child in tree.children: if isinstance(child, InputDefault): operator(tree, child) else: assert isinstance(child, DefaultsTreeNode) _dfs_walk(tree=child, operator=operator) def _tree_to_list( tree: DefaultsTreeNode, ) -> List[ResultDefault]: class Collector: def __init__(self) -> None: self.output: List[ResultDefault] = [] def __call__( self, tree_node: Optional[DefaultsTreeNode], node: InputDefault ) -> None: if node.is_deleted(): return if node.is_missing(): return rd = _create_result_default(tree=tree_node, node=node) if rd is not None: self.output.append(rd) visitor = Collector() _dfs_walk(tree, visitor) return visitor.output def _create_root(config_name: Optional[str], with_hydra: bool) -> DefaultsTreeNode: primary: InputDefault if config_name is None: primary = ConfigDefault(path="_dummy_empty_config_", primary=True) else: primary = ConfigDefault(path=config_name, primary=True) if with_hydra: root = DefaultsTreeNode( node=VirtualRoot(), children=[ConfigDefault(path="hydra/config"), primary], ) else: root = DefaultsTreeNode(node=primary) return root def ensure_no_duplicates_in_list(result: List[ResultDefault]) -> None: keys = set() for item in result: if not item.is_self: key = item.override_key if key is not None: if key in keys: raise ConfigCompositionException( f"{key} appears more than once in the final defaults list" ) keys.add(key) def _create_defaults_list( repo: IConfigRepository, config_name: Optional[str], overrides: Overrides, prepend_hydra: bool, skip_missing: bool, ) -> Tuple[List[ResultDefault], DefaultsTreeNode]: root = _create_root(config_name=config_name, with_hydra=prepend_hydra) defaults_tree = _create_defaults_tree( repo=repo, root=root, overrides=overrides, is_root_config=True, interpolated_subtree=False, skip_missing=skip_missing, ) output = _tree_to_list(tree=defaults_tree) ensure_no_duplicates_in_list(output) return output, defaults_tree def create_defaults_list( repo: IConfigRepository, config_name: Optional[str], overrides_list: List[Override], prepend_hydra: bool, skip_missing: bool, ) -> DefaultsList: """ :param repo: :param config_name: :param overrides_list: :param prepend_hydra: :param skip_missing: True to skip config group with the value '???' and not fail on them. Useful when sweeping. :return: """ overrides = Overrides(repo=repo, overrides_list=overrides_list) defaults, tree = _create_defaults_list( repo, config_name, overrides, prepend_hydra=prepend_hydra, skip_missing=skip_missing, ) overrides.ensure_overrides_used() overrides.ensure_deletions_used() return DefaultsList( defaults=defaults, config_overrides=overrides.config_overrides, defaults_tree=tree, overrides=overrides, ) def config_not_found_error(repo: IConfigRepository, tree: DefaultsTreeNode) -> None: element = tree.node options = None group = None if isinstance(element, GroupDefault): group = element.get_group_path() options = repo.get_group_options(group, ObjectType.CONFIG) if element.primary: msg = dedent( f"""\ Cannot find primary config '{element.get_config_path()}'. Check that it's in your config search path. """ ) else: parent = tree.parent.node if tree.parent is not None else None if isinstance(element, GroupDefault): msg = f"Could not find '{element.get_config_path()}'\n" if options is not None and len(options) > 0: opt_list = "\n".join(["\t" + x for x in options]) msg = f"{msg}\nAvailable options in '{group}':\n" + opt_list else: msg = dedent( f"""\ Could not load '{element.get_config_path()}'. """ ) if parent is not None: msg = f"In '{parent.get_config_path()}': {msg}" descs = [] for src in repo.get_sources(): descs.append(f"\t{repr(src)}") lines = "\n".join(descs) msg += "\nConfig search path:" + f"\n{lines}" raise MissingConfigException( missing_cfg_file=element.get_config_path(), message=msg, options=options, )
import asyncio import os import random import re import string import discord from discord.ext import commands from utils.functions import read_file class MadLibs(commands.Cog): """The classic [madlibs game](https://en.wikipedia.org/wiki/Mad_Libs)""" def __init__(self, bot): self.bot = bot # Setup our regex self.regex = re.compile(r"\[\[[^\[\]]+\]\]") @commands.command() async def madlibs(self, ctx): """Let's play MadLibs!""" # Check if our folder exists if not os.path.isdir("assets/madlibs"): return await ctx.channel.send("I'm not configured for MadLibs yet...") # Folder exists - let's see if it has any files choices = [] for file in os.listdir("assets/madlibs/"): if file.endswith(".txt"): choices.append(file) if not choices: # No madlibs files return await ctx.channel.send("No madlibs files found, ask the owner to add one") # We have the file, lets notify the user await ctx.send("Okay a madlibs game started, reply with `!stop` to stop") # Get a random madlib from those available random_madlib = random.choice(choices) # Let's load our madlibs file data = read_file(f"assets/madlibs/{random_madlib}") # Set up an empty array of words words = [] # Find all the words that need to be added matches = re.finditer(self.regex, data) # Get all the words from the matched and add them to a list for match in matches: words.append(match.group(0)) # Create empty substitution array subs = [] # Iterate words and ask for input for i, word in enumerate(words): # We define the vowels vowels = "aeiou" # The [2:-2] is there to remove the first [[ and the last ]] used by our syntax word = word[2:-2] # If the word starts with a vowel then we use an instead of a is_vowel = word[0].lower() in vowels await ctx.channel.send(f"I need a{"n" if is_vowel else ""} **{word}** (word *{i + 1}/{len(words)}*).") # Setup the check def check(msg): return msg.author == ctx.author and msg.channel == ctx.channel # We wait for a response try: talk = await self.bot.wait_for("message", check=check, timeout=60) except asyncio.TimeoutError: return await ctx.send("You did not respond") # Check if the message is to leave if talk.content.lower().startswith(("stop madlibs", "!stop", "!cancel")): if talk.author is ctx.author: return await ctx.channel.send(f"Alright, *{ctx.author.name}*. We'll play another time.") # We got a relevant message word = talk.content # Check for capitalization if not word.istitle(): # Make it properly capitalized word = string.capwords(word) # Add to our list subs.append(word) # We replace the placeholders with the words picked by our user for asub in subs: # Only replace the first occurrence data = re.sub(self.regex, f"**{asub}**", data, 1) # Send the result await ctx.channel.send(data) def setup(bot): """Adds the cog to the bot""" bot.add_cog(MadLibs(bot))
import asyncio import os import random import re import string import discord from discord.ext import commands from utils.functions import read_file class MadLibs(commands.Cog): """The classic [madlibs game](https://en.wikipedia.org/wiki/Mad_Libs)""" def __init__(self, bot): self.bot = bot # Setup our regex self.regex = re.compile(r"\[\[[^\[\]]+\]\]") @commands.command() async def madlibs(self, ctx): """Let's play MadLibs!""" # Check if our folder exists if not os.path.isdir("assets/madlibs"): return await ctx.channel.send("I'm not configured for MadLibs yet...") # Folder exists - let's see if it has any files choices = [] for file in os.listdir("assets/madlibs/"): if file.endswith(".txt"): choices.append(file) if not choices: # No madlibs files return await ctx.channel.send("No madlibs files found, ask the owner to add one") # We have the file, lets notify the user await ctx.send("Okay a madlibs game started, reply with `!stop` to stop") # Get a random madlib from those available random_madlib = random.choice(choices) # Let's load our madlibs file data = read_file(f"assets/madlibs/{random_madlib}") # Set up an empty array of words words = [] # Find all the words that need to be added matches = re.finditer(self.regex, data) # Get all the words from the matched and add them to a list for match in matches: words.append(match.group(0)) # Create empty substitution array subs = [] # Iterate words and ask for input for i, word in enumerate(words): # We define the vowels vowels = "aeiou" # The [2:-2] is there to remove the first [[ and the last ]] used by our syntax word = word[2:-2] # If the word starts with a vowel then we use an instead of a is_vowel = word[0].lower() in vowels await ctx.channel.send(f"I need a{'n' if is_vowel else ''} **{word}** (word *{i + 1}/{len(words)}*).") # Setup the check def check(msg): return msg.author == ctx.author and msg.channel == ctx.channel # We wait for a response try: talk = await self.bot.wait_for("message", check=check, timeout=60) except asyncio.TimeoutError: return await ctx.send("You did not respond") # Check if the message is to leave if talk.content.lower().startswith(("stop madlibs", "!stop", "!cancel")): if talk.author is ctx.author: return await ctx.channel.send(f"Alright, *{ctx.author.name}*. We'll play another time.") # We got a relevant message word = talk.content # Check for capitalization if not word.istitle(): # Make it properly capitalized word = string.capwords(word) # Add to our list subs.append(word) # We replace the placeholders with the words picked by our user for asub in subs: # Only replace the first occurrence data = re.sub(self.regex, f"**{asub}**", data, 1) # Send the result await ctx.channel.send(data) def setup(bot): """Adds the cog to the bot""" bot.add_cog(MadLibs(bot))
# Licensed under a 3-clause BSD style license - see LICENSE.rst import logging import numpy as np import astropy.units as u from astropy.io import fits from astropy.table import Table from gammapy.maps import MapAxes, MapAxis from gammapy.utils.integrate import trapz_loglog from gammapy.utils.nddata import NDDataArray from gammapy.utils.scripts import make_path __all__ = ["Background3D", "Background2D"] log = logging.getLogger(__name__) class Background3D: """Background 3D. Data format specification: :ref:`gadf:bkg_3d` Parameters ---------- energy_axis : `MapAxis` Energy axis fov_lon_axis: `MapAxis` FOV coordinate X-axis fov_lat_axis : `MapAxis` FOV coordinate Y-axis. data : `~astropy.units.Quantity` Background rate (usually: ``s^-1 MeV^-1 sr^-1``) Examples -------- Here's an example you can use to learn about this class: >>> from gammapy.irf import Background3D >>> filename = '$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits' >>> bkg_3d = Background3D.read(filename, hdu='BACKGROUND') >>> print(bkg_3d) Background3D NDDataArray summary info energy : size = 21, min = 0.016 TeV, max = 158.489 TeV fov_lon : size = 36, min = -5.833 deg, max = 5.833 deg fov_lat : size = 36, min = -5.833 deg, max = 5.833 deg Data : size = 27216, min = 0.000 1 / (MeV s sr), max = 0.421 1 / (MeV s sr) """ tag = "bkg_3d" default_interp_kwargs = dict( bounds_error=False, fill_value=None, values_scale="log" ) """Default Interpolation kwargs for `~gammapy.utils.nddata.NDDataArray`. Extrapolate.""" def __init__( self, energy_axis, fov_lon_axis, fov_lat_axis, data, meta=None, interp_kwargs=None, ): if interp_kwargs is None: interp_kwargs = self.default_interp_kwargs self.data = NDDataArray( axes=[energy_axis, fov_lon_axis, fov_lat_axis], data=data, interp_kwargs=interp_kwargs, ) self.data.axes.assert_names(["energy", "fov_lon", "fov_lat"]) self.meta = meta or {} def __str__(self): ss = self.__class__.__name__ ss += f"\n{self.data}" return ss @classmethod def from_table(cls, table): """Read from `~astropy.table.Table`.""" # Spec says key should be "BKG", but there are files around # (e.g. CTA 1DC) that use "BGD". For now we support both if "BKG" in table.colnames: bkg_name = "BKG" elif "BGD" in table.colnames: bkg_name = "BGD" else: raise ValueError('Invalid column names. Need "BKG" or "BGD".') data_unit = table[bkg_name].unit if data_unit is not None: data_unit = u.Unit(table[bkg_name].unit, parse_strict="silent") if isinstance(data_unit, u.UnrecognizedUnit) or (data_unit is None): data_unit = u.Unit("s-1 MeV-1 sr-1") log.warning( "Invalid unit found in background table! Assuming (s-1 MeV-1 sr-1)" ) energy_axis = MapAxis.from_table( table, column_prefix="ENERG", format="gadf-dl3" ) fov_lon_axis = MapAxis.from_table( table, column_prefix="DETX", format="gadf-dl3" ) fov_lat_axis = MapAxis.from_table( table, column_prefix="DETY", format="gadf-dl3" ) # TODO: The present HESS and CTA backgroundfits files # have a reverse order (lon, lat, E) than recommened in GADF(E, lat, lon) # For now, we suport both. data = table[bkg_name].data[0].T * data_unit shape = (energy_axis.nbin, fov_lon_axis.nbin, fov_lat_axis.nbin) if shape == shape[::-1]: log.error("Ambiguous axes order in Background fits files!") if np.shape(data) != shape: log.debug("Transposing background table on read") data = data.transpose() return cls( energy_axis=energy_axis, fov_lon_axis=fov_lon_axis, fov_lat_axis=fov_lat_axis, data=data, meta=table.meta, ) @classmethod def from_hdulist(cls, hdulist, hdu="BACKGROUND"): """Create from `~astropy.io.fits.HDUList`.""" return cls.from_table(Table.read(hdulist[hdu])) @classmethod def read(cls, filename, hdu="BACKGROUND"): """Read from file.""" with fits.open(str(make_path(filename)), memmap=False) as hdulist: return cls.from_hdulist(hdulist, hdu=hdu) def to_table(self): """Convert to `~astropy.table.Table`.""" # TODO: fix axis order axes = MapAxes(self.data.axes[::-1]) table = axes.to_table(format="gadf-dl3") table.meta = self.meta.copy() table.meta["HDUCLAS2"] = "BKG" table["BKG"] = self.data.data.T[np.newaxis] return table def to_table_hdu(self, name="BACKGROUND"): """Convert to `~astropy.io.fits.BinTableHDU`.""" return fits.BinTableHDU(self.to_table(), name=name) def evaluate(self, fov_lon, fov_lat, energy_reco, method="linear", **kwargs): """Evaluate at given FOV position and energy. Parameters ---------- fov_lon, fov_lat : `~astropy.coordinates.Angle` FOV coordinates expecting in AltAz frame. energy_reco : `~astropy.units.Quantity` energy on which you want to interpolate. Same dimension than fov_lat and fov_lat method : str {'linear', 'nearest'}, optional Interpolation method kwargs : dict option for interpolation for `~scipy.interpolate.RegularGridInterpolator` Returns ------- array : `~astropy.units.Quantity` Interpolated values, axis order is the same as for the NDData array """ values = self.data.evaluate( fov_lon=fov_lon, fov_lat=fov_lat, energy=energy_reco, method=method, **kwargs, ) return values def evaluate_integrate( self, fov_lon, fov_lat, energy_reco, method="linear", **kwargs ): """Integrate in a given energy band. Parameters ---------- fov_lon, fov_lat : `~astropy.coordinates.Angle` FOV coordinates expecting in AltAz frame. energy_reco: `~astropy.units.Quantity` Reconstructed energy edges. method : {'linear', 'nearest'}, optional Interpolation method Returns ------- array : `~astropy.units.Quantity` Returns 2D array with axes offset """ data = self.evaluate(fov_lon, fov_lat, energy_reco, method=method) return trapz_loglog(data, energy_reco, axis=0) def to_2d(self): """Convert to `Background2D`. This takes the values at Y = 0 and X >= 0. """ # TODO: this is incorrect as it misses the Jacobian? idx_lon = self.data.axes["fov_lon"].coord_to_idx(0 * u.deg)[0] idx_lat = self.data.axes["fov_lat"].coord_to_idx(0 * u.deg)[0] data = self.data.data[:, idx_lon:, idx_lat].copy() offset = self.data.axes["fov_lon"].edges[idx_lon:] offset_axis = MapAxis.from_edges(offset, name="offset") return Background2D( energy_axis=self.data.axes["energy"], offset_axis=offset_axis, data=data, ) def peek(self, figsize=(10, 8)): return self.to_2d().peek(figsize) class Background2D: """Background 2D. Data format specification: :ref:`gadf:bkg_2d` Parameters ---------- energy_axis : `MapAxis` Energy axis offset_axis : `MapAxis` FOV coordinate offset-axis data : `~astropy.units.Quantity` Background rate (usually: ``s^-1 MeV^-1 sr^-1``) """ tag = "bkg_2d" default_interp_kwargs = dict(bounds_error=False, fill_value=None) """Default Interpolation kwargs for `~gammapy.utils.nddata.NDDataArray`. Extrapolate.""" def __init__( self, energy_axis, offset_axis, data, meta=None, interp_kwargs=None, ): if interp_kwargs is None: interp_kwargs = self.default_interp_kwargs self.data = NDDataArray( axes=[energy_axis, offset_axis], data=data, interp_kwargs=interp_kwargs ) self.data.axes.assert_names(["energy", "offset"]) self.meta = meta or {} def __str__(self): ss = self.__class__.__name__ ss += f"\n{self.data}" return ss @classmethod def from_table(cls, table): """Read from `~astropy.table.Table`.""" # Spec says key should be "BKG", but there are files around # (e.g. CTA 1DC) that use "BGD". For now we support both if "BKG" in table.colnames: bkg_name = "BKG" elif "BGD" in table.colnames: bkg_name = "BGD" else: raise ValueError('Invalid column names. Need "BKG" or "BGD".') data_unit = table[bkg_name].unit if data_unit is not None: data_unit = u.Unit(data_unit, parse_strict="silent") if isinstance(data_unit, u.UnrecognizedUnit) or (data_unit is None): data_unit = u.Unit("s-1 MeV-1 sr-1") log.warning( "Invalid unit found in background table! Assuming (s-1 MeV-1 sr-1)" ) energy_axis = MapAxis.from_table( table, column_prefix="ENERG", format="gadf-dl3" ) offset_axis = MapAxis.from_table( table, column_prefix="THETA", format="gadf-dl3" ) # TODO: The present HESS and CTA backgroundfits files # have a reverse order (theta, E) than recommened in GADF(E, theta) # For now, we suport both. data = table[bkg_name].data[0].T * data_unit shape = (energy_axis.nbin, offset_axis.nbin) if shape == shape[::-1]: log.error("Ambiguous axes order in Background fits files!") if np.shape(data) != shape: log.debug("Transposing background table on read") data = data.transpose() return cls( energy_axis=energy_axis, offset_axis=offset_axis, data=data, meta=table.meta, ) @classmethod def from_hdulist(cls, hdulist, hdu="BACKGROUND"): """Create from `~astropy.io.fits.HDUList`.""" return cls.from_table(Table.read(hdulist[hdu])) @classmethod def read(cls, filename, hdu="BACKGROUND"): """Read from file.""" with fits.open(str(make_path(filename)), memmap=False) as hdulist: return cls.from_hdulist(hdulist, hdu=hdu) def to_table(self): """Convert to `~astropy.table.Table`.""" table = self.data.axes.to_table(format="gadf-dl3") table.meta = self.meta.copy() # TODO: add other required meta data table.meta["HDUCLAS2"] = "BKG" table["BKG"] = self.data.data.T[np.newaxis] return table def to_table_hdu(self, name="BACKGROUND"): """Convert to `~astropy.io.fits.BinTableHDU`.""" return fits.BinTableHDU(self.to_table(), name=name) def evaluate(self, fov_lon, fov_lat, energy_reco, method="linear", **kwargs): """Evaluate at a given FOV position and energy. The fov_lon, fov_lat, energy_reco has to have the same shape since this is a set of points on which you want to evaluate. To have the same API than background 3D for the background evaluation, the offset is ``fov_altaz_lon``. Parameters ---------- fov_lon, fov_lat : `~astropy.coordinates.Angle` FOV coordinates expecting in AltAz frame, same shape than energy_reco energy_reco : `~astropy.units.Quantity` Reconstructed energy, same dimension than fov_lat and fov_lat method : str {'linear', 'nearest'}, optional Interpolation method kwargs : dict option for interpolation for `~scipy.interpolate.RegularGridInterpolator` Returns ------- array : `~astropy.units.Quantity` Interpolated values, axis order is the same as for the NDData array """ offset = np.sqrt(fov_lon ** 2 + fov_lat ** 2) return self.data.evaluate( offset=offset, energy=energy_reco, method=method, **kwargs ) def evaluate_integrate(self, fov_lon, fov_lat, energy_reco, method="linear"): """Evaluate at given FOV position and energy, by integrating over the energy range. Parameters ---------- fov_lon, fov_lat : `~astropy.coordinates.Angle` FOV coordinates expecting in AltAz frame. energy_reco: `~astropy.units.Quantity` Reconstructed energy edges. method : {'linear', 'nearest'}, optional Interpolation method Returns ------- array : `~astropy.units.Quantity` Returns 2D array with axes offset """ data = self.evaluate(fov_lon, fov_lat, energy_reco, method=method) return trapz_loglog(data, energy_reco, axis=0) def to_3d(self): """Convert to `Background3D`. Fill in a radially symmetric way. """ raise NotImplementedError def plot(self, ax=None, add_cbar=True, **kwargs): """Plot energy offset dependence of the background model. """ import matplotlib.pyplot as plt from matplotlib.colors import LogNorm ax = plt.gca() if ax is None else ax x = self.data.axes["energy"].edges.to_value("TeV") y = self.data.axes["offset"].edges.to_value("deg") z = self.data.data.T.value kwargs.setdefault("cmap", "GnBu") kwargs.setdefault("edgecolors", "face") caxes = ax.pcolormesh(x, y, z, norm=LogNorm(), **kwargs) ax.set_xscale("log") ax.set_ylabel(f"Offset (deg)") ax.set_xlabel(f"Energy (TeV)") xmin, xmax = x.min(), x.max() ax.set_xlim(xmin, xmax) if add_cbar: label = f"Background rate ({self.data.data.unit})" ax.figure.colorbar(caxes, ax=ax, label=label) def plot_offset_dependence(self, ax=None, offset=None, energy=None, **kwargs): """Plot background rate versus offset for a given energy. Parameters ---------- ax : `~matplotlib.axes.Axes`, optional Axis offset : `~astropy.coordinates.Angle` Offset axis energy : `~astropy.units.Quantity` Energy Returns ------- ax : `~matplotlib.axes.Axes` Axis """ import matplotlib.pyplot as plt ax = plt.gca() if ax is None else ax if energy is None: energy_axis = self.data.axes["energy"] e_min, e_max = np.log10(energy_axis.center.value[[0, -1]]) energy = np.logspace(e_min, e_max, 4) * energy_axis.unit if offset is None: offset = self.data.axes["offset"].center for ee in energy: bkg = self.data.evaluate(offset=offset, energy=ee) if np.isnan(bkg).all(): continue label = f"energy = {ee:.1f}" ax.plot(offset, bkg.value, label=label, **kwargs) ax.set_xlabel(f"Offset ({self.data.axes["offset"].unit})") ax.set_ylabel(f"Background rate ({self.data.data.unit})") ax.set_yscale("log") ax.legend(loc="upper right") return ax def plot_energy_dependence(self, ax=None, offset=None, energy=None, **kwargs): """Plot background rate versus energy for a given offset. Parameters ---------- ax : `~matplotlib.axes.Axes`, optional Axis offset : `~astropy.coordinates.Angle` Offset energy : `~astropy.units.Quantity` Energy axis kwargs : dict Forwarded tp plt.plot() Returns ------- ax : `~matplotlib.axes.Axes` Axis """ import matplotlib.pyplot as plt ax = plt.gca() if ax is None else ax if offset is None: offset_axis = self.data.axes["offset"] off_min, off_max = offset_axis.center.value[[0, -1]] offset = np.linspace(off_min, off_max, 4) * offset_axis.unit if energy is None: energy = self.data.axes["energy"].center for off in offset: bkg = self.data.evaluate(offset=off, energy=energy) kwargs.setdefault("label", f"offset = {off:.1f}") ax.plot(energy, bkg.value, **kwargs) ax.set_xscale("log") ax.set_yscale("log") ax.set_xlabel(f"Energy [{energy.unit}]") ax.set_ylabel(f"Background rate ({self.data.data.unit})") ax.set_xlim(min(energy.value), max(energy.value)) ax.legend(loc="best") return ax def plot_spectrum(self, ax=None, **kwargs): """Plot angle integrated background rate versus energy. Parameters ---------- ax : `~matplotlib.axes.Axes`, optional Axis kwargs : dict Forwarded tp plt.plot() Returns ------- ax : `~matplotlib.axes.Axes` Axis """ import matplotlib.pyplot as plt ax = plt.gca() if ax is None else ax offset = self.data.axes["offset"].edges energy = self.data.axes["energy"].center bkg = [] for ee in energy: data = self.data.evaluate(offset=offset, energy=ee) val = np.nansum(trapz_loglog(data, offset, axis=0)) bkg.append(val.value) ax.plot(energy, bkg, label="integrated spectrum", **kwargs) unit = self.data.data.unit * offset.unit * offset.unit ax.set_xscale("log") ax.set_yscale("log") ax.set_xlabel(f"Energy [{energy.unit}]") ax.set_ylabel(f"Background rate ({unit})") ax.set_xlim(min(energy.value), max(energy.value)) ax.legend(loc="best") return ax def peek(self, figsize=(10, 8)): """Quick-look summary plots.""" import matplotlib.pyplot as plt fig, axes = plt.subplots(nrows=2, ncols=2, figsize=figsize) self.plot(ax=axes[1][1]) self.plot_offset_dependence(ax=axes[0][0]) self.plot_energy_dependence(ax=axes[1][0]) self.plot_spectrum(ax=axes[0][1]) plt.tight_layout()
# Licensed under a 3-clause BSD style license - see LICENSE.rst import logging import numpy as np import astropy.units as u from astropy.io import fits from astropy.table import Table from gammapy.maps import MapAxes, MapAxis from gammapy.utils.integrate import trapz_loglog from gammapy.utils.nddata import NDDataArray from gammapy.utils.scripts import make_path __all__ = ["Background3D", "Background2D"] log = logging.getLogger(__name__) class Background3D: """Background 3D. Data format specification: :ref:`gadf:bkg_3d` Parameters ---------- energy_axis : `MapAxis` Energy axis fov_lon_axis: `MapAxis` FOV coordinate X-axis fov_lat_axis : `MapAxis` FOV coordinate Y-axis. data : `~astropy.units.Quantity` Background rate (usually: ``s^-1 MeV^-1 sr^-1``) Examples -------- Here's an example you can use to learn about this class: >>> from gammapy.irf import Background3D >>> filename = '$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits' >>> bkg_3d = Background3D.read(filename, hdu='BACKGROUND') >>> print(bkg_3d) Background3D NDDataArray summary info energy : size = 21, min = 0.016 TeV, max = 158.489 TeV fov_lon : size = 36, min = -5.833 deg, max = 5.833 deg fov_lat : size = 36, min = -5.833 deg, max = 5.833 deg Data : size = 27216, min = 0.000 1 / (MeV s sr), max = 0.421 1 / (MeV s sr) """ tag = "bkg_3d" default_interp_kwargs = dict( bounds_error=False, fill_value=None, values_scale="log" ) """Default Interpolation kwargs for `~gammapy.utils.nddata.NDDataArray`. Extrapolate.""" def __init__( self, energy_axis, fov_lon_axis, fov_lat_axis, data, meta=None, interp_kwargs=None, ): if interp_kwargs is None: interp_kwargs = self.default_interp_kwargs self.data = NDDataArray( axes=[energy_axis, fov_lon_axis, fov_lat_axis], data=data, interp_kwargs=interp_kwargs, ) self.data.axes.assert_names(["energy", "fov_lon", "fov_lat"]) self.meta = meta or {} def __str__(self): ss = self.__class__.__name__ ss += f"\n{self.data}" return ss @classmethod def from_table(cls, table): """Read from `~astropy.table.Table`.""" # Spec says key should be "BKG", but there are files around # (e.g. CTA 1DC) that use "BGD". For now we support both if "BKG" in table.colnames: bkg_name = "BKG" elif "BGD" in table.colnames: bkg_name = "BGD" else: raise ValueError('Invalid column names. Need "BKG" or "BGD".') data_unit = table[bkg_name].unit if data_unit is not None: data_unit = u.Unit(table[bkg_name].unit, parse_strict="silent") if isinstance(data_unit, u.UnrecognizedUnit) or (data_unit is None): data_unit = u.Unit("s-1 MeV-1 sr-1") log.warning( "Invalid unit found in background table! Assuming (s-1 MeV-1 sr-1)" ) energy_axis = MapAxis.from_table( table, column_prefix="ENERG", format="gadf-dl3" ) fov_lon_axis = MapAxis.from_table( table, column_prefix="DETX", format="gadf-dl3" ) fov_lat_axis = MapAxis.from_table( table, column_prefix="DETY", format="gadf-dl3" ) # TODO: The present HESS and CTA backgroundfits files # have a reverse order (lon, lat, E) than recommened in GADF(E, lat, lon) # For now, we suport both. data = table[bkg_name].data[0].T * data_unit shape = (energy_axis.nbin, fov_lon_axis.nbin, fov_lat_axis.nbin) if shape == shape[::-1]: log.error("Ambiguous axes order in Background fits files!") if np.shape(data) != shape: log.debug("Transposing background table on read") data = data.transpose() return cls( energy_axis=energy_axis, fov_lon_axis=fov_lon_axis, fov_lat_axis=fov_lat_axis, data=data, meta=table.meta, ) @classmethod def from_hdulist(cls, hdulist, hdu="BACKGROUND"): """Create from `~astropy.io.fits.HDUList`.""" return cls.from_table(Table.read(hdulist[hdu])) @classmethod def read(cls, filename, hdu="BACKGROUND"): """Read from file.""" with fits.open(str(make_path(filename)), memmap=False) as hdulist: return cls.from_hdulist(hdulist, hdu=hdu) def to_table(self): """Convert to `~astropy.table.Table`.""" # TODO: fix axis order axes = MapAxes(self.data.axes[::-1]) table = axes.to_table(format="gadf-dl3") table.meta = self.meta.copy() table.meta["HDUCLAS2"] = "BKG" table["BKG"] = self.data.data.T[np.newaxis] return table def to_table_hdu(self, name="BACKGROUND"): """Convert to `~astropy.io.fits.BinTableHDU`.""" return fits.BinTableHDU(self.to_table(), name=name) def evaluate(self, fov_lon, fov_lat, energy_reco, method="linear", **kwargs): """Evaluate at given FOV position and energy. Parameters ---------- fov_lon, fov_lat : `~astropy.coordinates.Angle` FOV coordinates expecting in AltAz frame. energy_reco : `~astropy.units.Quantity` energy on which you want to interpolate. Same dimension than fov_lat and fov_lat method : str {'linear', 'nearest'}, optional Interpolation method kwargs : dict option for interpolation for `~scipy.interpolate.RegularGridInterpolator` Returns ------- array : `~astropy.units.Quantity` Interpolated values, axis order is the same as for the NDData array """ values = self.data.evaluate( fov_lon=fov_lon, fov_lat=fov_lat, energy=energy_reco, method=method, **kwargs, ) return values def evaluate_integrate( self, fov_lon, fov_lat, energy_reco, method="linear", **kwargs ): """Integrate in a given energy band. Parameters ---------- fov_lon, fov_lat : `~astropy.coordinates.Angle` FOV coordinates expecting in AltAz frame. energy_reco: `~astropy.units.Quantity` Reconstructed energy edges. method : {'linear', 'nearest'}, optional Interpolation method Returns ------- array : `~astropy.units.Quantity` Returns 2D array with axes offset """ data = self.evaluate(fov_lon, fov_lat, energy_reco, method=method) return trapz_loglog(data, energy_reco, axis=0) def to_2d(self): """Convert to `Background2D`. This takes the values at Y = 0 and X >= 0. """ # TODO: this is incorrect as it misses the Jacobian? idx_lon = self.data.axes["fov_lon"].coord_to_idx(0 * u.deg)[0] idx_lat = self.data.axes["fov_lat"].coord_to_idx(0 * u.deg)[0] data = self.data.data[:, idx_lon:, idx_lat].copy() offset = self.data.axes["fov_lon"].edges[idx_lon:] offset_axis = MapAxis.from_edges(offset, name="offset") return Background2D( energy_axis=self.data.axes["energy"], offset_axis=offset_axis, data=data, ) def peek(self, figsize=(10, 8)): return self.to_2d().peek(figsize) class Background2D: """Background 2D. Data format specification: :ref:`gadf:bkg_2d` Parameters ---------- energy_axis : `MapAxis` Energy axis offset_axis : `MapAxis` FOV coordinate offset-axis data : `~astropy.units.Quantity` Background rate (usually: ``s^-1 MeV^-1 sr^-1``) """ tag = "bkg_2d" default_interp_kwargs = dict(bounds_error=False, fill_value=None) """Default Interpolation kwargs for `~gammapy.utils.nddata.NDDataArray`. Extrapolate.""" def __init__( self, energy_axis, offset_axis, data, meta=None, interp_kwargs=None, ): if interp_kwargs is None: interp_kwargs = self.default_interp_kwargs self.data = NDDataArray( axes=[energy_axis, offset_axis], data=data, interp_kwargs=interp_kwargs ) self.data.axes.assert_names(["energy", "offset"]) self.meta = meta or {} def __str__(self): ss = self.__class__.__name__ ss += f"\n{self.data}" return ss @classmethod def from_table(cls, table): """Read from `~astropy.table.Table`.""" # Spec says key should be "BKG", but there are files around # (e.g. CTA 1DC) that use "BGD". For now we support both if "BKG" in table.colnames: bkg_name = "BKG" elif "BGD" in table.colnames: bkg_name = "BGD" else: raise ValueError('Invalid column names. Need "BKG" or "BGD".') data_unit = table[bkg_name].unit if data_unit is not None: data_unit = u.Unit(data_unit, parse_strict="silent") if isinstance(data_unit, u.UnrecognizedUnit) or (data_unit is None): data_unit = u.Unit("s-1 MeV-1 sr-1") log.warning( "Invalid unit found in background table! Assuming (s-1 MeV-1 sr-1)" ) energy_axis = MapAxis.from_table( table, column_prefix="ENERG", format="gadf-dl3" ) offset_axis = MapAxis.from_table( table, column_prefix="THETA", format="gadf-dl3" ) # TODO: The present HESS and CTA backgroundfits files # have a reverse order (theta, E) than recommened in GADF(E, theta) # For now, we suport both. data = table[bkg_name].data[0].T * data_unit shape = (energy_axis.nbin, offset_axis.nbin) if shape == shape[::-1]: log.error("Ambiguous axes order in Background fits files!") if np.shape(data) != shape: log.debug("Transposing background table on read") data = data.transpose() return cls( energy_axis=energy_axis, offset_axis=offset_axis, data=data, meta=table.meta, ) @classmethod def from_hdulist(cls, hdulist, hdu="BACKGROUND"): """Create from `~astropy.io.fits.HDUList`.""" return cls.from_table(Table.read(hdulist[hdu])) @classmethod def read(cls, filename, hdu="BACKGROUND"): """Read from file.""" with fits.open(str(make_path(filename)), memmap=False) as hdulist: return cls.from_hdulist(hdulist, hdu=hdu) def to_table(self): """Convert to `~astropy.table.Table`.""" table = self.data.axes.to_table(format="gadf-dl3") table.meta = self.meta.copy() # TODO: add other required meta data table.meta["HDUCLAS2"] = "BKG" table["BKG"] = self.data.data.T[np.newaxis] return table def to_table_hdu(self, name="BACKGROUND"): """Convert to `~astropy.io.fits.BinTableHDU`.""" return fits.BinTableHDU(self.to_table(), name=name) def evaluate(self, fov_lon, fov_lat, energy_reco, method="linear", **kwargs): """Evaluate at a given FOV position and energy. The fov_lon, fov_lat, energy_reco has to have the same shape since this is a set of points on which you want to evaluate. To have the same API than background 3D for the background evaluation, the offset is ``fov_altaz_lon``. Parameters ---------- fov_lon, fov_lat : `~astropy.coordinates.Angle` FOV coordinates expecting in AltAz frame, same shape than energy_reco energy_reco : `~astropy.units.Quantity` Reconstructed energy, same dimension than fov_lat and fov_lat method : str {'linear', 'nearest'}, optional Interpolation method kwargs : dict option for interpolation for `~scipy.interpolate.RegularGridInterpolator` Returns ------- array : `~astropy.units.Quantity` Interpolated values, axis order is the same as for the NDData array """ offset = np.sqrt(fov_lon ** 2 + fov_lat ** 2) return self.data.evaluate( offset=offset, energy=energy_reco, method=method, **kwargs ) def evaluate_integrate(self, fov_lon, fov_lat, energy_reco, method="linear"): """Evaluate at given FOV position and energy, by integrating over the energy range. Parameters ---------- fov_lon, fov_lat : `~astropy.coordinates.Angle` FOV coordinates expecting in AltAz frame. energy_reco: `~astropy.units.Quantity` Reconstructed energy edges. method : {'linear', 'nearest'}, optional Interpolation method Returns ------- array : `~astropy.units.Quantity` Returns 2D array with axes offset """ data = self.evaluate(fov_lon, fov_lat, energy_reco, method=method) return trapz_loglog(data, energy_reco, axis=0) def to_3d(self): """Convert to `Background3D`. Fill in a radially symmetric way. """ raise NotImplementedError def plot(self, ax=None, add_cbar=True, **kwargs): """Plot energy offset dependence of the background model. """ import matplotlib.pyplot as plt from matplotlib.colors import LogNorm ax = plt.gca() if ax is None else ax x = self.data.axes["energy"].edges.to_value("TeV") y = self.data.axes["offset"].edges.to_value("deg") z = self.data.data.T.value kwargs.setdefault("cmap", "GnBu") kwargs.setdefault("edgecolors", "face") caxes = ax.pcolormesh(x, y, z, norm=LogNorm(), **kwargs) ax.set_xscale("log") ax.set_ylabel(f"Offset (deg)") ax.set_xlabel(f"Energy (TeV)") xmin, xmax = x.min(), x.max() ax.set_xlim(xmin, xmax) if add_cbar: label = f"Background rate ({self.data.data.unit})" ax.figure.colorbar(caxes, ax=ax, label=label) def plot_offset_dependence(self, ax=None, offset=None, energy=None, **kwargs): """Plot background rate versus offset for a given energy. Parameters ---------- ax : `~matplotlib.axes.Axes`, optional Axis offset : `~astropy.coordinates.Angle` Offset axis energy : `~astropy.units.Quantity` Energy Returns ------- ax : `~matplotlib.axes.Axes` Axis """ import matplotlib.pyplot as plt ax = plt.gca() if ax is None else ax if energy is None: energy_axis = self.data.axes["energy"] e_min, e_max = np.log10(energy_axis.center.value[[0, -1]]) energy = np.logspace(e_min, e_max, 4) * energy_axis.unit if offset is None: offset = self.data.axes["offset"].center for ee in energy: bkg = self.data.evaluate(offset=offset, energy=ee) if np.isnan(bkg).all(): continue label = f"energy = {ee:.1f}" ax.plot(offset, bkg.value, label=label, **kwargs) ax.set_xlabel(f"Offset ({self.data.axes['offset'].unit})") ax.set_ylabel(f"Background rate ({self.data.data.unit})") ax.set_yscale("log") ax.legend(loc="upper right") return ax def plot_energy_dependence(self, ax=None, offset=None, energy=None, **kwargs): """Plot background rate versus energy for a given offset. Parameters ---------- ax : `~matplotlib.axes.Axes`, optional Axis offset : `~astropy.coordinates.Angle` Offset energy : `~astropy.units.Quantity` Energy axis kwargs : dict Forwarded tp plt.plot() Returns ------- ax : `~matplotlib.axes.Axes` Axis """ import matplotlib.pyplot as plt ax = plt.gca() if ax is None else ax if offset is None: offset_axis = self.data.axes["offset"] off_min, off_max = offset_axis.center.value[[0, -1]] offset = np.linspace(off_min, off_max, 4) * offset_axis.unit if energy is None: energy = self.data.axes["energy"].center for off in offset: bkg = self.data.evaluate(offset=off, energy=energy) kwargs.setdefault("label", f"offset = {off:.1f}") ax.plot(energy, bkg.value, **kwargs) ax.set_xscale("log") ax.set_yscale("log") ax.set_xlabel(f"Energy [{energy.unit}]") ax.set_ylabel(f"Background rate ({self.data.data.unit})") ax.set_xlim(min(energy.value), max(energy.value)) ax.legend(loc="best") return ax def plot_spectrum(self, ax=None, **kwargs): """Plot angle integrated background rate versus energy. Parameters ---------- ax : `~matplotlib.axes.Axes`, optional Axis kwargs : dict Forwarded tp plt.plot() Returns ------- ax : `~matplotlib.axes.Axes` Axis """ import matplotlib.pyplot as plt ax = plt.gca() if ax is None else ax offset = self.data.axes["offset"].edges energy = self.data.axes["energy"].center bkg = [] for ee in energy: data = self.data.evaluate(offset=offset, energy=ee) val = np.nansum(trapz_loglog(data, offset, axis=0)) bkg.append(val.value) ax.plot(energy, bkg, label="integrated spectrum", **kwargs) unit = self.data.data.unit * offset.unit * offset.unit ax.set_xscale("log") ax.set_yscale("log") ax.set_xlabel(f"Energy [{energy.unit}]") ax.set_ylabel(f"Background rate ({unit})") ax.set_xlim(min(energy.value), max(energy.value)) ax.legend(loc="best") return ax def peek(self, figsize=(10, 8)): """Quick-look summary plots.""" import matplotlib.pyplot as plt fig, axes = plt.subplots(nrows=2, ncols=2, figsize=figsize) self.plot(ax=axes[1][1]) self.plot_offset_dependence(ax=axes[0][0]) self.plot_energy_dependence(ax=axes[1][0]) self.plot_spectrum(ax=axes[0][1]) plt.tight_layout()
import netCDF4 import defopt import sys import datetime def main(*, tfile: str='', ufile: str='', vfile: str='', outputdir: str='./', jmin: int, jmax: int, imin: int, imax: int): """ subset nemo data :param tfile: name of the netCDF file containing T cell grid data :param ufile: name of the netCDF file containing u data :param vfile: name of the netCDF file containing v data :param outputdir: output directory, the files will be saved as T.nc, U.nc and V.nc :param jmin: min j index :param jmax: max j index :param imin: min i index :param imax: max i index """ # T file print(f'T file: {tfile}') nci = netCDF4.Dataset(tfile) nco = netCDF4.Dataset(f'{outputdir}/T.nc', 'w') nco.command = sys.argv nco.timestamp = f'generated on {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}' for d in nci.dimensions: print(f'creating dimension {d}') if d == 'x': nco.createDimension(d, imax - imin) elif d == 'y': nco.createDimension(d, jmax - jmin) else: nco.createDimension(d, nci.dimensions[d].size) for vname in 'bounds_lon', 'bounds_lat', 'deptht', 'deptht_bounds': print(f'creating variable {vname}') vari = nci.variables[vname] varo = nco.createVariable(vname, vari.dtype, vari.dimensions) for a in vari.ncattrs(): val = getattr(vari, a) print(f'\tattribute {a} has value {val}') setattr(varo, a, val) # write the variable if 'lon' in vname or 'lat' in vname: varo[:] = vari[jmin:jmax, imin:imax] else: varo[:] = vari[:] nco.close() nci.close() # U, V file varnameMap = {'U': 'uo', 'V': 'vo'} filenameMap = {'U': ufile, 'V': vfile} for field in 'U', 'V': nci = netCDF4.Dataset(filenameMap[field]) nco = netCDF4.Dataset(f'{outputdir}/{field}.nc', 'w') nco.command = sys.argv nco.timestamp = f'generated on {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}' for d in nci.dimensions: print(f'creating dimension {d}') if d == 'x': nco.createDimension(d, imax - imin) elif d == 'y': nco.createDimension(d, jmax - jmin) else: nco.createDimension(d, nci.dimensions[d].size) fname = varnameMap[field] for vname in 'time_counter', 'time_centered', 'time_centered_bounds', fname: print(f'creating variable {vname}') vari = nci.variables[vname] if vname in ('uo', 'vo'): varo = nco.createVariable(vname, vari.dtype, vari.dimensions, fill_value=vari._FillValue, zlib=True) else: varo = nco.createVariable(vname, vari.dtype, vari.dimensions) for a in vari.ncattrs(): if a == '_FillValue': continue val = getattr(vari, a) print(f'\tattribute {a} has value {val}') setattr(varo, a, val) # write if vname == 'uo' or vname == 'vo': varo[:] = vari[..., jmin:jmax, imin:imax] else: varo[:] = vari[:] nco.close() nci.close() if __name__ == '__main__': defopt.run(main)
import netCDF4 import defopt import sys import datetime def main(*, tfile: str='', ufile: str='', vfile: str='', outputdir: str='./', jmin: int, jmax: int, imin: int, imax: int): """ subset nemo data :param tfile: name of the netCDF file containing T cell grid data :param ufile: name of the netCDF file containing u data :param vfile: name of the netCDF file containing v data :param outputdir: output directory, the files will be saved as T.nc, U.nc and V.nc :param jmin: min j index :param jmax: max j index :param imin: min i index :param imax: max i index """ # T file print(f'T file: {tfile}') nci = netCDF4.Dataset(tfile) nco = netCDF4.Dataset(f'{outputdir}/T.nc', 'w') nco.command = sys.argv nco.timestamp = f'generated on {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}' for d in nci.dimensions: print(f'creating dimension {d}') if d == 'x': nco.createDimension(d, imax - imin) elif d == 'y': nco.createDimension(d, jmax - jmin) else: nco.createDimension(d, nci.dimensions[d].size) for vname in 'bounds_lon', 'bounds_lat', 'deptht', 'deptht_bounds': print(f'creating variable {vname}') vari = nci.variables[vname] varo = nco.createVariable(vname, vari.dtype, vari.dimensions) for a in vari.ncattrs(): val = getattr(vari, a) print(f'\tattribute {a} has value {val}') setattr(varo, a, val) # write the variable if 'lon' in vname or 'lat' in vname: varo[:] = vari[jmin:jmax, imin:imax] else: varo[:] = vari[:] nco.close() nci.close() # U, V file varnameMap = {'U': 'uo', 'V': 'vo'} filenameMap = {'U': ufile, 'V': vfile} for field in 'U', 'V': nci = netCDF4.Dataset(filenameMap[field]) nco = netCDF4.Dataset(f'{outputdir}/{field}.nc', 'w') nco.command = sys.argv nco.timestamp = f'generated on {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}' for d in nci.dimensions: print(f'creating dimension {d}') if d == 'x': nco.createDimension(d, imax - imin) elif d == 'y': nco.createDimension(d, jmax - jmin) else: nco.createDimension(d, nci.dimensions[d].size) fname = varnameMap[field] for vname in 'time_counter', 'time_centered', 'time_centered_bounds', fname: print(f'creating variable {vname}') vari = nci.variables[vname] if vname in ('uo', 'vo'): varo = nco.createVariable(vname, vari.dtype, vari.dimensions, fill_value=vari._FillValue, zlib=True) else: varo = nco.createVariable(vname, vari.dtype, vari.dimensions) for a in vari.ncattrs(): if a == '_FillValue': continue val = getattr(vari, a) print(f'\tattribute {a} has value {val}') setattr(varo, a, val) # write if vname == 'uo' or vname == 'vo': varo[:] = vari[..., jmin:jmax, imin:imax] else: varo[:] = vari[:] nco.close() nci.close() if __name__ == '__main__': defopt.run(main)
from typing import Dict, List, Optional import os from glob import glob from yaml.parser import ParserError, ScannerError from bs4 import BeautifulSoup from app_settings.app_settings import AppSettings from general_tools import file_utils from general_tools.file_utils import write_file from resource_container.ResourceContainer import RC from general_tools.file_utils import load_yaml_object def init_template(repo_subject:str, source_dir:str, output_dir:str, template_file:str): """ Tries to determine the correct templater for the appropriate repo_subject """ # AppSettings.logger.debug(f"init_template({repo_subject})") if repo_subject in ('Generic_Markdown','Open_Bible_Stories', 'Greek_Lexicon','Hebrew-Aramaic_Lexicon', 'OBS_Study_Questions', # NOTE: I don't yet understand why this works better for righthand nav column ): AppSettings.logger.info(f"Using ObsTemplater for '{repo_subject}' …") templater = ObsTemplater(repo_subject, source_dir, output_dir, template_file) elif repo_subject in ('OBS_Study_Notes','XXXOBS_Study_QuestionsXXX', 'OBS_Translation_Notes','OBS_Translation_Questions'): AppSettings.logger.info(f"Using ObsNotesTemplater for '{repo_subject}' …") templater = ObsNotesTemplater(repo_subject, source_dir, output_dir, template_file) elif repo_subject in ('Translation_Academy',): AppSettings.logger.info(f"Using TaTemplater for '{repo_subject}' …") templater = TaTemplater(repo_subject, source_dir, output_dir, template_file) elif repo_subject in ('Translation_Questions',): AppSettings.logger.info(f"Using TqTemplater for '{repo_subject}' …") templater = TqTemplater(repo_subject, source_dir, output_dir, template_file) elif repo_subject in ('Translation_Words',): AppSettings.logger.info(f"Using TwTemplater for '{repo_subject}' …") templater = TwTemplater(repo_subject, source_dir, output_dir, template_file) elif repo_subject in ('Translation_Notes','TSV_Translation_Notes'): AppSettings.logger.info(f"Using TnTemplater for '{repo_subject}' …") templater = TnTemplater(repo_subject, source_dir, output_dir, template_file) else: if repo_subject in ('Bible', 'Aligned_Bible', 'Greek_New_Testament', 'Hebrew_Old_Testament'): AppSettings.logger.info(f"Using BibleTemplater for '{repo_subject}' …") else: AppSettings.logger.critical(f"Choosing BibleTemplater for unexpected repo_subject='{repo_subject}'") templater = BibleTemplater(repo_subject, source_dir, output_dir, template_file) return templater #end of init_template function def get_sorted_Bible_html_filepath_list(folder_path:str) -> List[str]: """ Make sure that front and back "books" are ordered correctly as this list will affect the display on the web pages. See http://ubsicap.github.io/usfm/identification/books.html """ # AppSettings.logger.debug(f"get_sorted_Bible_html_filepath_list({folder_path})…") HTMLfilepaths = sorted(glob(os.path.join(folder_path, '*.html'))) for book_code, number_string in (('INT','A7'), ('FRT','A0')): # must be in reverse of desired order! for ix, filepath in enumerate( HTMLfilepaths.copy() ): if book_code in filepath and number_string in filepath: # Allows for various ordering of filename bits AppSettings.logger.info(f"Moving {book_code} HTML to front of filepath list…") HTMLfilepaths.insert(0, HTMLfilepaths.pop(ix)) # Move to front of list break return HTMLfilepaths # end of get_sorted_Bible_html_filepath_list class Templater: NO_NAV_TITLES = ['', 'Conversion requested…', 'Conversion started…', 'Conversion successful', 'Conversion successful with warnings', 'Index', 'View lexicon entry', # For Hebrew and Greek lexicons ] def __init__(self, repo_subject:str, source_dir:str, output_dir:str, template_file:str) -> None: # AppSettings.logger.debug(f"Templater.__init__(repo_subject={repo_subject}, source_dir={source_dir}, output_dir={output_dir}, template_file={template_file})…") self.repo_subject = repo_subject # This templater_CSS_class is used to set the html body class # so it must match the css in door43.org/_site/css/project-page.css assert self.templater_CSS_class # Must be set by subclass AppSettings.logger.debug(f"Using templater for '{self.templater_CSS_class}' CSS class…") if self.templater_CSS_class not in ('obs','ta','tq','tw','tn','bible'): AppSettings.logger.error(f"Unexpected templater_CSS_class='{self.templater_CSS_class}'") self.classes:List[str] = [] # These get appended to the templater_CSS_class self.source_dir = source_dir # Local directory self.output_dir = output_dir # Local directory self.template_file = template_file # Local file of template self.HTMLfilepaths = sorted(glob(os.path.join(self.source_dir, '*.html'))) self.rc = None self.template_html = '' self.already_converted = [] # The following three dictionaries will be used by the deployer to build the right-side Navigation bar self.titles:Dict[str,str] = {} self.chapters:Dict[str,str] = {} self.book_codes:Dict[str,str] = {} self.error_messages = set() # Don't want duplicates def run(self) -> bool: """ Called from ProjectDeployer.run_templater function """ # AppSettings.logger.debug("Templater.run()") # Get the resource container self.rc = RC(self.source_dir) with open(self.template_file) as template_file: self.template_html = template_file.read() soup = BeautifulSoup(self.template_html, 'html.parser') soup.body['class'] = soup.body.get('class', []) + [self.templater_CSS_class] if self.classes: for some_class in self.classes: # Check that we don't double unnecessarily assert some_class != self.templater_CSS_class soup.body['class'] = soup.body.get('class', []) + self.classes AppSettings.logger.info(f"Have {self.template_file.split("/")[-1]} body class(es)={soup.body.get("class", [])}") self.template_html = str(soup) self.apply_template() return True # end of Templater.run() @staticmethod def build_left_sidebar(filename:Optional[str]=None) -> str: html = """ <nav class="affix-top hidden-print hidden-xs hidden-sm" id="left-sidebar-nav"> <div class="nav nav-stacked" id="revisions-div"> <h1>Revisions</h1> <table width="100%" id="revisions"></table> </div> </nav> """ return html # end of Templater.build_left_sidebar static function def build_right_sidebar(self, filename:Optional[str]=None) -> str: """ Called from apply_template() """ html = self.build_page_nav(filename) return html # end of Templater.build_right_sidebar function def build_page_nav(self, filename:Optional[str]=None) -> str: raise Exception("Programmer Error: You must subclass this build_page_nav function!") # end of Templater.build_page_nav function def get_page_navigation(self) -> None: """ Called early in apply_template() Creates self.titles """ for fname in self.HTMLfilepaths: key = os.path.basename(fname) if key in self.titles: # skip if we already have data continue with open(fname, 'r') as f: soup = BeautifulSoup(f, 'html.parser') if soup.select('div#content h1'): title = soup.select('div#content h1')[0].text.strip() else: title = os.path.splitext(os.path.basename(fname))[0].replace('_', ' ').capitalize() self.titles[key] = title # end of Templater.get_page_navigation() def apply_template(self) -> None: """ Called from run() """ AppSettings.logger.info(f"Templater.apply_template() to all {len(self.HTMLfilepaths)} HTML files…") language_code = self.rc.resource.language.identifier language_name = self.rc.resource.language.title language_dir = self.rc.resource.language.direction resource_title = self.rc.resource.title self.get_page_navigation() heading = f'{language_name}: {resource_title}' title = '' canonical = '' # soup is the template that we will replace content of for every file soup = BeautifulSoup(self.template_html, 'html.parser') left_sidebar_div = soup.body.find('div', id='left-sidebar') outer_content_div = soup.body.find('div', id='outer-content') right_sidebar_div = soup.body.find('div', id='right-sidebar') # Find the outer-content div in the template if not outer_content_div: raise Exception('No div tag with id "outer-content" was found in the template') # Get the canonical UTL if not canonical: links = soup.head.find_all('link[rel="canonical"]') if len(links) == 1: canonical = links[0]['href'] # Loop through the html files for filepath in self.HTMLfilepaths: if filepath not in self.already_converted: AppSettings.logger.debug(f"Applying1 template to {filepath.rsplit("/",1)[-1]}…") # Read the downloaded file into a dom abject with open(filepath, 'r') as f: file_soup = BeautifulSoup(f, 'html.parser') # get the title from the raw html file if not title and file_soup.head and file_soup.head.title: title = file_soup.head.title.text else: title = os.path.basename(filepath) # get the language code, if we haven't yet if not language_code: if 'lang' in file_soup.html: language_code = file_soup.html['lang'] else: language_code = 'en' # get the body of the raw html file if not file_soup.body: body = BeautifulSoup('<div>No content</div>', 'html.parser') else: body = BeautifulSoup(''.join(['%s' % x for x in file_soup.body.contents]), 'html.parser') # insert new HTML into the template outer_content_div.clear() outer_content_div.append(body) soup.html['lang'] = language_code soup.html['dir'] = language_dir soup.head.title.clear() soup.head.title.append(heading+' - '+title) # set the page heading heading_span = soup.body.find('span', id='h1') heading_span.clear() heading_span.append(heading) if left_sidebar_div: left_sidebar_html = self.build_left_sidebar(filepath) left_sidebar = BeautifulSoup(left_sidebar_html, 'html.parser').nav.extract() left_sidebar_div.clear() left_sidebar_div.append(left_sidebar) if right_sidebar_div: right_sidebar_div.clear() right_sidebar_html = self.build_right_sidebar(filepath) if right_sidebar_html: right_sidebar = BeautifulSoup(right_sidebar_html, 'html.parser') if right_sidebar and right_sidebar.nav: right_sidebar_nav = right_sidebar.nav.extract() right_sidebar_div.append(right_sidebar_nav) # Render the html as a unicode string html = str(soup) # fix the footer message, removing the title of this page in parentheses as it doesn't get filled html = html.replace( '("<a xmlns:dct="http://purl.org/dc/terms/" href="https://live.door43.org/templates/project-page.html" rel="dct:source">{{ HEADING }}</a>") ', '') # update the canonical URL - it is in several different locations html = html.replace(canonical, canonical.replace('/templates/', f'/{language_code}/')) # Replace HEADING with page title in footer html = html.replace('{{ HEADING }}', title) # write to output directory out_file = os.path.join(self.output_dir, os.path.basename(filepath)) AppSettings.logger.debug(f'Templater writing {out_file} …') # write_file(out_file, html.encode('ascii', 'xmlcharrefreplace')) write_file(out_file, html) else: # if already templated, need to update navigation bar AppSettings.logger.debug(f"Applying2 template to {filepath.rsplit("/",1)[-1]}…") # Read the templated file into a dom abject with open(filepath, 'r') as f: soup = BeautifulSoup(f, 'html.parser') right_sidebar_div = soup.body.find('div', id='right-sidebar') if right_sidebar_div: right_sidebar_html = self.build_right_sidebar(filepath) right_sidebar = BeautifulSoup(right_sidebar_html, 'html.parser').nav.extract() right_sidebar_div.clear() right_sidebar_div.append(right_sidebar) # render the html as a unicode string html = str(soup) # write to output directory out_file = os.path.join(self.output_dir, os.path.basename(filepath)) AppSettings.logger.debug(f'Updating nav in {out_file} …') # write_file(out_file, html.encode('ascii', 'xmlcharrefreplace')) write_file(out_file, html) # end of Template.apply_template() # end of class Templater class ObsTemplater(Templater): def __init__(self, *args, **kwargs) -> None: self.templater_CSS_class = 'obs' super(ObsTemplater, self).__init__(*args, **kwargs) # end of ObsTemplater.__init__ function def build_page_nav(self, filename:Optional[str]=None) -> str: # AppSettings.logger.debug(f"Template.build_page_nav({filename})") # AppSettings.logger.debug(f"Have self.titles={self.titles}") html = """ <nav class="affix-top hidden-print hidden-xs hidden-sm content-nav" id="right-sidebar-nav"> <ul id="sidebar-nav" class="nav nav-stacked"> <li><h1>Navigation</h1></li> """ for fname in self.HTMLfilepaths: # AppSettings.logger.debug(f"ObsTemplater.build_page_nav: {fname}") base_name = os.path.basename(fname) title = "" if base_name in self.titles: title = self.titles[base_name] if title in self.NO_NAV_TITLES: continue # Link to other pages but not to myself html += f'<li>{title}</li>' if filename == fname \ else f'<li><a href="{os.path.basename(fname)}">{title}</a></li>' html += """ </ul> </nav> """ # AppSettings.logger.debug(f"ObsTemplater.build_page_nav returning {html}") return html # end of ObsTemplater.build_page_nav function # end of class ObsTemplater class ObsNotesTemplater(Templater): def __init__(self, *args, **kwargs) -> None: self.templater_CSS_class = 'obs' super(ObsNotesTemplater, self).__init__(*args, **kwargs) if self.repo_subject in ('OBS_Study_Notes','OBS_Translation_Notes'): self.classes=['tn'] elif self.repo_subject in ('OBS_Study_Questions','OBS_Translation_Questions'): self.classes=['tq'] # end of ObsNotesTemplater.__init__ function def build_section_toc(self, section:str) -> str: """ Recursive section toc builder :param dict section: :return: """ if 'link' in section: link = section['link'] else: link = f'section-container-{self.section_container_id}' self.section_container_id = self.section_container_id + 1 html = f""" <li> <a href="#{link}">{section['title']}</a> """ if 'sections' in section: html += f""" <a href="#" data-target="#{link}-sub" data-toggle="collapse" class="content-nav-expand collapsed"></a> <ul id="{link}-sub" class="collapse"> """ for subsection in section['sections']: html += self.build_section_toc(subsection) html += """ </ul> """ html += """ </li> """ return html # end of ObsNotesTemplater.build_section_toc function def build_page_nav(self, filename:Optional[str]=None) -> str: self.section_container_id = 1 html = """ <nav class="hidden-print hidden-xs hidden-sm content-nav" id="right-sidebar-nav"> <ul class="nav nav-stacked"> """ for fname in self.HTMLfilepaths: # with open(fname, 'r') as f: # soup = BeautifulSoup(f.read(), 'html.parser') # if soup.select('div#content h1'): # title = soup.select('div#content h1')[0].text.strip() # print(f"Got title1='{title}'") # else: title = os.path.splitext(os.path.basename(fname))[0].title() # print(f"Got title2='{title}'") if title in self.NO_NAV_TITLES: continue if fname != filename: html += f""" <h4><a href="{os.path.basename(fname)}">{title}</a></h4> """ else: html += f""" <h4>{title}</h4> """ filepath = f'{os.path.splitext(fname)[0]}-toc.yaml' try: toc = load_yaml_object(filepath) except (ParserError, ScannerError) as e: err_msg = f"Templater found badly formed '{os.path.basename(filepath)}': {e}" AppSettings.logger.critical("ObsNotes"+err_msg) self.error_messages.add(err_msg) toc = None if toc: for section in toc['sections']: html += self.build_section_toc(section) html += """ """ html += """ </ul> </nav> """ return html # end of ObsNotesTemplater.build_page_nav function # end of class ObsNotesTemplater class TqTemplater(Templater): def __init__(self, *args, **kwargs) -> None: self.templater_CSS_class = 'tq' super(TqTemplater, self).__init__(*args, **kwargs) index = file_utils.load_json_object(os.path.join(self.source_dir, 'index.json')) if index: self.titles = index['titles'] self.chapters = index['chapters'] self.book_codes = index['book_codes'] def get_page_navigation(self) -> None: """ Called early in apply_template() Creates self.titles """ for fname in self.HTMLfilepaths: key = os.path.basename(fname) if key in self.titles: # skip if we already have data continue filebase = os.path.splitext(os.path.basename(fname))[0] # Getting the book code for HTML tag references fileparts = filebase.split('-') if len(fileparts) == 2: # Assuming filename of ##-<name>.usfm, such as 01-GEN.usfm book_code = fileparts[1].lower() else: # Assuming filename of <name.usfm, such as GEN.usfm book_code = fileparts[0].lower() book_code.replace(' ', '-').replace('.', '-') # replacing spaces and periods since used as tag class with open(fname, 'r') as f: soup = BeautifulSoup(f.read(), 'html.parser') if soup.select('div#content h1'): title = soup.select('div#content h1')[0].text.strip() else: title = f'{book_code}.' self.titles[key] = title self.book_codes[key] = book_code chapters = soup.find_all('h2', {'section-header'}) # Returns a list of bs4.element.Tag's self.chapters[key] = [c['id'] for c in chapters] # end of TqTemplater.get_page_navigation() def build_page_nav(self, filename:Optional[str]=None) -> str: html = """ <nav class="hidden-print hidden-xs hidden-sm content-nav" id="right-sidebar-nav"> <ul id="sidebar-nav" class="nav nav-stacked books panel-group"> """ for fname in self.HTMLfilepaths: key = os.path.basename(fname) book_code = "" if key in self.book_codes: book_code = self.book_codes[key] title = "" if key in self.titles: title = self.titles[key] if title in self.NO_NAV_TITLES: continue html += f""" <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#sidebar-nav" href="#collapse{book_code}">{title}</a> </h4> </div> <div id="collapse{book_code}" class="panel-collapse collapse{' in' if fname == filename else ''}"> <ul class="panel-body chapters"> """ chapters = {} if key in self.chapters: chapters = self.chapters[key] for chapter in chapters: chapter_parts = chapter.split('-') label = chapter if len(chapter_parts) < 4 else chapter_parts[3].lstrip('0') html += f""" <li class="chapter"><a href="{os.path.basename(fname) if fname != filename else ''}#{chapter}">{label}</a></li> """ html += """ </ul> </div> </div> """ html += """ </ul> </nav> """ return html # end of TqTemplater.build_page_nav function # end of class TqTemplater class TwTemplater(Templater): def __init__(self, *args, **kwargs) -> None: self.templater_CSS_class = 'tw' super(TwTemplater, self).__init__(*args, **kwargs) index = file_utils.load_json_object(os.path.join(self.source_dir, 'index.json')) if index: self.titles = index['titles'] self.chapters = index['chapters'] # end of TwTemplater.__init__ function def build_page_nav(self, filename:Optional[str]=None) -> str: if not self.HTMLfilepaths or not self.titles or not self.chapters: return "" html = """ <nav class="hidden-print hidden-xs hidden-sm content-nav" id="right-sidebar-nav"> <ul class="nav nav-stacked"> """ for fname in self.HTMLfilepaths: key = os.path.basename(fname) section = os.path.splitext(key)[0] html += f""" <li{' class="active"' if fname == filename else ''}><a href="{key if fname != filename else ''}#tw-section-{section}">{self.titles[key]}</a> <a class="content-nav-expand collapsed" data-target="#section-{section}-sub" data-toggle="collapse" href="#"></a> <ul class="collapse" id="section-{section}-sub"> """ titles = self.chapters[key] terms_sorted_by_title = sorted(titles, key=lambda i: titles[i].lower()) for term in terms_sorted_by_title: html += f""" <li><a href="{key if fname != filename else ''}#{term}">{titles[term]}</a></li> """ html += """ </ul> </li> """ html += """ </ul> </nav> """ return html # end of TwTemplater.build_page_nav function # end of class TwTemplater class TnTemplater(Templater): def __init__(self, *args, **kwargs) -> None: self.templater_CSS_class = 'tn' super(TnTemplater, self).__init__(*args, **kwargs) index = file_utils.load_json_object(os.path.join(self.source_dir, 'index.json')) if index: self.titles = index['titles'] self.chapters = index['chapters'] self.book_codes = index['book_codes'] # end of TnTemplater.__init__ function def get_page_navigation(self) -> None: """ Called early in apply_template() Creates self.titles """ for fname in self.HTMLfilepaths: key = os.path.basename(fname) if key in self.titles: # skip if we already have data continue filebase = os.path.splitext(os.path.basename(fname))[0] # Getting the book code for HTML tag references fileparts = filebase.split('-') if len(fileparts) == 2: # Assuming filename of ##-<name>.usfm, such as 01-GEN.usfm book_code = fileparts[1].lower() else: # Assuming filename of <name.usfm, such as GEN.usfm book_code = fileparts[0].lower() book_code.replace(' ', '-').replace('.', '-') # replacing spaces and periods since used as tag class with open(fname, 'r') as f: soup = BeautifulSoup(f.read(), 'html.parser') if soup.select('div#content h1'): title = soup.select('div#content h1')[0].text.strip() else: title = f'{book_code}.' self.titles[key] = title self.book_codes[key] = book_code chapters = soup.find_all('h2', {'section-header'}) # Returns a list of bs4.element.Tag's self.chapters[key] = [c['id'] for c in chapters] # end of TnTemplater.get_page_navigation() def build_page_nav(self, filename:Optional[str]=None) -> str: html = """ <nav class="hidden-print hidden-xs hidden-sm content-nav" id="right-sidebar-nav"> <ul id="sidebar-nav" class="nav nav-stacked books panel-group"> """ for fname in self.HTMLfilepaths: key = os.path.basename(fname) book_code = "" if key in self.book_codes: book_code = self.book_codes[key] title = "" if key in self.titles: title = self.titles[key] if title in self.NO_NAV_TITLES: continue html += f""" <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#sidebar-nav" href="#collapse{book_code}">{title}</a> </h4> </div> <div id="collapse{book_code}" class="panel-collapse collapse{' in' if fname == filename else ''}"> <ul class="panel-body chapters"> """ chapters = {} if key in self.chapters: chapters = self.chapters[key] for chapter in chapters: chapter_parts = chapter.split('-') label = chapter if len(chapter_parts) < 4 else chapter_parts[3].lstrip('0') html += f""" <li class="chapter"><a href="{os.path.basename(fname) if fname != filename else ''}#{chapter}">{label}</a></li> """ html += """ </ul> </div> </div> """ html += """ </ul> </nav> """ return html # end of TnTemplater.build_page_nav function # end of class TnTemplater class TaTemplater(Templater): def __init__(self, *args, **kwargs) -> None: self.templater_CSS_class = 'ta' super(TaTemplater, self).__init__(*args, **kwargs) self.section_container_id = 1 # end of TaTemplater.__init__ function def build_section_toc(self, section:str) -> str: """ Recursive section toc builder :param dict section: :return: """ if 'link' in section: link = section['link'] else: link = f'section-container-{self.section_container_id}' self.section_container_id = self.section_container_id + 1 try: html = f""" <li> <a href="#{link}">{section['title']}</a> """ except KeyError: # probably missing section title html = f""" <li> <a href="#{link}">MISSING TITLE???</a> """ if 'sections' in section: html += f""" <a href="#" data-target="#{link}-sub" data-toggle="collapse" class="content-nav-expand collapsed"></a> <ul id="{link}-sub" class="collapse"> """ if section['sections']: # covers case of user leaving it empty = None for subsection in section['sections']: html += self.build_section_toc(subsection) html += """ </ul> """ html += """ </li> """ return html # end of TaTemplater.build_section_toc function def build_page_nav(self, filename:Optional[str]=None) -> str: self.section_container_id = 1 html = """ <nav class="hidden-print hidden-xs hidden-sm content-nav" id="right-sidebar-nav"> <ul class="nav nav-stacked"> """ for fname in self.HTMLfilepaths: with open(fname, 'r') as f: soup = BeautifulSoup(f.read(), 'html.parser') if soup.select('div#content h1'): title = soup.select('div#content h1')[0].text.strip() else: title = os.path.splitext(os.path.basename(fname))[0].title() if title in self.NO_NAV_TITLES: continue if fname != filename: html += f""" <h4><a href="{os.path.basename(fname)}">{title}</a></h4> """ else: html += f""" <h4>{title}</h4> """ filepath = f'{os.path.splitext(fname)[0]}-toc.yaml' try: toc = load_yaml_object(os.path.join(filepath)) except (ParserError, ScannerError) as e: err_msg = f"Templater found badly formed '{os.path.basename(filepath)}': {e}" AppSettings.logger.critical("Ta"+err_msg) self.error_messages.add(err_msg) toc = None if toc: for section in toc['sections']: html += self.build_section_toc(section) html += """ """ html += """ </ul> </nav> """ return html # end of TaTemplater.build_page_nav function # end of class TaTemplater class BibleTemplater(Templater): """ Creates the index as we go Bibles come from USFM files """ def __init__(self, *args, **kwargs) -> None: self.templater_CSS_class = 'bible' super(BibleTemplater, self).__init__(*args, **kwargs) # Make sure that front and back "books" are ordered correctly self.HTMLfilepaths = get_sorted_Bible_html_filepath_list(self.source_dir) # print( "now BibleTemplater filepaths", self.HTMLfilepaths) # end of BibleTemplater.__init__ function def get_page_navigation(self) -> None: """ Called early in apply_template() Creates self.titles and self.book_codes and self.chapters """ AppSettings.logger.debug("BibleTemplater get_page_navigation()…") assert not self.titles assert not self.book_codes assert not self.chapters for fname in self.HTMLfilepaths: key = os.path.basename(fname) if key in self.titles: # skip if we already have data continue filebase = os.path.splitext(os.path.basename(fname))[0] # Getting the book code for HTML tag references fileparts = filebase.split('-') if len(fileparts) == 2: # Assuming filename of ##-<name>.usfm, such as 01-GEN.usfm book_code = fileparts[1].lower() else: # Assuming filename of <name.usfm, such as GEN.usfm book_code = fileparts[0].lower() book_code.replace(' ', '-').replace('.', '-') # replacing spaces and periods since used as tag class self.book_codes[key] = book_code with open(fname, 'r') as f: soup = BeautifulSoup(f.read(), 'html.parser') if soup.select('div#content h1'): title = soup.select('div#content h1')[0].text.strip() else: title = f'{book_code}.' self.titles[key] = title if book_code == 'frt': self.chapters[key] = ['content'] else: # a normal Bible book chapters = soup.find_all('h2', {'c-num'}) # Returns a list of bs4.element.Tag's self.chapters[key] = [c['id'] for c in chapters] # end of BibleTemplater.get_page_navigation() def build_page_nav(self, filename:Optional[str]=None) -> str: """ Called from build_right_sidebar function """ AppSettings.logger.debug("BibleTemplater build_page_nav()…") html = """ <nav class="hidden-print hidden-xs hidden-sm content-nav" id="right-sidebar-nav"> <ul id="sidebar-nav" class="nav nav-stacked books panel-group"> """ for fname in self.HTMLfilepaths: key = os.path.basename(fname) book_code = "" if key in self.book_codes: book_code = self.book_codes[key] title = "" if key in self.titles: title = self.titles[key] if title in self.NO_NAV_TITLES: continue html += f""" <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#sidebar-nav" href="#collapse{book_code}">{title}</a> </h4> </div> <div id="collapse{book_code}" class="panel-collapse collapse{' in' if fname == filename else ''}"> <ul class="panel-body chapters"> """ chapters = {} if key in self.chapters: chapters = self.chapters[key] for chapter in chapters: chapter_parts = chapter.split('-') label = chapter if len(chapter_parts) < 3 else chapter_parts[2].lstrip('0') html += f""" <li class="chapter"><a href="{os.path.basename(fname) if fname != filename else ''}#{chapter}">{label}</a></li> """ html += """ </ul> </div> </div> """ html += """ </ul> </nav> """ return html # end of BibleTemplater.build_page_nav function # end of class BibleTemplater def do_template(repo_subject:str, source_dir:str, output_dir:str, template_file:str) -> bool: """ Only used by test_templaters.py """ templater = init_template(repo_subject, source_dir, output_dir, template_file) return templater.run() # end of do_template function
from typing import Dict, List, Optional import os from glob import glob from yaml.parser import ParserError, ScannerError from bs4 import BeautifulSoup from app_settings.app_settings import AppSettings from general_tools import file_utils from general_tools.file_utils import write_file from resource_container.ResourceContainer import RC from general_tools.file_utils import load_yaml_object def init_template(repo_subject:str, source_dir:str, output_dir:str, template_file:str): """ Tries to determine the correct templater for the appropriate repo_subject """ # AppSettings.logger.debug(f"init_template({repo_subject})") if repo_subject in ('Generic_Markdown','Open_Bible_Stories', 'Greek_Lexicon','Hebrew-Aramaic_Lexicon', 'OBS_Study_Questions', # NOTE: I don't yet understand why this works better for righthand nav column ): AppSettings.logger.info(f"Using ObsTemplater for '{repo_subject}' …") templater = ObsTemplater(repo_subject, source_dir, output_dir, template_file) elif repo_subject in ('OBS_Study_Notes','XXXOBS_Study_QuestionsXXX', 'OBS_Translation_Notes','OBS_Translation_Questions'): AppSettings.logger.info(f"Using ObsNotesTemplater for '{repo_subject}' …") templater = ObsNotesTemplater(repo_subject, source_dir, output_dir, template_file) elif repo_subject in ('Translation_Academy',): AppSettings.logger.info(f"Using TaTemplater for '{repo_subject}' …") templater = TaTemplater(repo_subject, source_dir, output_dir, template_file) elif repo_subject in ('Translation_Questions',): AppSettings.logger.info(f"Using TqTemplater for '{repo_subject}' …") templater = TqTemplater(repo_subject, source_dir, output_dir, template_file) elif repo_subject in ('Translation_Words',): AppSettings.logger.info(f"Using TwTemplater for '{repo_subject}' …") templater = TwTemplater(repo_subject, source_dir, output_dir, template_file) elif repo_subject in ('Translation_Notes','TSV_Translation_Notes'): AppSettings.logger.info(f"Using TnTemplater for '{repo_subject}' …") templater = TnTemplater(repo_subject, source_dir, output_dir, template_file) else: if repo_subject in ('Bible', 'Aligned_Bible', 'Greek_New_Testament', 'Hebrew_Old_Testament'): AppSettings.logger.info(f"Using BibleTemplater for '{repo_subject}' …") else: AppSettings.logger.critical(f"Choosing BibleTemplater for unexpected repo_subject='{repo_subject}'") templater = BibleTemplater(repo_subject, source_dir, output_dir, template_file) return templater #end of init_template function def get_sorted_Bible_html_filepath_list(folder_path:str) -> List[str]: """ Make sure that front and back "books" are ordered correctly as this list will affect the display on the web pages. See http://ubsicap.github.io/usfm/identification/books.html """ # AppSettings.logger.debug(f"get_sorted_Bible_html_filepath_list({folder_path})…") HTMLfilepaths = sorted(glob(os.path.join(folder_path, '*.html'))) for book_code, number_string in (('INT','A7'), ('FRT','A0')): # must be in reverse of desired order! for ix, filepath in enumerate( HTMLfilepaths.copy() ): if book_code in filepath and number_string in filepath: # Allows for various ordering of filename bits AppSettings.logger.info(f"Moving {book_code} HTML to front of filepath list…") HTMLfilepaths.insert(0, HTMLfilepaths.pop(ix)) # Move to front of list break return HTMLfilepaths # end of get_sorted_Bible_html_filepath_list class Templater: NO_NAV_TITLES = ['', 'Conversion requested…', 'Conversion started…', 'Conversion successful', 'Conversion successful with warnings', 'Index', 'View lexicon entry', # For Hebrew and Greek lexicons ] def __init__(self, repo_subject:str, source_dir:str, output_dir:str, template_file:str) -> None: # AppSettings.logger.debug(f"Templater.__init__(repo_subject={repo_subject}, source_dir={source_dir}, output_dir={output_dir}, template_file={template_file})…") self.repo_subject = repo_subject # This templater_CSS_class is used to set the html body class # so it must match the css in door43.org/_site/css/project-page.css assert self.templater_CSS_class # Must be set by subclass AppSettings.logger.debug(f"Using templater for '{self.templater_CSS_class}' CSS class…") if self.templater_CSS_class not in ('obs','ta','tq','tw','tn','bible'): AppSettings.logger.error(f"Unexpected templater_CSS_class='{self.templater_CSS_class}'") self.classes:List[str] = [] # These get appended to the templater_CSS_class self.source_dir = source_dir # Local directory self.output_dir = output_dir # Local directory self.template_file = template_file # Local file of template self.HTMLfilepaths = sorted(glob(os.path.join(self.source_dir, '*.html'))) self.rc = None self.template_html = '' self.already_converted = [] # The following three dictionaries will be used by the deployer to build the right-side Navigation bar self.titles:Dict[str,str] = {} self.chapters:Dict[str,str] = {} self.book_codes:Dict[str,str] = {} self.error_messages = set() # Don't want duplicates def run(self) -> bool: """ Called from ProjectDeployer.run_templater function """ # AppSettings.logger.debug("Templater.run()") # Get the resource container self.rc = RC(self.source_dir) with open(self.template_file) as template_file: self.template_html = template_file.read() soup = BeautifulSoup(self.template_html, 'html.parser') soup.body['class'] = soup.body.get('class', []) + [self.templater_CSS_class] if self.classes: for some_class in self.classes: # Check that we don't double unnecessarily assert some_class != self.templater_CSS_class soup.body['class'] = soup.body.get('class', []) + self.classes AppSettings.logger.info(f"Have {self.template_file.split('/')[-1]} body class(es)={soup.body.get('class', [])}") self.template_html = str(soup) self.apply_template() return True # end of Templater.run() @staticmethod def build_left_sidebar(filename:Optional[str]=None) -> str: html = """ <nav class="affix-top hidden-print hidden-xs hidden-sm" id="left-sidebar-nav"> <div class="nav nav-stacked" id="revisions-div"> <h1>Revisions</h1> <table width="100%" id="revisions"></table> </div> </nav> """ return html # end of Templater.build_left_sidebar static function def build_right_sidebar(self, filename:Optional[str]=None) -> str: """ Called from apply_template() """ html = self.build_page_nav(filename) return html # end of Templater.build_right_sidebar function def build_page_nav(self, filename:Optional[str]=None) -> str: raise Exception("Programmer Error: You must subclass this build_page_nav function!") # end of Templater.build_page_nav function def get_page_navigation(self) -> None: """ Called early in apply_template() Creates self.titles """ for fname in self.HTMLfilepaths: key = os.path.basename(fname) if key in self.titles: # skip if we already have data continue with open(fname, 'r') as f: soup = BeautifulSoup(f, 'html.parser') if soup.select('div#content h1'): title = soup.select('div#content h1')[0].text.strip() else: title = os.path.splitext(os.path.basename(fname))[0].replace('_', ' ').capitalize() self.titles[key] = title # end of Templater.get_page_navigation() def apply_template(self) -> None: """ Called from run() """ AppSettings.logger.info(f"Templater.apply_template() to all {len(self.HTMLfilepaths)} HTML files…") language_code = self.rc.resource.language.identifier language_name = self.rc.resource.language.title language_dir = self.rc.resource.language.direction resource_title = self.rc.resource.title self.get_page_navigation() heading = f'{language_name}: {resource_title}' title = '' canonical = '' # soup is the template that we will replace content of for every file soup = BeautifulSoup(self.template_html, 'html.parser') left_sidebar_div = soup.body.find('div', id='left-sidebar') outer_content_div = soup.body.find('div', id='outer-content') right_sidebar_div = soup.body.find('div', id='right-sidebar') # Find the outer-content div in the template if not outer_content_div: raise Exception('No div tag with id "outer-content" was found in the template') # Get the canonical UTL if not canonical: links = soup.head.find_all('link[rel="canonical"]') if len(links) == 1: canonical = links[0]['href'] # Loop through the html files for filepath in self.HTMLfilepaths: if filepath not in self.already_converted: AppSettings.logger.debug(f"Applying1 template to {filepath.rsplit('/',1)[-1]}…") # Read the downloaded file into a dom abject with open(filepath, 'r') as f: file_soup = BeautifulSoup(f, 'html.parser') # get the title from the raw html file if not title and file_soup.head and file_soup.head.title: title = file_soup.head.title.text else: title = os.path.basename(filepath) # get the language code, if we haven't yet if not language_code: if 'lang' in file_soup.html: language_code = file_soup.html['lang'] else: language_code = 'en' # get the body of the raw html file if not file_soup.body: body = BeautifulSoup('<div>No content</div>', 'html.parser') else: body = BeautifulSoup(''.join(['%s' % x for x in file_soup.body.contents]), 'html.parser') # insert new HTML into the template outer_content_div.clear() outer_content_div.append(body) soup.html['lang'] = language_code soup.html['dir'] = language_dir soup.head.title.clear() soup.head.title.append(heading+' - '+title) # set the page heading heading_span = soup.body.find('span', id='h1') heading_span.clear() heading_span.append(heading) if left_sidebar_div: left_sidebar_html = self.build_left_sidebar(filepath) left_sidebar = BeautifulSoup(left_sidebar_html, 'html.parser').nav.extract() left_sidebar_div.clear() left_sidebar_div.append(left_sidebar) if right_sidebar_div: right_sidebar_div.clear() right_sidebar_html = self.build_right_sidebar(filepath) if right_sidebar_html: right_sidebar = BeautifulSoup(right_sidebar_html, 'html.parser') if right_sidebar and right_sidebar.nav: right_sidebar_nav = right_sidebar.nav.extract() right_sidebar_div.append(right_sidebar_nav) # Render the html as a unicode string html = str(soup) # fix the footer message, removing the title of this page in parentheses as it doesn't get filled html = html.replace( '("<a xmlns:dct="http://purl.org/dc/terms/" href="https://live.door43.org/templates/project-page.html" rel="dct:source">{{ HEADING }}</a>") ', '') # update the canonical URL - it is in several different locations html = html.replace(canonical, canonical.replace('/templates/', f'/{language_code}/')) # Replace HEADING with page title in footer html = html.replace('{{ HEADING }}', title) # write to output directory out_file = os.path.join(self.output_dir, os.path.basename(filepath)) AppSettings.logger.debug(f'Templater writing {out_file} …') # write_file(out_file, html.encode('ascii', 'xmlcharrefreplace')) write_file(out_file, html) else: # if already templated, need to update navigation bar AppSettings.logger.debug(f"Applying2 template to {filepath.rsplit('/',1)[-1]}…") # Read the templated file into a dom abject with open(filepath, 'r') as f: soup = BeautifulSoup(f, 'html.parser') right_sidebar_div = soup.body.find('div', id='right-sidebar') if right_sidebar_div: right_sidebar_html = self.build_right_sidebar(filepath) right_sidebar = BeautifulSoup(right_sidebar_html, 'html.parser').nav.extract() right_sidebar_div.clear() right_sidebar_div.append(right_sidebar) # render the html as a unicode string html = str(soup) # write to output directory out_file = os.path.join(self.output_dir, os.path.basename(filepath)) AppSettings.logger.debug(f'Updating nav in {out_file} …') # write_file(out_file, html.encode('ascii', 'xmlcharrefreplace')) write_file(out_file, html) # end of Template.apply_template() # end of class Templater class ObsTemplater(Templater): def __init__(self, *args, **kwargs) -> None: self.templater_CSS_class = 'obs' super(ObsTemplater, self).__init__(*args, **kwargs) # end of ObsTemplater.__init__ function def build_page_nav(self, filename:Optional[str]=None) -> str: # AppSettings.logger.debug(f"Template.build_page_nav({filename})") # AppSettings.logger.debug(f"Have self.titles={self.titles}") html = """ <nav class="affix-top hidden-print hidden-xs hidden-sm content-nav" id="right-sidebar-nav"> <ul id="sidebar-nav" class="nav nav-stacked"> <li><h1>Navigation</h1></li> """ for fname in self.HTMLfilepaths: # AppSettings.logger.debug(f"ObsTemplater.build_page_nav: {fname}") base_name = os.path.basename(fname) title = "" if base_name in self.titles: title = self.titles[base_name] if title in self.NO_NAV_TITLES: continue # Link to other pages but not to myself html += f'<li>{title}</li>' if filename == fname \ else f'<li><a href="{os.path.basename(fname)}">{title}</a></li>' html += """ </ul> </nav> """ # AppSettings.logger.debug(f"ObsTemplater.build_page_nav returning {html}") return html # end of ObsTemplater.build_page_nav function # end of class ObsTemplater class ObsNotesTemplater(Templater): def __init__(self, *args, **kwargs) -> None: self.templater_CSS_class = 'obs' super(ObsNotesTemplater, self).__init__(*args, **kwargs) if self.repo_subject in ('OBS_Study_Notes','OBS_Translation_Notes'): self.classes=['tn'] elif self.repo_subject in ('OBS_Study_Questions','OBS_Translation_Questions'): self.classes=['tq'] # end of ObsNotesTemplater.__init__ function def build_section_toc(self, section:str) -> str: """ Recursive section toc builder :param dict section: :return: """ if 'link' in section: link = section['link'] else: link = f'section-container-{self.section_container_id}' self.section_container_id = self.section_container_id + 1 html = f""" <li> <a href="#{link}">{section['title']}</a> """ if 'sections' in section: html += f""" <a href="#" data-target="#{link}-sub" data-toggle="collapse" class="content-nav-expand collapsed"></a> <ul id="{link}-sub" class="collapse"> """ for subsection in section['sections']: html += self.build_section_toc(subsection) html += """ </ul> """ html += """ </li> """ return html # end of ObsNotesTemplater.build_section_toc function def build_page_nav(self, filename:Optional[str]=None) -> str: self.section_container_id = 1 html = """ <nav class="hidden-print hidden-xs hidden-sm content-nav" id="right-sidebar-nav"> <ul class="nav nav-stacked"> """ for fname in self.HTMLfilepaths: # with open(fname, 'r') as f: # soup = BeautifulSoup(f.read(), 'html.parser') # if soup.select('div#content h1'): # title = soup.select('div#content h1')[0].text.strip() # print(f"Got title1='{title}'") # else: title = os.path.splitext(os.path.basename(fname))[0].title() # print(f"Got title2='{title}'") if title in self.NO_NAV_TITLES: continue if fname != filename: html += f""" <h4><a href="{os.path.basename(fname)}">{title}</a></h4> """ else: html += f""" <h4>{title}</h4> """ filepath = f'{os.path.splitext(fname)[0]}-toc.yaml' try: toc = load_yaml_object(filepath) except (ParserError, ScannerError) as e: err_msg = f"Templater found badly formed '{os.path.basename(filepath)}': {e}" AppSettings.logger.critical("ObsNotes"+err_msg) self.error_messages.add(err_msg) toc = None if toc: for section in toc['sections']: html += self.build_section_toc(section) html += """ """ html += """ </ul> </nav> """ return html # end of ObsNotesTemplater.build_page_nav function # end of class ObsNotesTemplater class TqTemplater(Templater): def __init__(self, *args, **kwargs) -> None: self.templater_CSS_class = 'tq' super(TqTemplater, self).__init__(*args, **kwargs) index = file_utils.load_json_object(os.path.join(self.source_dir, 'index.json')) if index: self.titles = index['titles'] self.chapters = index['chapters'] self.book_codes = index['book_codes'] def get_page_navigation(self) -> None: """ Called early in apply_template() Creates self.titles """ for fname in self.HTMLfilepaths: key = os.path.basename(fname) if key in self.titles: # skip if we already have data continue filebase = os.path.splitext(os.path.basename(fname))[0] # Getting the book code for HTML tag references fileparts = filebase.split('-') if len(fileparts) == 2: # Assuming filename of ##-<name>.usfm, such as 01-GEN.usfm book_code = fileparts[1].lower() else: # Assuming filename of <name.usfm, such as GEN.usfm book_code = fileparts[0].lower() book_code.replace(' ', '-').replace('.', '-') # replacing spaces and periods since used as tag class with open(fname, 'r') as f: soup = BeautifulSoup(f.read(), 'html.parser') if soup.select('div#content h1'): title = soup.select('div#content h1')[0].text.strip() else: title = f'{book_code}.' self.titles[key] = title self.book_codes[key] = book_code chapters = soup.find_all('h2', {'section-header'}) # Returns a list of bs4.element.Tag's self.chapters[key] = [c['id'] for c in chapters] # end of TqTemplater.get_page_navigation() def build_page_nav(self, filename:Optional[str]=None) -> str: html = """ <nav class="hidden-print hidden-xs hidden-sm content-nav" id="right-sidebar-nav"> <ul id="sidebar-nav" class="nav nav-stacked books panel-group"> """ for fname in self.HTMLfilepaths: key = os.path.basename(fname) book_code = "" if key in self.book_codes: book_code = self.book_codes[key] title = "" if key in self.titles: title = self.titles[key] if title in self.NO_NAV_TITLES: continue html += f""" <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#sidebar-nav" href="#collapse{book_code}">{title}</a> </h4> </div> <div id="collapse{book_code}" class="panel-collapse collapse{' in' if fname == filename else ''}"> <ul class="panel-body chapters"> """ chapters = {} if key in self.chapters: chapters = self.chapters[key] for chapter in chapters: chapter_parts = chapter.split('-') label = chapter if len(chapter_parts) < 4 else chapter_parts[3].lstrip('0') html += f""" <li class="chapter"><a href="{os.path.basename(fname) if fname != filename else ''}#{chapter}">{label}</a></li> """ html += """ </ul> </div> </div> """ html += """ </ul> </nav> """ return html # end of TqTemplater.build_page_nav function # end of class TqTemplater class TwTemplater(Templater): def __init__(self, *args, **kwargs) -> None: self.templater_CSS_class = 'tw' super(TwTemplater, self).__init__(*args, **kwargs) index = file_utils.load_json_object(os.path.join(self.source_dir, 'index.json')) if index: self.titles = index['titles'] self.chapters = index['chapters'] # end of TwTemplater.__init__ function def build_page_nav(self, filename:Optional[str]=None) -> str: if not self.HTMLfilepaths or not self.titles or not self.chapters: return "" html = """ <nav class="hidden-print hidden-xs hidden-sm content-nav" id="right-sidebar-nav"> <ul class="nav nav-stacked"> """ for fname in self.HTMLfilepaths: key = os.path.basename(fname) section = os.path.splitext(key)[0] html += f""" <li{' class="active"' if fname == filename else ''}><a href="{key if fname != filename else ''}#tw-section-{section}">{self.titles[key]}</a> <a class="content-nav-expand collapsed" data-target="#section-{section}-sub" data-toggle="collapse" href="#"></a> <ul class="collapse" id="section-{section}-sub"> """ titles = self.chapters[key] terms_sorted_by_title = sorted(titles, key=lambda i: titles[i].lower()) for term in terms_sorted_by_title: html += f""" <li><a href="{key if fname != filename else ''}#{term}">{titles[term]}</a></li> """ html += """ </ul> </li> """ html += """ </ul> </nav> """ return html # end of TwTemplater.build_page_nav function # end of class TwTemplater class TnTemplater(Templater): def __init__(self, *args, **kwargs) -> None: self.templater_CSS_class = 'tn' super(TnTemplater, self).__init__(*args, **kwargs) index = file_utils.load_json_object(os.path.join(self.source_dir, 'index.json')) if index: self.titles = index['titles'] self.chapters = index['chapters'] self.book_codes = index['book_codes'] # end of TnTemplater.__init__ function def get_page_navigation(self) -> None: """ Called early in apply_template() Creates self.titles """ for fname in self.HTMLfilepaths: key = os.path.basename(fname) if key in self.titles: # skip if we already have data continue filebase = os.path.splitext(os.path.basename(fname))[0] # Getting the book code for HTML tag references fileparts = filebase.split('-') if len(fileparts) == 2: # Assuming filename of ##-<name>.usfm, such as 01-GEN.usfm book_code = fileparts[1].lower() else: # Assuming filename of <name.usfm, such as GEN.usfm book_code = fileparts[0].lower() book_code.replace(' ', '-').replace('.', '-') # replacing spaces and periods since used as tag class with open(fname, 'r') as f: soup = BeautifulSoup(f.read(), 'html.parser') if soup.select('div#content h1'): title = soup.select('div#content h1')[0].text.strip() else: title = f'{book_code}.' self.titles[key] = title self.book_codes[key] = book_code chapters = soup.find_all('h2', {'section-header'}) # Returns a list of bs4.element.Tag's self.chapters[key] = [c['id'] for c in chapters] # end of TnTemplater.get_page_navigation() def build_page_nav(self, filename:Optional[str]=None) -> str: html = """ <nav class="hidden-print hidden-xs hidden-sm content-nav" id="right-sidebar-nav"> <ul id="sidebar-nav" class="nav nav-stacked books panel-group"> """ for fname in self.HTMLfilepaths: key = os.path.basename(fname) book_code = "" if key in self.book_codes: book_code = self.book_codes[key] title = "" if key in self.titles: title = self.titles[key] if title in self.NO_NAV_TITLES: continue html += f""" <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#sidebar-nav" href="#collapse{book_code}">{title}</a> </h4> </div> <div id="collapse{book_code}" class="panel-collapse collapse{' in' if fname == filename else ''}"> <ul class="panel-body chapters"> """ chapters = {} if key in self.chapters: chapters = self.chapters[key] for chapter in chapters: chapter_parts = chapter.split('-') label = chapter if len(chapter_parts) < 4 else chapter_parts[3].lstrip('0') html += f""" <li class="chapter"><a href="{os.path.basename(fname) if fname != filename else ''}#{chapter}">{label}</a></li> """ html += """ </ul> </div> </div> """ html += """ </ul> </nav> """ return html # end of TnTemplater.build_page_nav function # end of class TnTemplater class TaTemplater(Templater): def __init__(self, *args, **kwargs) -> None: self.templater_CSS_class = 'ta' super(TaTemplater, self).__init__(*args, **kwargs) self.section_container_id = 1 # end of TaTemplater.__init__ function def build_section_toc(self, section:str) -> str: """ Recursive section toc builder :param dict section: :return: """ if 'link' in section: link = section['link'] else: link = f'section-container-{self.section_container_id}' self.section_container_id = self.section_container_id + 1 try: html = f""" <li> <a href="#{link}">{section['title']}</a> """ except KeyError: # probably missing section title html = f""" <li> <a href="#{link}">MISSING TITLE???</a> """ if 'sections' in section: html += f""" <a href="#" data-target="#{link}-sub" data-toggle="collapse" class="content-nav-expand collapsed"></a> <ul id="{link}-sub" class="collapse"> """ if section['sections']: # covers case of user leaving it empty = None for subsection in section['sections']: html += self.build_section_toc(subsection) html += """ </ul> """ html += """ </li> """ return html # end of TaTemplater.build_section_toc function def build_page_nav(self, filename:Optional[str]=None) -> str: self.section_container_id = 1 html = """ <nav class="hidden-print hidden-xs hidden-sm content-nav" id="right-sidebar-nav"> <ul class="nav nav-stacked"> """ for fname in self.HTMLfilepaths: with open(fname, 'r') as f: soup = BeautifulSoup(f.read(), 'html.parser') if soup.select('div#content h1'): title = soup.select('div#content h1')[0].text.strip() else: title = os.path.splitext(os.path.basename(fname))[0].title() if title in self.NO_NAV_TITLES: continue if fname != filename: html += f""" <h4><a href="{os.path.basename(fname)}">{title}</a></h4> """ else: html += f""" <h4>{title}</h4> """ filepath = f'{os.path.splitext(fname)[0]}-toc.yaml' try: toc = load_yaml_object(os.path.join(filepath)) except (ParserError, ScannerError) as e: err_msg = f"Templater found badly formed '{os.path.basename(filepath)}': {e}" AppSettings.logger.critical("Ta"+err_msg) self.error_messages.add(err_msg) toc = None if toc: for section in toc['sections']: html += self.build_section_toc(section) html += """ """ html += """ </ul> </nav> """ return html # end of TaTemplater.build_page_nav function # end of class TaTemplater class BibleTemplater(Templater): """ Creates the index as we go Bibles come from USFM files """ def __init__(self, *args, **kwargs) -> None: self.templater_CSS_class = 'bible' super(BibleTemplater, self).__init__(*args, **kwargs) # Make sure that front and back "books" are ordered correctly self.HTMLfilepaths = get_sorted_Bible_html_filepath_list(self.source_dir) # print( "now BibleTemplater filepaths", self.HTMLfilepaths) # end of BibleTemplater.__init__ function def get_page_navigation(self) -> None: """ Called early in apply_template() Creates self.titles and self.book_codes and self.chapters """ AppSettings.logger.debug("BibleTemplater get_page_navigation()…") assert not self.titles assert not self.book_codes assert not self.chapters for fname in self.HTMLfilepaths: key = os.path.basename(fname) if key in self.titles: # skip if we already have data continue filebase = os.path.splitext(os.path.basename(fname))[0] # Getting the book code for HTML tag references fileparts = filebase.split('-') if len(fileparts) == 2: # Assuming filename of ##-<name>.usfm, such as 01-GEN.usfm book_code = fileparts[1].lower() else: # Assuming filename of <name.usfm, such as GEN.usfm book_code = fileparts[0].lower() book_code.replace(' ', '-').replace('.', '-') # replacing spaces and periods since used as tag class self.book_codes[key] = book_code with open(fname, 'r') as f: soup = BeautifulSoup(f.read(), 'html.parser') if soup.select('div#content h1'): title = soup.select('div#content h1')[0].text.strip() else: title = f'{book_code}.' self.titles[key] = title if book_code == 'frt': self.chapters[key] = ['content'] else: # a normal Bible book chapters = soup.find_all('h2', {'c-num'}) # Returns a list of bs4.element.Tag's self.chapters[key] = [c['id'] for c in chapters] # end of BibleTemplater.get_page_navigation() def build_page_nav(self, filename:Optional[str]=None) -> str: """ Called from build_right_sidebar function """ AppSettings.logger.debug("BibleTemplater build_page_nav()…") html = """ <nav class="hidden-print hidden-xs hidden-sm content-nav" id="right-sidebar-nav"> <ul id="sidebar-nav" class="nav nav-stacked books panel-group"> """ for fname in self.HTMLfilepaths: key = os.path.basename(fname) book_code = "" if key in self.book_codes: book_code = self.book_codes[key] title = "" if key in self.titles: title = self.titles[key] if title in self.NO_NAV_TITLES: continue html += f""" <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#sidebar-nav" href="#collapse{book_code}">{title}</a> </h4> </div> <div id="collapse{book_code}" class="panel-collapse collapse{' in' if fname == filename else ''}"> <ul class="panel-body chapters"> """ chapters = {} if key in self.chapters: chapters = self.chapters[key] for chapter in chapters: chapter_parts = chapter.split('-') label = chapter if len(chapter_parts) < 3 else chapter_parts[2].lstrip('0') html += f""" <li class="chapter"><a href="{os.path.basename(fname) if fname != filename else ''}#{chapter}">{label}</a></li> """ html += """ </ul> </div> </div> """ html += """ </ul> </nav> """ return html # end of BibleTemplater.build_page_nav function # end of class BibleTemplater def do_template(repo_subject:str, source_dir:str, output_dir:str, template_file:str) -> bool: """ Only used by test_templaters.py """ templater = init_template(repo_subject, source_dir, output_dir, template_file) return templater.run() # end of do_template function
#from bottom_up import maximumScore from memo_recursion import maximumScore if __name__ == "__main__": print("TestCase-1") nums = [1,2,3] multipliers = [3,2,1] ans = maximumScore(nums, multipliers) expected = 14 #print(f"{"Correct" if ans == expected else "Incorrect"}") print(f"{"Correct" if ans == expected else f"Incorrect: ans = {ans}, expected = {expected}'}") print() print("TestCase-2") nums = [-5,-3,-3,-2,7,1] multipliers = [-10,-5,3,4,6] ans = maximumScore(nums, multipliers) expected = 102 print(f"{"Correct" if ans == expected else f"Incorrect: ans = {ans}, expected = {expected}'}") print() print("TestCase11") nums = [920,108,-649,-682,-778,-268,-611,795,-877,-338,804,931,959,-754,-909,-9,-245,-553,-296,500,-190,-227,-258,-683,-1000,-833,505,481,419,-29,341,522,-495,109,-106,543,616,491,-143,766,769,1000,-378,341,498,-456,14,428,470,-917,133,454,-411,-64,551,929,-186,396,-822,-781,348,445,-786,-330,334,856,-204,-294,483,-802,-138,960,991,949,-294,355,-856,-437,-413,307,-950,-263,-506,-668,60,957,-654,-726,711,-799,-222,761,865,706,626,-384,922,590,891,-784,853,-82,79,-149,420,-546,887,-57,-415,728,586,-260,176,-56,-907,839,-664,821,213,-59,394,-204,-327,-163,-874,-557,-15,646,937,-538,171,-115,491,878,963,332,-573,962,287,980,792,325,537,657,146,-899,-497,595,-644,703,-212,23,-941,-944,402,267,894,-393,1000,766,44,864,-231,373,484,404,441,-554,650,-847,181,-141,506,970,619,427,-239,413,-294,-408,-249,-101,-255,357,-608,-946,-431,639,464,-797,836,-272,850,-253,-383,902,579,836,-786,-802,493,85,-982,-757,348,742,-418,149,-748,126,-150,831,-217,-752,-961,-664,-864,408,-713,403,805,-200,-858,-716,-849,-249,67,650,662,619,-108,608,-43,168,-225,582,3,-624,899,394,692] multipliers = [-112,19,-462,-463,-575,-337,-167,11,-736,-441,-811,94,-37,-841,-515,184,-697,-361,-143,892,697,-609,461,872,685,801,-653,417,329,876,372,118,346,-207,-631,-122,214,233,-628,931,846,-824,819,868,-802,132,-728,-241,-669,-757,693,485,-117,488,659,237,-687,219,-871,727,697,630,-106,207,-564,818,-561,-999,329,-454,367,490,-144,-85,522,-136,-161,115,130,801,-368,447,943,555,-271,-643,216,-456,-935,663,822,263,-387,167,-928,-371,-805,972,-962,661,-1000,-283,-883,865,-311,-88,-924,334,850,-806,-111,-387,7,-822,708,-847,-932,-142,403,921,443,16,982,-423,-508,519,-14,967,-88,-765,679,-697,-682,-448,741,-416,96,0,-498,968,-927,222,686,461,489,356,885,618,134,121,-298,-208,571,-425,603,532,-463,908,480,852,-418,-597] ans = maximumScore(nums, multipliers) expected = 43563107 print(f"{"Correct" if ans == expected else f"Incorrect: ans = {ans}, expected = {expected}'}") print() print("TestCase50") nums = [822,963,170,305,258,841,204,748,850,721,824,405,108,843,76,78,848,318,105,530,703,38,875,785,223,733,310,402,450,447,712,253,369,189,232,478,990,681,847,137,706,789,241,457,351,91,445,823,780,555,144,866,286,808,147,334,818,751,286,60,90,88,53,850,513,694,727,100,335,137,92,37,806,963,566,948,193,838,299,299,655,777,50,353,681,65,47,768,562,854,553,939,334,419,570,704,601,735,123,602,621,910,821,327,526,613,455,979,32,876,974,359,765,248,313,380,127,382,551,987,720,753,382,962,415,7,973,648,194,399,379,717,462,682,488,835,781,599,841,890,520,24,296,702,2,690,613,983,653,485,907,643,458,811,100,254,964,990,708,413,543,632,584,324,843,415,849,976,727,894,380,318,513,818,228,971,990,13,373,882,433,84,986,303,891,789,775,612,612,470,509,718,566,416,236,710,875,861,905,758,400,467,116,297,140,527,43,950,794,475,954,140,743,403,506,252,623,479,960,379,161,140,702,677,700,52,77,428,258,545,926,999,45,436,99,810,823,733,683,199,625,766,547,574,483,535,625,954,173,136,470,149,956,509,929,119,228,194,146,968,901,883,530,161,885,949,137,726,697,313,717,781,169,678,377,53,114,273,517,866,595,546,288,448,16,855,748,754,88,960,451,872,52,911,178,652,70,108,116,461,72,590,11,71,633,531,276,298,425,452,338,325,191,123,386,21,120,288,263,511,639,279,195,865,957,606,180,587,344,526,707,383,671,764,985,85,116,506,835,691,702,705,292,220,926,480,82,953,612,191,127,943,191,82,998,920,171,824,12,487,357,684,918,939,738,495,132,239,550,329,831,127,523,91,624,760,577,996,283,492,127,955,747,701,629,5,723,383,528,97,914,211,573,320,416,52,190,137,695,283,91,559,695,348,679,855,380,561,705,66,183,847,568,579,805,423,926,904,934,73,539,382,698,398,953,831,157,923,747,68,312,825,517,463,365,884,179,549,811,299,125,34,734,844,40,604,282,55,420,234,195,324,170,605,842,300,943,451,507,276,156,97,131,691,103,782,886,583,485,269,636,415,276,105,141,86,229,858,923,526,431,469,647,678,673,316,97,397,546,658,395,158,162,939,136,953,519,475,986,611,378,133,23,897,112,558,245,732,732,683,131,648,719,688,967,415,666,2,68,206,915,43,346,477,645,841,747,200,533,81,216,785,204,832,390,755,782,629,925,523,954,602,628,299,490,30,406,183,157,428,232,206,887,411,796,397,843,574,277,665,963,497,108,759,763,406,646,397,100,419,299,718,517,315,189,604,623,792,928,72,689,955,604,262,148,706,955,169,956,311,955,903,562,600,840,403,346,115,107,815,135,488,363,629,889,404,316,595,30,934,121,194,246,444,465,878,942,886,545,8,746,516,42,726,883,821,827,386,749,945,313,386,237,612,108,965,280,390,136,74,989,692,764,91,335,268,979,13,349,46,403,592,168,198,27,191,801,80,41,256,228,127,521,998,257,93,779,484,922,924,931,894,336,133,492,815,972,524,136,918,96,192,25,367,86,784,378,583,677,971,507,550,638,436,1000,684,31,565,627,915,517,221,930,523,900,472,776,892,779,576,490,27,87,517,301,570,747,481,596,360,276,884,891,784,951,250,99,711,538,560,951,578,725,686,765,543,224,399,458,558,593,447,367,56,778,264,644,725,961,598,829,45,433,286,747,343,94,486,462,135,877,469,822,137,843,501,18,939,182,618,486,442,444,907,549,455,216,461,684,29,440,365,506,481,301,855,225,195,112,894,398,909,878,226,480,514,742,722,344,113,401,941,297,349,32,558,397,989,961,478,56,302,350,53,658,529,444,888,40,468,104,895,629,365,611,56,639,716,181,988,91,742,712,596,588,339,795,406,127,558,181,701,24,861,338,509,680,203,730,444,331,913,770,902,720,186,812,226,350,760,343,995,330,367,734,963,758,858,591,847,68,780,812,255,695,268,955,919,347,60,86,566,156,134,59,738,491,804,367,88,780,364,306,967,772,43,130,957,565,57,485,418,169,861,599,28,109,440,194,833,799,129,945,443,147,21,368,641,798,32,9,638,366,694,836,1000,811,515,898,741,717,889,458,209,556,611,825,288,755,450,942,799,404,801,892,29,375,545,859,207,573,194,885,227,983,148,219,903,875,319,668,492,732,747,410,217,473,718,564,897,876,8,305,204,576,747,290,604,315,25,156,28,48,897,735,90,760,962,26,135,545,535,775,917,330,564,738,298,19,99,278,540,781,632,659,343,193,478,608,600,657,1000,816,412,802,931,655,896,157,865,218,87,683,271,144,964,695,907,460,865,901,759,657,887,486,564,545,188,258,827,403,173,750,55,859,857,511,758,300,832,975,37,258,332,74,179,26,117,852,624,250,229,54,139,963,453,728,440,247,442,901,253,592,301,557,367,558,732,151,975,279,815,520,424,810,215,396,362,259,786,356,777,57,407,76,330,751,178,440,802,329,851,112,788,938,697,399,249,478,258,474,978,699,576,616,932,576,682,361,502,357,894,957,803,529,521,443,208,87,441,247,531,990,148,123,527,798,207,227,43,46,850,935,393,271,633,897,955,781,584,463,309,36,864,960,152,754,998,679,356,785,46,228,55,692,460,733,492,378,592,135,925,797,748,593,932,393,353,223,947,396,953,685,186,748,383,824,262,76,758,730,725,950,462,464,286,513,765,343,723,873,671,934,86,325,335,73,754,726,863,179,880,916,339,256,541,200,837,932,624,639,88,36,209,841,736,662,849,586,738,516,776,743,831,757,480,818,382,993,290,163,464,602,907,414,348,501,665,928,225,124,257,922,839,305,890,568,870,106,898,454,169,559,790,236,646,347,41,949,333,887,211,984,349,26,622,900,156,461,226,617,333,976,32,342,442,995,99,726,951,114,329,67,602,358,306,844,124,465,383,548,265,213,106,720,917,526,759,316,619,18,83,461,649,579,75,493,568,604,482,796,431,503,67,169,312,509,772,591,509,372,635,620,359,253,137,535,732,919,746,186,95,441,28,309,112,924,260,389,1,414,130,640,162,177,106,867,302,879,7,553,790,762,796,977,647,111,342,866,944,657,974,434,894,641,382,982,891,407,779,838,138,659,432,706,725,969,361,631,256,33,226,678,840,820,582,847,816,658,611,190,84,627,420,239,870,121,1000,754,665,612,767,541,780,22,141,954,245,287,687,5,939,783,373,76,995,316,160,601,284,808,833,880,870,85,838,129,276,977,810,295,890,299,718,376,980,685,196,439,90,371,573,682,868,370,298,616,689,492,502,212,260,320,219,310,997,972,42,989,216,318,240,227,519,461,161,829,147,451,345,493,408,44,1,601,288,889,794,569,646,105,110,428,233,765,953,674,967,236,227,600,400,532,770,110,192,637,925,659,730,478,957,864,560,85,173,488,645,853,49,556,85,553,781,478,576,926,38,931,536,337,534,161,166,606,318,390,491,972,95,162,841,856,13,967,334,673,354,481,654,914,456,393,303,145,288,144,651,33,584,698,754,78,614,700,96,719,838,947,974,513,884,133,23,746,879,672,922,893,609,620,468,121,966,42,994,935,199,56,481,285,292,568,776,830,163,742,663,768,974,634,293,934,803,413,364,880,38,922,241,387,389,810,341,466,500,486,285,57,453,951,804,563,874,138,382,234,290,645,64,51,977,322,59,424,265,451,10,226,503,34,445,10,614,256,336,285,512,31,583,732,61,744,162,624,226,905,516,788,898,587,426,38,22,130,708,653,531,56,803,440,154,698,646,684,943,108,455,595,469,450,78,130,536,227,766,384,904,295,116,298,838,987,636,273,51,191,402,947,607,314,794,459,920,208,351,722,737,305,399,221,798,707,550,869,614,988,680,392,196,378,436,916,533,697,836,681,518,493,678,565,967,319,441,187,337,393,530,79,704,493,978,249,540,953,940,534,604,749,752,559,488,902,52,169,50,959,684,544,61,38,336,43,119,758,55,877,442,877,395,297,500,678,932,519,206,46,808,172,246,630,340,193,480,418,191,646,313,113,534,677,478,49,892,34,794,571,8,606,548,51,199,1000,154,615,235,772,897,377,106,704,128,635,692,17,964,915,555,799,326,939,846,249,329,606,259,996,616,137,165,420,882,9,364,848,209,447,746,697,699,690,861,870,244,851,942,779,538,516,448,224,98,480,869,430,90,933,308,417,515,807,585,625,632,620,50,173,417,689,67,862,833,322,722,719,701,190,400,201,9,358,126,910,652,335,867,182,602,214,670,931,581,520,970,121,139,472,107,416,631,914,118,547,297,263,405,192,674,817,46,774,828,370,644,985,755,960,226,514,110,766,296,670,762,179,662,862,390,416,616,405,731,822,924,606,102,609,586,281,226,812,780,318,363,797,970,338,940,732,188,439,512,409,104,671,548,324,816,273,269,120,642,394,318,962,425,811,647,370,960,361,702,475,516,690,74,597,943,174,200,802,813,919,323,567,195,873,891,316,657,203,718,250,204,239,924,216,253,921,393,863,37,233,870,264,770,674,581,579,984,938,20,245,831,364,292,972,294,236,761,66,486,694,863,489,601,305,981,894,798,718,518,62,451,766,457,348,244,678,479,551,141,808,894,89,994,550,398,24,762,262,344,463,323,951,158,789,310,599,968,883,163,614,271,637,403,35,389,437,449,187,671,596,428,449,546,450,755,966,141,788,866,53,388,241,195,367,279,279,878,292,731,31,996,284,31,46,547,80,510,763,962,887,298,195,186,58,25,185,568,34,199,861,188,602,820,63,106,967,365,887,66,388,61,168,400,356,255,101,918,93,443,29,448,796,601,545,905,6,355,762,247,870,180,17,20,656,50,964,196,583,647,516,862,964,560,590,124,119,429,330,138,341,844,61,935,781,158,205,603,775,201,629,493,715,168,881,413,986,902,56,503,304,505,984,156,262,100,72,879,679,401,415,715,102,240,116,287,737,225,160,902,572,52,240,731,812,938,884,167,997,365,218,675,193,531,690,298,270,85,787,949,767,8,214,564,937,548,220,781,45,280,988,261,533,455,460,159,9,191,45,529,901,416,152,408,907,624,432,932,324,9,791,872,729,929,743,690,412,270,356,545,201,130,863,908,103,65,622,468,907,802,942,540,589,625,457,32,229,818,299,99,943,20,293,147,764,291,438,588,107,521,953,235,200,130,607,114,126,732,573,472,586,562,8,533,354,413,865,112,895,678,195,763,489,163,878,83,486,19,171,970,596,948,705,166,751,780,202,289,553,995,116,838,517,585,930,117,896,546,886,1000,366,697,965,540,345,82,501,449,722,380,670,162,449,30,199,18,45,850,678,259,313,159,542,141,845,39,560,50,712,503,580,22,227,440,44,474,322,559,81,261,865,241,129,831,860,653,608,854,597,405,475,871,308,341,551,893,498,336,673,651,68,620,65,920,875,474,923,101,789,222,59,925,254,633,750,810,814,151,363,357,919,973,974,414,304,399,311,33,976,533,114,911,451,602,85,316,808,120,187,512,650,149,950,575,728,543,933,245,311,311,955,15,289,16,481,95,608,450,109,163,323,703,67,491,247,128,545,406,501,8,72,275,483,947,396,333,426,635,701,712,469,367,774,460,301,718,90,199,507,860,483,363,918,280,629,890,440,769,515,914,604,747,87,734,491,466,140,354,86,333,585,947,439,936,278,513,985,362,968,57,874,875,769,499,898,309,972,137,579,761,578,658,588,506,238,176,572,885,596,657,8,90,916,755,293,307,534,475,430,658,86,801,997,4,924,379,507,178,1000,571,737,357,347,75,513,193,214,274,307,152,59,591,426,905,96,473,168,425,130,84,502,950,226,566,74,938,204,217,461,594,954,705,282,478,324,364,576,819,915,420,984,545,41,860,630,297,43,298,513,492,16,165,151,291,408,815,903,155,686,222,258,576,986,762,560,932,997,326,575,266,378,987,365,137,849,549,868,983,95,983,374,893,633,462,643,207,940,827,91,394,242,886,633,540,471,884,716,387,208,199,846,343,877,85,90,474,164,320,699,594,275,40,708,446,821,259,522,845,651,301,621,200,541,153,474,244,80,812,212,924,341,185,22,680,766,529,206,192,330,913,848,23,10,309,518,740,257,777,534,917,823,172,901,197,681,688,923,824,609,446,734,84,268,352,739,631,228,183,997,562,756,349,791,633,939,275,889,706,385,560,588,745,401,149,800,768,761,756,808,138,707,350,944,192,697,990,435,419,240,387,455,812,778,479,429,445,51,730,307,238,153,331,838,178,454,658,829,645,332,855,684,44,554,383,430,574,243,305,994,778,513,392,209,720,232,68,613,674,716,663,859,548,993,40,575,245,443,822,883,695,39,69,976,215,51,515,722,67,214,131,729,909,419,593,266,515,434,347,123,699,525,192,753,701,865,266,107,289,851,351,82,17,601,754,398,365,940,343,870,488,32,19,458,745,807,919,130,582,478,53,796,990,211,102,388,371,21,606,998,1,37,689,276,673,642,889,689,811,399,691,219,780,294,737,225,286,331,249,439,425,955,718,685,712,529,885,700,514,11,904,555,380,495,932,439,957,698,504,784,600,340,360,653,660,676,437,836,404,871,399,23,283,563,609,595,928,72,710,950,870,684,421,175,180,367,761,585,842,563,371,240,265,447,558,514,97,433,32,908,900,736,423,826,605,952,882,862,388,898,742,810,957,971,606,28,376,677,606,746,719,877,25,168,262,828,187,688,922,202,302,213,835,536,129,720,556,412,723,964,143,635,156,677,444,437,460,878,6,892,729,144,883,873,319,689,170,396,725,313,439,20,303,934,895,351,734,164,38,421,789,668,775,688,433,964,786,473,573,320,954,155,661,47,239,261,665,701,220,263,29,466,84,949,482,244,45,510,943,624,410,932,783,480,511,354,885,425,357,243,160,496,419,35,631,304,703,479,349,49,619,720,607,509,896,561,741,801,662,264,410,511,461,182,323,501,571,810,171,916,57,87,459,840,199,591,189,229,787,674,468,774,274,811,536,553,475,66,940,243,58,136,789,511,18,589,416,598,522,360,241,377,322,721,971,868,912,715,460,138,413,7,56,132,877,14,548,376,839,275,15,985,729,235,540,312,36,886,796,474,470,755,965,417,505,481,425,837,829,557,615,68,213,732,52,436,249,881,334,769,514,743,304,775,858,775,802,168,551,745,214,803,418,790,588,801,190,667,653,639,577,989,220,566,869,788,348,960,257,513,138,394,426,487,691,720,767,851,353,474,230,822,348,612,938,883,50,97,809,772,243,135,861,568,257,876,400,285,1,621,472,555,821,807,924,299,385,534,107,119,9,785,55,549,595,639,557,210,198,553,346,723,269,551,659,217,760,329,160,164,53,351,476,533,935,344,655,159,254,722,341,953,74,731,823,759,224,323,319,935,798,703,793,256,49,142,914,779,72,345,815,746,756,799,992,18,155,384,182,54,399,977,726,282,664,315,889,672,887,62,863,79,560,626,679,391,272,261,854,707,376,24,369,161,275,575,93,195,539,820,187,782,86,378,423,807,862,215,609,23,935,236,924,60,493,481,162,907,411,739,463,910,95,748,686,675,635,721,225,319,856,465,503,726,924,166,931,312,57,389,572,332,402,378,576,990,698,37,656,765,370,32,840,909,20,816,99,692,543,358,741,512,362,237,912,545,907,2,504,541,821,852,623,21,544,299,522,992,100,586,253,308,779,174,530,113,433,418,244,141,660,935,851,446,660,503,184,890,238,453,629,942,221,311,776,575,192,863,131,361,716,436,208,525,695,680,77,23,331,858,380,507,428,418,576,622,494,678,960,85,820,106,315,228,653,280,315,900,807,752,68,464,335,102,914,148,299,776,936,707,233,633,510,918,226,205,673,501,667,152,86,635,801,632,623,817,170,781,553,539,30,153,77,83,252,170,867,67,721,716,634,271,516,214,360,165,712,856,384,902,276,697,635,342,406,12,264,973,936,267,102,300,392,519,468,331,171,282,788,980,62,381,55,298,693,31,502,373,618,977,473,715,346,885,399,156,877,802,558,567,297,322,846,918,187,186,46,542,818,966,42,836,604,550,367,610,493,714,986,306,208,147,489,151,253,302,230,782,164,134,668,826,851,299,70,307,11,167,873,333,193,981,135,779,801,795,478,9,88,17,755,58,609,117,526,558,254,958,22,536,785,596,767,640,108,389,558,184,314,870,54,368,512,905,89,503,282,734,518,362,24,288,444,445,845,133,477,920,147,552,530,214,92,116,259,295,348,913,812,132,6,289,629,831,272,995,979,271,197,964,68,665,633,943,17,785,529,710,788,725,164,617,589,50,924,923,739,581,885,641,360,386,245,287,653,586,405,260,898,3,533,902,661,48,890,844,837,170,828,530,586,812,587,641,51,215,220,733,386,334,656,779,287,410,680,413,990,606,233,905,21,391,743,394,834,843,938,815,771,18,702,668,94,653,550,928,788,795,234,85,341,651,623,106,821,325,890,547,710,617,303,513,413,569,736,373,794,237,418,825,498,803,608,735,237,119,977,154,429,744,625,53,413,91,926,200,296,8,975,453,28,271,486,305,146,149,663,368,783,139,538,268,343,533,152,987,968,225,278,671,892,694,553,978,544,49,413,3,668,745,250,115,707,154,961,536,279,510,363,5,408,918,18,146,331,625,685,803,487,576,21,455,605,698,823,668,183,223,830,752,930,-250,592,517,726,205,-478,199,388,-658,293,-400,-790,-53,-671,929,-657,-411,-365,69,45,-713,-878,-368,-230,-920,-257,-989,778,504,-999,863,-746,531,77,-308,724,389,260,-444,425,938,-91,517,-791,-955,332,-942,36,947,-417,26,-929,-899,373,-263,-865,-587,-979,-34,-535,427,-9,383,813,-456,-506,665,-838,951,-771,-110,-329,-358,-902,913,277,-867,-969,-506,639,-232] multipliers = [-525,571,-905,-670,-892,-87,-697,-566,-606,-375,-749,-294,-312,-765,-714,-833,496,-990,-731,-228,-178,-564,-566,-495,-328,-319,-180,-895,-461,-453,-16,-938,-627,-8,-95,144,-60,-794,-663,-723,-492,-427,-719,-497,-506,-823,-974,-529,-427,-640,-274,-675,-741,899,-349,-283,-584,-521,-634,-346,-690,-868,-603,-409,-479,-895,-783,-532,-748,-611,126,-523,-995,-109,-225,-845,-470,-884,-125,-201,-24,-450,-516,-654,-285,-309,-41,-895,-306,-337,-827,-288,-99,-551,-518,-895,965,-568,-254,-166,-363,-77,-173,520,-649,-428,-684,-358,750,-401,-58,-747,-638,-3,-222,-986,-992,-826,-690,-290,-86,300,-984,532,-564,-231,-677,-160,-912,-740,-447,-172,-164,-269,-150,-28,-193,-419,-803,-838,632,-461,-483,-82,-804,-205,-629,-163,-449,-330,-987,-760,-783,-739,-525,-965,-661,-19,-842,-324,-81,770,-111,-613,-244,-689,-193,-367,-939,-107,-936,-840,-112,-700,-330,-396,-138,-156,-362,310,-437,-848,-5,-624,631,-388,-192,-66,-704,-916,-796,542,-37,-858,-68,-961,-533,-157,-306,-768,-688,-888,-987,-437,-465,244,-542,-976,-173,-23,-945,-378,-456,-564,-764,544,747,-389,-167,-388,-934,-178,-466,-361,-169,-610,-95,-836,-611,-387,-472,-396,-629,-33,-799,-691,-853,-328,-234,-264,-978,-189,-308,-510,-665,-719,-246,-220,-418,-732,982,-521,-708,-790,-683,-793,-169,-335,-584,-429,-421,-355,-295,-150,-888,-394,-431,-149,-243,-394,-56,-774,-170,-906,-811,-712,-456,-541,-757,-373,-40,-278,-132,-79,-774,263,-612,-811,-366,-813,-576,-8,676,-43,-983,-376,-153,-48,-906,-182,-335,-285,-419,-909,-433,-223,-487,60,-766,-356,-701,-623,-672,-872,-320,-782,-5,-747,-415,-385,-835,-393,-693,-22,-91,-638,-786,-133,-14,-218,-713,-560,-725,-200,-890,766,-979,-369,-481,-924,-500,-295,-940,-658,-528,-684,490,-690,-881,-781,-410,-141,-365,-598,-840,-440,-460,-787,-450,-326,-92,-596,-141,-65,-930,-691,-547,-765,-76,-328,-751,-653,-783,-552,-470,-478,-232,-829,-477,462,-831,-713,-851,-228,-254,135,-528,-784,-292,-472,-26,-890,-252,-684,-580,-791,-273,-623,-53,-289,-52,-165,-261,-395,-939,-477,-455,-138,-473,-289,-139,-63,-685,-11,-294,-152,-182,-907,-218,-233,-631,-809,-292,-703,-78,-527,-92,-778,-223,-636,-22,-122,-419,-440,-518,-310,-34,-93,-166,-584,-312,-627,-711,326,-513,-818,-350,-897,-676,-503,-664,-447,-653,-105,502,-678,-734,-614,-334,-170,-152,-409,-707,-410,-295,-78,961,-800,-152,-342,-342,-30,487,-692,-426,947,-111,-454,-184,-168,-105,-460,-994,-565,-944,492,-602,-353,-112,-224,-368,-849,-468,-866,-908,-577,-211,-905,-177,-829,-693,-912,-924,-280,-172,-467,-794,-470,-953,-919,-904,-174,-868,-865,-463,-976,-939,-225,-592,-235,-172,-308,-115,-605,-930,-698,-460,-344,-810,-467,-80,-610,-521,-877,-9,-202,-951,-496,-521,-569,-447,-815,-987,-661,-727,739,-744,-672,-635,-431,-233,-57,-704,-277,-8,-794,-127,-744,-251,-771,-617,-412,-925,-311,-611,-169,-756,-219,-627,-175,-149,-765,-32,-553,-576,-484,-698,-599,-84,-677,-117,636,-253,-950,-208,-893,-622,-8,-477,-4,-981,-581,-406,-59,-89,167,-222,758,-100,536,-688,-952,-57,-797,-649,-983,-442,-828,-544,-842,-473,-133,-548,-514,-889,-430,-119,-835,-863,-231,-754,-533,-134,-832,-785,-537,-205,-870,-729,-641,-71,-915,-789,-340,-501,-641,-483,-525,-146,-100,-645,-543,-780,-466,-231,-964,-315,-311,881,-864,-501,-661,-156,-213,-872,-823,-999,-87,-687,-892,-925,-196,-438,-606,-178,-841,-660,-981,-579,-640,-203,-430,-532,-670,-713,-329,-631,-297,-522,-679,-45,-18,-36,-930,-359,-18,-335,-791,-242,-106,-674,-152,847,-167,-366,-973,-95,-658,-18,-989,-422,-832,-331,-853,-969,-673,-13,-802,-86,-147,-82,-253,522,-403,-463,-964,-57,-344,-434,-976,-385,597,-522,-954,-711,-620,-554,-542,-392,-511,-440,-290,-749,-243,186,-312,-704,-275,-317,-525,-57,-228,-395,177,-916,-390,-57,-811,-555,445,-499,-90,-787,-718,-596,-250,-882,-875,-19,-627,-6,-830,-724,-716,-841,-133,-122,-839,-815,-360,486,-181,-599,-264,-579,-506,-375,-2,-465,-186,-88,-334,-362,-612,-494,-79,-9,-824,-191,-910,-382,-453,-670,-750,-664,-127,-749,-734,-132,-698,699,-563,-985,-399,-961,-602,-733,-495,-305,-375,-790,-367,-136,-314,-979,-303,-32,-109,-920,-677] ans = maximumScore(nums, multipliers) expected = "Unknown" print(f"{"Correct" if ans == expected else f"Incorrect: ans = {ans}, expected = {expected}'}") print()
#from bottom_up import maximumScore from memo_recursion import maximumScore if __name__ == "__main__": print("TestCase-1") nums = [1,2,3] multipliers = [3,2,1] ans = maximumScore(nums, multipliers) expected = 14 #print(f"{'Correct' if ans == expected else 'Incorrect'}") print(f"{'Correct' if ans == expected else f'Incorrect: ans = {ans}, expected = {expected}'}") print() print("TestCase-2") nums = [-5,-3,-3,-2,7,1] multipliers = [-10,-5,3,4,6] ans = maximumScore(nums, multipliers) expected = 102 print(f"{'Correct' if ans == expected else f'Incorrect: ans = {ans}, expected = {expected}'}") print() print("TestCase11") nums = [920,108,-649,-682,-778,-268,-611,795,-877,-338,804,931,959,-754,-909,-9,-245,-553,-296,500,-190,-227,-258,-683,-1000,-833,505,481,419,-29,341,522,-495,109,-106,543,616,491,-143,766,769,1000,-378,341,498,-456,14,428,470,-917,133,454,-411,-64,551,929,-186,396,-822,-781,348,445,-786,-330,334,856,-204,-294,483,-802,-138,960,991,949,-294,355,-856,-437,-413,307,-950,-263,-506,-668,60,957,-654,-726,711,-799,-222,761,865,706,626,-384,922,590,891,-784,853,-82,79,-149,420,-546,887,-57,-415,728,586,-260,176,-56,-907,839,-664,821,213,-59,394,-204,-327,-163,-874,-557,-15,646,937,-538,171,-115,491,878,963,332,-573,962,287,980,792,325,537,657,146,-899,-497,595,-644,703,-212,23,-941,-944,402,267,894,-393,1000,766,44,864,-231,373,484,404,441,-554,650,-847,181,-141,506,970,619,427,-239,413,-294,-408,-249,-101,-255,357,-608,-946,-431,639,464,-797,836,-272,850,-253,-383,902,579,836,-786,-802,493,85,-982,-757,348,742,-418,149,-748,126,-150,831,-217,-752,-961,-664,-864,408,-713,403,805,-200,-858,-716,-849,-249,67,650,662,619,-108,608,-43,168,-225,582,3,-624,899,394,692] multipliers = [-112,19,-462,-463,-575,-337,-167,11,-736,-441,-811,94,-37,-841,-515,184,-697,-361,-143,892,697,-609,461,872,685,801,-653,417,329,876,372,118,346,-207,-631,-122,214,233,-628,931,846,-824,819,868,-802,132,-728,-241,-669,-757,693,485,-117,488,659,237,-687,219,-871,727,697,630,-106,207,-564,818,-561,-999,329,-454,367,490,-144,-85,522,-136,-161,115,130,801,-368,447,943,555,-271,-643,216,-456,-935,663,822,263,-387,167,-928,-371,-805,972,-962,661,-1000,-283,-883,865,-311,-88,-924,334,850,-806,-111,-387,7,-822,708,-847,-932,-142,403,921,443,16,982,-423,-508,519,-14,967,-88,-765,679,-697,-682,-448,741,-416,96,0,-498,968,-927,222,686,461,489,356,885,618,134,121,-298,-208,571,-425,603,532,-463,908,480,852,-418,-597] ans = maximumScore(nums, multipliers) expected = 43563107 print(f"{'Correct' if ans == expected else f'Incorrect: ans = {ans}, expected = {expected}'}") print() print("TestCase50") nums = [822,963,170,305,258,841,204,748,850,721,824,405,108,843,76,78,848,318,105,530,703,38,875,785,223,733,310,402,450,447,712,253,369,189,232,478,990,681,847,137,706,789,241,457,351,91,445,823,780,555,144,866,286,808,147,334,818,751,286,60,90,88,53,850,513,694,727,100,335,137,92,37,806,963,566,948,193,838,299,299,655,777,50,353,681,65,47,768,562,854,553,939,334,419,570,704,601,735,123,602,621,910,821,327,526,613,455,979,32,876,974,359,765,248,313,380,127,382,551,987,720,753,382,962,415,7,973,648,194,399,379,717,462,682,488,835,781,599,841,890,520,24,296,702,2,690,613,983,653,485,907,643,458,811,100,254,964,990,708,413,543,632,584,324,843,415,849,976,727,894,380,318,513,818,228,971,990,13,373,882,433,84,986,303,891,789,775,612,612,470,509,718,566,416,236,710,875,861,905,758,400,467,116,297,140,527,43,950,794,475,954,140,743,403,506,252,623,479,960,379,161,140,702,677,700,52,77,428,258,545,926,999,45,436,99,810,823,733,683,199,625,766,547,574,483,535,625,954,173,136,470,149,956,509,929,119,228,194,146,968,901,883,530,161,885,949,137,726,697,313,717,781,169,678,377,53,114,273,517,866,595,546,288,448,16,855,748,754,88,960,451,872,52,911,178,652,70,108,116,461,72,590,11,71,633,531,276,298,425,452,338,325,191,123,386,21,120,288,263,511,639,279,195,865,957,606,180,587,344,526,707,383,671,764,985,85,116,506,835,691,702,705,292,220,926,480,82,953,612,191,127,943,191,82,998,920,171,824,12,487,357,684,918,939,738,495,132,239,550,329,831,127,523,91,624,760,577,996,283,492,127,955,747,701,629,5,723,383,528,97,914,211,573,320,416,52,190,137,695,283,91,559,695,348,679,855,380,561,705,66,183,847,568,579,805,423,926,904,934,73,539,382,698,398,953,831,157,923,747,68,312,825,517,463,365,884,179,549,811,299,125,34,734,844,40,604,282,55,420,234,195,324,170,605,842,300,943,451,507,276,156,97,131,691,103,782,886,583,485,269,636,415,276,105,141,86,229,858,923,526,431,469,647,678,673,316,97,397,546,658,395,158,162,939,136,953,519,475,986,611,378,133,23,897,112,558,245,732,732,683,131,648,719,688,967,415,666,2,68,206,915,43,346,477,645,841,747,200,533,81,216,785,204,832,390,755,782,629,925,523,954,602,628,299,490,30,406,183,157,428,232,206,887,411,796,397,843,574,277,665,963,497,108,759,763,406,646,397,100,419,299,718,517,315,189,604,623,792,928,72,689,955,604,262,148,706,955,169,956,311,955,903,562,600,840,403,346,115,107,815,135,488,363,629,889,404,316,595,30,934,121,194,246,444,465,878,942,886,545,8,746,516,42,726,883,821,827,386,749,945,313,386,237,612,108,965,280,390,136,74,989,692,764,91,335,268,979,13,349,46,403,592,168,198,27,191,801,80,41,256,228,127,521,998,257,93,779,484,922,924,931,894,336,133,492,815,972,524,136,918,96,192,25,367,86,784,378,583,677,971,507,550,638,436,1000,684,31,565,627,915,517,221,930,523,900,472,776,892,779,576,490,27,87,517,301,570,747,481,596,360,276,884,891,784,951,250,99,711,538,560,951,578,725,686,765,543,224,399,458,558,593,447,367,56,778,264,644,725,961,598,829,45,433,286,747,343,94,486,462,135,877,469,822,137,843,501,18,939,182,618,486,442,444,907,549,455,216,461,684,29,440,365,506,481,301,855,225,195,112,894,398,909,878,226,480,514,742,722,344,113,401,941,297,349,32,558,397,989,961,478,56,302,350,53,658,529,444,888,40,468,104,895,629,365,611,56,639,716,181,988,91,742,712,596,588,339,795,406,127,558,181,701,24,861,338,509,680,203,730,444,331,913,770,902,720,186,812,226,350,760,343,995,330,367,734,963,758,858,591,847,68,780,812,255,695,268,955,919,347,60,86,566,156,134,59,738,491,804,367,88,780,364,306,967,772,43,130,957,565,57,485,418,169,861,599,28,109,440,194,833,799,129,945,443,147,21,368,641,798,32,9,638,366,694,836,1000,811,515,898,741,717,889,458,209,556,611,825,288,755,450,942,799,404,801,892,29,375,545,859,207,573,194,885,227,983,148,219,903,875,319,668,492,732,747,410,217,473,718,564,897,876,8,305,204,576,747,290,604,315,25,156,28,48,897,735,90,760,962,26,135,545,535,775,917,330,564,738,298,19,99,278,540,781,632,659,343,193,478,608,600,657,1000,816,412,802,931,655,896,157,865,218,87,683,271,144,964,695,907,460,865,901,759,657,887,486,564,545,188,258,827,403,173,750,55,859,857,511,758,300,832,975,37,258,332,74,179,26,117,852,624,250,229,54,139,963,453,728,440,247,442,901,253,592,301,557,367,558,732,151,975,279,815,520,424,810,215,396,362,259,786,356,777,57,407,76,330,751,178,440,802,329,851,112,788,938,697,399,249,478,258,474,978,699,576,616,932,576,682,361,502,357,894,957,803,529,521,443,208,87,441,247,531,990,148,123,527,798,207,227,43,46,850,935,393,271,633,897,955,781,584,463,309,36,864,960,152,754,998,679,356,785,46,228,55,692,460,733,492,378,592,135,925,797,748,593,932,393,353,223,947,396,953,685,186,748,383,824,262,76,758,730,725,950,462,464,286,513,765,343,723,873,671,934,86,325,335,73,754,726,863,179,880,916,339,256,541,200,837,932,624,639,88,36,209,841,736,662,849,586,738,516,776,743,831,757,480,818,382,993,290,163,464,602,907,414,348,501,665,928,225,124,257,922,839,305,890,568,870,106,898,454,169,559,790,236,646,347,41,949,333,887,211,984,349,26,622,900,156,461,226,617,333,976,32,342,442,995,99,726,951,114,329,67,602,358,306,844,124,465,383,548,265,213,106,720,917,526,759,316,619,18,83,461,649,579,75,493,568,604,482,796,431,503,67,169,312,509,772,591,509,372,635,620,359,253,137,535,732,919,746,186,95,441,28,309,112,924,260,389,1,414,130,640,162,177,106,867,302,879,7,553,790,762,796,977,647,111,342,866,944,657,974,434,894,641,382,982,891,407,779,838,138,659,432,706,725,969,361,631,256,33,226,678,840,820,582,847,816,658,611,190,84,627,420,239,870,121,1000,754,665,612,767,541,780,22,141,954,245,287,687,5,939,783,373,76,995,316,160,601,284,808,833,880,870,85,838,129,276,977,810,295,890,299,718,376,980,685,196,439,90,371,573,682,868,370,298,616,689,492,502,212,260,320,219,310,997,972,42,989,216,318,240,227,519,461,161,829,147,451,345,493,408,44,1,601,288,889,794,569,646,105,110,428,233,765,953,674,967,236,227,600,400,532,770,110,192,637,925,659,730,478,957,864,560,85,173,488,645,853,49,556,85,553,781,478,576,926,38,931,536,337,534,161,166,606,318,390,491,972,95,162,841,856,13,967,334,673,354,481,654,914,456,393,303,145,288,144,651,33,584,698,754,78,614,700,96,719,838,947,974,513,884,133,23,746,879,672,922,893,609,620,468,121,966,42,994,935,199,56,481,285,292,568,776,830,163,742,663,768,974,634,293,934,803,413,364,880,38,922,241,387,389,810,341,466,500,486,285,57,453,951,804,563,874,138,382,234,290,645,64,51,977,322,59,424,265,451,10,226,503,34,445,10,614,256,336,285,512,31,583,732,61,744,162,624,226,905,516,788,898,587,426,38,22,130,708,653,531,56,803,440,154,698,646,684,943,108,455,595,469,450,78,130,536,227,766,384,904,295,116,298,838,987,636,273,51,191,402,947,607,314,794,459,920,208,351,722,737,305,399,221,798,707,550,869,614,988,680,392,196,378,436,916,533,697,836,681,518,493,678,565,967,319,441,187,337,393,530,79,704,493,978,249,540,953,940,534,604,749,752,559,488,902,52,169,50,959,684,544,61,38,336,43,119,758,55,877,442,877,395,297,500,678,932,519,206,46,808,172,246,630,340,193,480,418,191,646,313,113,534,677,478,49,892,34,794,571,8,606,548,51,199,1000,154,615,235,772,897,377,106,704,128,635,692,17,964,915,555,799,326,939,846,249,329,606,259,996,616,137,165,420,882,9,364,848,209,447,746,697,699,690,861,870,244,851,942,779,538,516,448,224,98,480,869,430,90,933,308,417,515,807,585,625,632,620,50,173,417,689,67,862,833,322,722,719,701,190,400,201,9,358,126,910,652,335,867,182,602,214,670,931,581,520,970,121,139,472,107,416,631,914,118,547,297,263,405,192,674,817,46,774,828,370,644,985,755,960,226,514,110,766,296,670,762,179,662,862,390,416,616,405,731,822,924,606,102,609,586,281,226,812,780,318,363,797,970,338,940,732,188,439,512,409,104,671,548,324,816,273,269,120,642,394,318,962,425,811,647,370,960,361,702,475,516,690,74,597,943,174,200,802,813,919,323,567,195,873,891,316,657,203,718,250,204,239,924,216,253,921,393,863,37,233,870,264,770,674,581,579,984,938,20,245,831,364,292,972,294,236,761,66,486,694,863,489,601,305,981,894,798,718,518,62,451,766,457,348,244,678,479,551,141,808,894,89,994,550,398,24,762,262,344,463,323,951,158,789,310,599,968,883,163,614,271,637,403,35,389,437,449,187,671,596,428,449,546,450,755,966,141,788,866,53,388,241,195,367,279,279,878,292,731,31,996,284,31,46,547,80,510,763,962,887,298,195,186,58,25,185,568,34,199,861,188,602,820,63,106,967,365,887,66,388,61,168,400,356,255,101,918,93,443,29,448,796,601,545,905,6,355,762,247,870,180,17,20,656,50,964,196,583,647,516,862,964,560,590,124,119,429,330,138,341,844,61,935,781,158,205,603,775,201,629,493,715,168,881,413,986,902,56,503,304,505,984,156,262,100,72,879,679,401,415,715,102,240,116,287,737,225,160,902,572,52,240,731,812,938,884,167,997,365,218,675,193,531,690,298,270,85,787,949,767,8,214,564,937,548,220,781,45,280,988,261,533,455,460,159,9,191,45,529,901,416,152,408,907,624,432,932,324,9,791,872,729,929,743,690,412,270,356,545,201,130,863,908,103,65,622,468,907,802,942,540,589,625,457,32,229,818,299,99,943,20,293,147,764,291,438,588,107,521,953,235,200,130,607,114,126,732,573,472,586,562,8,533,354,413,865,112,895,678,195,763,489,163,878,83,486,19,171,970,596,948,705,166,751,780,202,289,553,995,116,838,517,585,930,117,896,546,886,1000,366,697,965,540,345,82,501,449,722,380,670,162,449,30,199,18,45,850,678,259,313,159,542,141,845,39,560,50,712,503,580,22,227,440,44,474,322,559,81,261,865,241,129,831,860,653,608,854,597,405,475,871,308,341,551,893,498,336,673,651,68,620,65,920,875,474,923,101,789,222,59,925,254,633,750,810,814,151,363,357,919,973,974,414,304,399,311,33,976,533,114,911,451,602,85,316,808,120,187,512,650,149,950,575,728,543,933,245,311,311,955,15,289,16,481,95,608,450,109,163,323,703,67,491,247,128,545,406,501,8,72,275,483,947,396,333,426,635,701,712,469,367,774,460,301,718,90,199,507,860,483,363,918,280,629,890,440,769,515,914,604,747,87,734,491,466,140,354,86,333,585,947,439,936,278,513,985,362,968,57,874,875,769,499,898,309,972,137,579,761,578,658,588,506,238,176,572,885,596,657,8,90,916,755,293,307,534,475,430,658,86,801,997,4,924,379,507,178,1000,571,737,357,347,75,513,193,214,274,307,152,59,591,426,905,96,473,168,425,130,84,502,950,226,566,74,938,204,217,461,594,954,705,282,478,324,364,576,819,915,420,984,545,41,860,630,297,43,298,513,492,16,165,151,291,408,815,903,155,686,222,258,576,986,762,560,932,997,326,575,266,378,987,365,137,849,549,868,983,95,983,374,893,633,462,643,207,940,827,91,394,242,886,633,540,471,884,716,387,208,199,846,343,877,85,90,474,164,320,699,594,275,40,708,446,821,259,522,845,651,301,621,200,541,153,474,244,80,812,212,924,341,185,22,680,766,529,206,192,330,913,848,23,10,309,518,740,257,777,534,917,823,172,901,197,681,688,923,824,609,446,734,84,268,352,739,631,228,183,997,562,756,349,791,633,939,275,889,706,385,560,588,745,401,149,800,768,761,756,808,138,707,350,944,192,697,990,435,419,240,387,455,812,778,479,429,445,51,730,307,238,153,331,838,178,454,658,829,645,332,855,684,44,554,383,430,574,243,305,994,778,513,392,209,720,232,68,613,674,716,663,859,548,993,40,575,245,443,822,883,695,39,69,976,215,51,515,722,67,214,131,729,909,419,593,266,515,434,347,123,699,525,192,753,701,865,266,107,289,851,351,82,17,601,754,398,365,940,343,870,488,32,19,458,745,807,919,130,582,478,53,796,990,211,102,388,371,21,606,998,1,37,689,276,673,642,889,689,811,399,691,219,780,294,737,225,286,331,249,439,425,955,718,685,712,529,885,700,514,11,904,555,380,495,932,439,957,698,504,784,600,340,360,653,660,676,437,836,404,871,399,23,283,563,609,595,928,72,710,950,870,684,421,175,180,367,761,585,842,563,371,240,265,447,558,514,97,433,32,908,900,736,423,826,605,952,882,862,388,898,742,810,957,971,606,28,376,677,606,746,719,877,25,168,262,828,187,688,922,202,302,213,835,536,129,720,556,412,723,964,143,635,156,677,444,437,460,878,6,892,729,144,883,873,319,689,170,396,725,313,439,20,303,934,895,351,734,164,38,421,789,668,775,688,433,964,786,473,573,320,954,155,661,47,239,261,665,701,220,263,29,466,84,949,482,244,45,510,943,624,410,932,783,480,511,354,885,425,357,243,160,496,419,35,631,304,703,479,349,49,619,720,607,509,896,561,741,801,662,264,410,511,461,182,323,501,571,810,171,916,57,87,459,840,199,591,189,229,787,674,468,774,274,811,536,553,475,66,940,243,58,136,789,511,18,589,416,598,522,360,241,377,322,721,971,868,912,715,460,138,413,7,56,132,877,14,548,376,839,275,15,985,729,235,540,312,36,886,796,474,470,755,965,417,505,481,425,837,829,557,615,68,213,732,52,436,249,881,334,769,514,743,304,775,858,775,802,168,551,745,214,803,418,790,588,801,190,667,653,639,577,989,220,566,869,788,348,960,257,513,138,394,426,487,691,720,767,851,353,474,230,822,348,612,938,883,50,97,809,772,243,135,861,568,257,876,400,285,1,621,472,555,821,807,924,299,385,534,107,119,9,785,55,549,595,639,557,210,198,553,346,723,269,551,659,217,760,329,160,164,53,351,476,533,935,344,655,159,254,722,341,953,74,731,823,759,224,323,319,935,798,703,793,256,49,142,914,779,72,345,815,746,756,799,992,18,155,384,182,54,399,977,726,282,664,315,889,672,887,62,863,79,560,626,679,391,272,261,854,707,376,24,369,161,275,575,93,195,539,820,187,782,86,378,423,807,862,215,609,23,935,236,924,60,493,481,162,907,411,739,463,910,95,748,686,675,635,721,225,319,856,465,503,726,924,166,931,312,57,389,572,332,402,378,576,990,698,37,656,765,370,32,840,909,20,816,99,692,543,358,741,512,362,237,912,545,907,2,504,541,821,852,623,21,544,299,522,992,100,586,253,308,779,174,530,113,433,418,244,141,660,935,851,446,660,503,184,890,238,453,629,942,221,311,776,575,192,863,131,361,716,436,208,525,695,680,77,23,331,858,380,507,428,418,576,622,494,678,960,85,820,106,315,228,653,280,315,900,807,752,68,464,335,102,914,148,299,776,936,707,233,633,510,918,226,205,673,501,667,152,86,635,801,632,623,817,170,781,553,539,30,153,77,83,252,170,867,67,721,716,634,271,516,214,360,165,712,856,384,902,276,697,635,342,406,12,264,973,936,267,102,300,392,519,468,331,171,282,788,980,62,381,55,298,693,31,502,373,618,977,473,715,346,885,399,156,877,802,558,567,297,322,846,918,187,186,46,542,818,966,42,836,604,550,367,610,493,714,986,306,208,147,489,151,253,302,230,782,164,134,668,826,851,299,70,307,11,167,873,333,193,981,135,779,801,795,478,9,88,17,755,58,609,117,526,558,254,958,22,536,785,596,767,640,108,389,558,184,314,870,54,368,512,905,89,503,282,734,518,362,24,288,444,445,845,133,477,920,147,552,530,214,92,116,259,295,348,913,812,132,6,289,629,831,272,995,979,271,197,964,68,665,633,943,17,785,529,710,788,725,164,617,589,50,924,923,739,581,885,641,360,386,245,287,653,586,405,260,898,3,533,902,661,48,890,844,837,170,828,530,586,812,587,641,51,215,220,733,386,334,656,779,287,410,680,413,990,606,233,905,21,391,743,394,834,843,938,815,771,18,702,668,94,653,550,928,788,795,234,85,341,651,623,106,821,325,890,547,710,617,303,513,413,569,736,373,794,237,418,825,498,803,608,735,237,119,977,154,429,744,625,53,413,91,926,200,296,8,975,453,28,271,486,305,146,149,663,368,783,139,538,268,343,533,152,987,968,225,278,671,892,694,553,978,544,49,413,3,668,745,250,115,707,154,961,536,279,510,363,5,408,918,18,146,331,625,685,803,487,576,21,455,605,698,823,668,183,223,830,752,930,-250,592,517,726,205,-478,199,388,-658,293,-400,-790,-53,-671,929,-657,-411,-365,69,45,-713,-878,-368,-230,-920,-257,-989,778,504,-999,863,-746,531,77,-308,724,389,260,-444,425,938,-91,517,-791,-955,332,-942,36,947,-417,26,-929,-899,373,-263,-865,-587,-979,-34,-535,427,-9,383,813,-456,-506,665,-838,951,-771,-110,-329,-358,-902,913,277,-867,-969,-506,639,-232] multipliers = [-525,571,-905,-670,-892,-87,-697,-566,-606,-375,-749,-294,-312,-765,-714,-833,496,-990,-731,-228,-178,-564,-566,-495,-328,-319,-180,-895,-461,-453,-16,-938,-627,-8,-95,144,-60,-794,-663,-723,-492,-427,-719,-497,-506,-823,-974,-529,-427,-640,-274,-675,-741,899,-349,-283,-584,-521,-634,-346,-690,-868,-603,-409,-479,-895,-783,-532,-748,-611,126,-523,-995,-109,-225,-845,-470,-884,-125,-201,-24,-450,-516,-654,-285,-309,-41,-895,-306,-337,-827,-288,-99,-551,-518,-895,965,-568,-254,-166,-363,-77,-173,520,-649,-428,-684,-358,750,-401,-58,-747,-638,-3,-222,-986,-992,-826,-690,-290,-86,300,-984,532,-564,-231,-677,-160,-912,-740,-447,-172,-164,-269,-150,-28,-193,-419,-803,-838,632,-461,-483,-82,-804,-205,-629,-163,-449,-330,-987,-760,-783,-739,-525,-965,-661,-19,-842,-324,-81,770,-111,-613,-244,-689,-193,-367,-939,-107,-936,-840,-112,-700,-330,-396,-138,-156,-362,310,-437,-848,-5,-624,631,-388,-192,-66,-704,-916,-796,542,-37,-858,-68,-961,-533,-157,-306,-768,-688,-888,-987,-437,-465,244,-542,-976,-173,-23,-945,-378,-456,-564,-764,544,747,-389,-167,-388,-934,-178,-466,-361,-169,-610,-95,-836,-611,-387,-472,-396,-629,-33,-799,-691,-853,-328,-234,-264,-978,-189,-308,-510,-665,-719,-246,-220,-418,-732,982,-521,-708,-790,-683,-793,-169,-335,-584,-429,-421,-355,-295,-150,-888,-394,-431,-149,-243,-394,-56,-774,-170,-906,-811,-712,-456,-541,-757,-373,-40,-278,-132,-79,-774,263,-612,-811,-366,-813,-576,-8,676,-43,-983,-376,-153,-48,-906,-182,-335,-285,-419,-909,-433,-223,-487,60,-766,-356,-701,-623,-672,-872,-320,-782,-5,-747,-415,-385,-835,-393,-693,-22,-91,-638,-786,-133,-14,-218,-713,-560,-725,-200,-890,766,-979,-369,-481,-924,-500,-295,-940,-658,-528,-684,490,-690,-881,-781,-410,-141,-365,-598,-840,-440,-460,-787,-450,-326,-92,-596,-141,-65,-930,-691,-547,-765,-76,-328,-751,-653,-783,-552,-470,-478,-232,-829,-477,462,-831,-713,-851,-228,-254,135,-528,-784,-292,-472,-26,-890,-252,-684,-580,-791,-273,-623,-53,-289,-52,-165,-261,-395,-939,-477,-455,-138,-473,-289,-139,-63,-685,-11,-294,-152,-182,-907,-218,-233,-631,-809,-292,-703,-78,-527,-92,-778,-223,-636,-22,-122,-419,-440,-518,-310,-34,-93,-166,-584,-312,-627,-711,326,-513,-818,-350,-897,-676,-503,-664,-447,-653,-105,502,-678,-734,-614,-334,-170,-152,-409,-707,-410,-295,-78,961,-800,-152,-342,-342,-30,487,-692,-426,947,-111,-454,-184,-168,-105,-460,-994,-565,-944,492,-602,-353,-112,-224,-368,-849,-468,-866,-908,-577,-211,-905,-177,-829,-693,-912,-924,-280,-172,-467,-794,-470,-953,-919,-904,-174,-868,-865,-463,-976,-939,-225,-592,-235,-172,-308,-115,-605,-930,-698,-460,-344,-810,-467,-80,-610,-521,-877,-9,-202,-951,-496,-521,-569,-447,-815,-987,-661,-727,739,-744,-672,-635,-431,-233,-57,-704,-277,-8,-794,-127,-744,-251,-771,-617,-412,-925,-311,-611,-169,-756,-219,-627,-175,-149,-765,-32,-553,-576,-484,-698,-599,-84,-677,-117,636,-253,-950,-208,-893,-622,-8,-477,-4,-981,-581,-406,-59,-89,167,-222,758,-100,536,-688,-952,-57,-797,-649,-983,-442,-828,-544,-842,-473,-133,-548,-514,-889,-430,-119,-835,-863,-231,-754,-533,-134,-832,-785,-537,-205,-870,-729,-641,-71,-915,-789,-340,-501,-641,-483,-525,-146,-100,-645,-543,-780,-466,-231,-964,-315,-311,881,-864,-501,-661,-156,-213,-872,-823,-999,-87,-687,-892,-925,-196,-438,-606,-178,-841,-660,-981,-579,-640,-203,-430,-532,-670,-713,-329,-631,-297,-522,-679,-45,-18,-36,-930,-359,-18,-335,-791,-242,-106,-674,-152,847,-167,-366,-973,-95,-658,-18,-989,-422,-832,-331,-853,-969,-673,-13,-802,-86,-147,-82,-253,522,-403,-463,-964,-57,-344,-434,-976,-385,597,-522,-954,-711,-620,-554,-542,-392,-511,-440,-290,-749,-243,186,-312,-704,-275,-317,-525,-57,-228,-395,177,-916,-390,-57,-811,-555,445,-499,-90,-787,-718,-596,-250,-882,-875,-19,-627,-6,-830,-724,-716,-841,-133,-122,-839,-815,-360,486,-181,-599,-264,-579,-506,-375,-2,-465,-186,-88,-334,-362,-612,-494,-79,-9,-824,-191,-910,-382,-453,-670,-750,-664,-127,-749,-734,-132,-698,699,-563,-985,-399,-961,-602,-733,-495,-305,-375,-790,-367,-136,-314,-979,-303,-32,-109,-920,-677] ans = maximumScore(nums, multipliers) expected = "Unknown" print(f"{'Correct' if ans == expected else f'Incorrect: ans = {ans}, expected = {expected}'}") print()
#!/usr/bin/env python3 # # Copyright 2017-2020 GridGain Systems. # # 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. import os from ..app import App from ..appexception import AppException, MissedRequirementException from ...util import log_print class Profiler(App): jfr_jvm_opts = "-XX:+UnlockCommercialFeatures" \ " -XX:+FlightRecorder" \ " -XX:StartFlightRecording=delay={WARMUP}s," \ "duration={DURATION}s," \ "filename={JFR_PATH}," \ "settings={JFC_PATH}" available_profilers = ('jfr', 'async_flamegraph') def __init__(self, name, config, ssh, profiler='', **kwargs): super().__init__(name, config, ssh, app_type='profiler') self.type = self.config['environment'].get('yardstick', {}).get('profiler') if not self.type: self.type = profiler if self.type not in self.available_profilers: raise AppException(f"Unknown profiler type {self.type}. Available types: {self.available_profilers}") self.async_profiler_home = os.path.join(self.config['remote']['suite_var_dir'], 'flamegraph', 'async_fmg') self.options = { 'warmup': 60, 'duration': 60, 'bench_name': '' } def check_requirements(self): if self.type == 'jfr': self.require_artifact('jfr_cfg') else: self.require_artifact(self.type) def update_options(self, **kwargs): if kwargs: self.options.update(kwargs) def check_hosts_for_async_profiler(self, hosts): # async_profiler requires 'perf_event_paranoid' and 'kptr_restrict' to be set to '1' and '0' respectively # https://github.com/jvm-profiling-tools/async-profiler#basic-usage check_cmd = ['cat /proc/sys/kernel/perf_event_paranoid', 'cat /proc/sys/kernel/kptr_restrict'] check_cmds = {} for h in hosts: check_cmds[hosts[h]['host']] = check_cmd out = self.ssh.exec(check_cmds) err_msg = "" for host in out.keys(): res_str = ''.join(out[host]) res_str_exp = "1\n0\n" if res_str != res_str_exp: if len(err_msg) == 0: err_msg += "Unsatisfied requirement for async_profiler found\n" err_msg += f"Command: {"; ".join(check_cmd)} on host {host}:\n" err_msg += f"Expected:\n{res_str_exp}\n" + \ f"Actual:\n{res_str}\n" if len(err_msg) > 0: raise MissedRequirementException(err_msg) def get_jvm_options(self): if self.type == 'jfr': jfr_str = self.jfr_jvm_opts.format( WARMUP=self.options['warmup'], DURATION=self.options['duration'], JFR_PATH=os.path.join( self.config['rt']['remote']['test_dir'], 'jfr-{b}-d{d}.jfr'.format(b=self.options['bench_name'], d=self.options['duration'])), JFC_PATH=self.config['artifacts']['jfr_cfg']['remote_path']) return jfr_str.split(' ') else: return [] def start(self): warmup = self.options['warmup'] duration = self.options['duration'] nodes = self.options.get('nodes') if self.type == "jfr": log_print("Will be used profiler: {profiler}\nYou no need to call start method.".format( profiler=self.type)) elif self.type == "async_flamegraph": # Checks if nodes is None: log_print(f"No Ignite nodes info available. Will not start profiler of type {self.type}", color='red') return self.check_hosts_for_async_profiler(nodes) output_dir = self.config['rt']['remote']['test_dir'] for node_id in nodes.keys(): pid = nodes[node_id]['PID'] host = nodes[node_id]['host'] out_file_basename = os.path.join(output_dir, f"fmgrh-pid-{pid}") out_file_fmg = out_file_basename + '.svg' out_file_log = out_file_basename + '.log' self.ssh.exec_on_host(host, [ f"chmod +x {self.async_profiler_home}/*.sh", f"chmod +x {self.async_profiler_home}/build/*" ]) cmd = f"sleep {warmup}; " + \ f"{self.async_profiler_home}/profiler.sh " + \ f"-d {duration} -i 999000 -b 5000000 -o svg -f {out_file_fmg} {pid}" cmds = [f"nohup bash -c '{cmd}' >{out_file_log} 2>&1 &"] log_print(f"Starting profiler on host {host}") log_print('; '.join(cmds), color='debug') self.ssh.exec_on_host(host, cmds) def stop(self): if self.type == 'jfr': return # Since async profiler is started with 'duration' option, # there is no need to stop it explicitly if self.type == "async_flamegraph": return
#!/usr/bin/env python3 # # Copyright 2017-2020 GridGain Systems. # # 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. import os from ..app import App from ..appexception import AppException, MissedRequirementException from ...util import log_print class Profiler(App): jfr_jvm_opts = "-XX:+UnlockCommercialFeatures" \ " -XX:+FlightRecorder" \ " -XX:StartFlightRecording=delay={WARMUP}s," \ "duration={DURATION}s," \ "filename={JFR_PATH}," \ "settings={JFC_PATH}" available_profilers = ('jfr', 'async_flamegraph') def __init__(self, name, config, ssh, profiler='', **kwargs): super().__init__(name, config, ssh, app_type='profiler') self.type = self.config['environment'].get('yardstick', {}).get('profiler') if not self.type: self.type = profiler if self.type not in self.available_profilers: raise AppException(f"Unknown profiler type {self.type}. Available types: {self.available_profilers}") self.async_profiler_home = os.path.join(self.config['remote']['suite_var_dir'], 'flamegraph', 'async_fmg') self.options = { 'warmup': 60, 'duration': 60, 'bench_name': '' } def check_requirements(self): if self.type == 'jfr': self.require_artifact('jfr_cfg') else: self.require_artifact(self.type) def update_options(self, **kwargs): if kwargs: self.options.update(kwargs) def check_hosts_for_async_profiler(self, hosts): # async_profiler requires 'perf_event_paranoid' and 'kptr_restrict' to be set to '1' and '0' respectively # https://github.com/jvm-profiling-tools/async-profiler#basic-usage check_cmd = ['cat /proc/sys/kernel/perf_event_paranoid', 'cat /proc/sys/kernel/kptr_restrict'] check_cmds = {} for h in hosts: check_cmds[hosts[h]['host']] = check_cmd out = self.ssh.exec(check_cmds) err_msg = "" for host in out.keys(): res_str = ''.join(out[host]) res_str_exp = "1\n0\n" if res_str != res_str_exp: if len(err_msg) == 0: err_msg += "Unsatisfied requirement for async_profiler found\n" err_msg += f"Command: {'; '.join(check_cmd)} on host {host}:\n" err_msg += f"Expected:\n{res_str_exp}\n" + \ f"Actual:\n{res_str}\n" if len(err_msg) > 0: raise MissedRequirementException(err_msg) def get_jvm_options(self): if self.type == 'jfr': jfr_str = self.jfr_jvm_opts.format( WARMUP=self.options['warmup'], DURATION=self.options['duration'], JFR_PATH=os.path.join( self.config['rt']['remote']['test_dir'], 'jfr-{b}-d{d}.jfr'.format(b=self.options['bench_name'], d=self.options['duration'])), JFC_PATH=self.config['artifacts']['jfr_cfg']['remote_path']) return jfr_str.split(' ') else: return [] def start(self): warmup = self.options['warmup'] duration = self.options['duration'] nodes = self.options.get('nodes') if self.type == "jfr": log_print("Will be used profiler: {profiler}\nYou no need to call start method.".format( profiler=self.type)) elif self.type == "async_flamegraph": # Checks if nodes is None: log_print(f"No Ignite nodes info available. Will not start profiler of type {self.type}", color='red') return self.check_hosts_for_async_profiler(nodes) output_dir = self.config['rt']['remote']['test_dir'] for node_id in nodes.keys(): pid = nodes[node_id]['PID'] host = nodes[node_id]['host'] out_file_basename = os.path.join(output_dir, f"fmgrh-pid-{pid}") out_file_fmg = out_file_basename + '.svg' out_file_log = out_file_basename + '.log' self.ssh.exec_on_host(host, [ f"chmod +x {self.async_profiler_home}/*.sh", f"chmod +x {self.async_profiler_home}/build/*" ]) cmd = f"sleep {warmup}; " + \ f"{self.async_profiler_home}/profiler.sh " + \ f"-d {duration} -i 999000 -b 5000000 -o svg -f {out_file_fmg} {pid}" cmds = [f"nohup bash -c '{cmd}' >{out_file_log} 2>&1 &"] log_print(f"Starting profiler on host {host}") log_print('; '.join(cmds), color='debug') self.ssh.exec_on_host(host, cmds) def stop(self): if self.type == 'jfr': return # Since async profiler is started with 'duration' option, # there is no need to stop it explicitly if self.type == "async_flamegraph": return
# Copyright 2018 Jian Wu # License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) from collections import defaultdict from typing import Optional, NoReturn, Tuple from kaldi_python_io import Reader as BaseReader class MetricReporter(object): """ Metric reporter (WER, SiSNR, SDR ...) """ def __init__(self, spk2class: Optional[str] = None, name: str = "UNK", unit: str = "UNK") -> None: self.s2c = BaseReader(spk2class) if spk2class else None self.val = defaultdict(float) self.name = name self.unit = unit def report(self): """ Print results """ raise NotImplementedError class AverageReporter(MetricReporter): """ Reportor for SDR, PESQ, SiSNR Args: spk2class (str, optional): spk2class file name (str): SDR, PESQ or SiSNR unit (str): dB """ def __init__(self, spk2class: Optional[str] = None, name: str = "UNK", unit: str = "UNK") -> None: super(AverageReporter, self).__init__(spk2class=spk2class, name=name, unit=unit) self.cnt = defaultdict(int) def add(self, key: str, val: float) -> NoReturn: cls_str = "NG" if self.s2c: cls_str = self.s2c[key] self.val[cls_str] += val self.cnt[cls_str] += 1 def report(self) -> NoReturn: print(f"{self.name} ({self.unit}) Report: ") tot_utt = sum([self.cnt[cls_str] for cls_str in self.cnt]) tot_snr = sum([self.val[cls_str] for cls_str in self.val]) print(f"Total: {tot_snr / tot_utt:.3f}, {tot_utt:d} utterances") if len(self.val) != 1: for cls_str in self.val: cls_snr = self.val[cls_str] num_utt = self.cnt[cls_str] print(f"\t{cls_str}: {cls_snr / num_utt:.3f}, " + f"{num_utt:d} utterances") class WerReporter(MetricReporter): """ Reportor for WER, CER Args: spk2class (str, optional): spk2class file name (str): WER or CER unit (str): % """ def __init__(self, spk2class: Optional[str] = None, name: str = "UNK", unit: str = "UNK") -> None: super(WerReporter, self).__init__(spk2class=spk2class, name=name, unit=unit) self.tot = defaultdict(float) self.err = { "sub": defaultdict(float), "ins": defaultdict(float), "del": defaultdict(float) } self.cnt = 0 def add(self, key: str, val: Tuple[float], tot: int) -> NoReturn: cls_str = "NG" if self.s2c: cls_str = self.s2c[key] self.tot[cls_str] += tot self.val[cls_str] += sum(val) self.err["sub"][cls_str] += val[0] self.err["ins"][cls_str] += val[1] self.err["del"][cls_str] += val[2] self.cnt += 1 def report(self) -> NoReturn: print(f"{self.name} ({self.unit}) Report: ") sum_err = sum([self.val[cls_str] for cls_str in self.val]) sum_len = sum([self.tot[cls_str] for cls_str in self.tot]) wer = sum_err * 100 / sum_len errs = { key: sum([self.err[key][cls_str] for cls_str in self.val ]) for key in self.err } errs_str = f"{errs["sub"]:.0f}/{errs["ins"]:.0f}/{errs["del"]:.0f}" print( f"Total ({self.cnt:.0f} utterances): {sum_err:.0f}/{sum_len:.0f} " + f"= {wer:.2f}{self.unit}, SUB/INS/DEL = {errs_str}") if len(self.val) != 1: for cls_str in self.val: cls_err = self.val[cls_str] cls_tot = self.tot[cls_str] wer = cls_err * 100 / cls_tot print(f" {cls_str}: {cls_err:.0f}/{cls_tot:.0f} " + f"= {wer:.2f}{self.unit}")
# Copyright 2018 Jian Wu # License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) from collections import defaultdict from typing import Optional, NoReturn, Tuple from kaldi_python_io import Reader as BaseReader class MetricReporter(object): """ Metric reporter (WER, SiSNR, SDR ...) """ def __init__(self, spk2class: Optional[str] = None, name: str = "UNK", unit: str = "UNK") -> None: self.s2c = BaseReader(spk2class) if spk2class else None self.val = defaultdict(float) self.name = name self.unit = unit def report(self): """ Print results """ raise NotImplementedError class AverageReporter(MetricReporter): """ Reportor for SDR, PESQ, SiSNR Args: spk2class (str, optional): spk2class file name (str): SDR, PESQ or SiSNR unit (str): dB """ def __init__(self, spk2class: Optional[str] = None, name: str = "UNK", unit: str = "UNK") -> None: super(AverageReporter, self).__init__(spk2class=spk2class, name=name, unit=unit) self.cnt = defaultdict(int) def add(self, key: str, val: float) -> NoReturn: cls_str = "NG" if self.s2c: cls_str = self.s2c[key] self.val[cls_str] += val self.cnt[cls_str] += 1 def report(self) -> NoReturn: print(f"{self.name} ({self.unit}) Report: ") tot_utt = sum([self.cnt[cls_str] for cls_str in self.cnt]) tot_snr = sum([self.val[cls_str] for cls_str in self.val]) print(f"Total: {tot_snr / tot_utt:.3f}, {tot_utt:d} utterances") if len(self.val) != 1: for cls_str in self.val: cls_snr = self.val[cls_str] num_utt = self.cnt[cls_str] print(f"\t{cls_str}: {cls_snr / num_utt:.3f}, " + f"{num_utt:d} utterances") class WerReporter(MetricReporter): """ Reportor for WER, CER Args: spk2class (str, optional): spk2class file name (str): WER or CER unit (str): % """ def __init__(self, spk2class: Optional[str] = None, name: str = "UNK", unit: str = "UNK") -> None: super(WerReporter, self).__init__(spk2class=spk2class, name=name, unit=unit) self.tot = defaultdict(float) self.err = { "sub": defaultdict(float), "ins": defaultdict(float), "del": defaultdict(float) } self.cnt = 0 def add(self, key: str, val: Tuple[float], tot: int) -> NoReturn: cls_str = "NG" if self.s2c: cls_str = self.s2c[key] self.tot[cls_str] += tot self.val[cls_str] += sum(val) self.err["sub"][cls_str] += val[0] self.err["ins"][cls_str] += val[1] self.err["del"][cls_str] += val[2] self.cnt += 1 def report(self) -> NoReturn: print(f"{self.name} ({self.unit}) Report: ") sum_err = sum([self.val[cls_str] for cls_str in self.val]) sum_len = sum([self.tot[cls_str] for cls_str in self.tot]) wer = sum_err * 100 / sum_len errs = { key: sum([self.err[key][cls_str] for cls_str in self.val ]) for key in self.err } errs_str = f"{errs['sub']:.0f}/{errs['ins']:.0f}/{errs['del']:.0f}" print( f"Total ({self.cnt:.0f} utterances): {sum_err:.0f}/{sum_len:.0f} " + f"= {wer:.2f}{self.unit}, SUB/INS/DEL = {errs_str}") if len(self.val) != 1: for cls_str in self.val: cls_err = self.val[cls_str] cls_tot = self.tot[cls_str] wer = cls_err * 100 / cls_tot print(f" {cls_str}: {cls_err:.0f}/{cls_tot:.0f} " + f"= {wer:.2f}{self.unit}")
import sys import importlib import glob from pathlib import Path from panda3d.core import NodePath from ursina.vec3 import Vec3 from panda3d.core import Vec4, Vec2 from panda3d.core import TransparencyAttrib from panda3d.core import Shader from panda3d.core import TextureStage, TexGenAttrib from ursina.texture import Texture from panda3d.core import MovieTexture from panda3d.core import TextureStage from panda3d.core import CullFaceAttrib from ursina import application from ursina.collider import * from ursina.mesh import Mesh from ursina.sequence import Sequence, Func, Wait from ursina.ursinamath import lerp from ursina import curve from ursina.curve import CubicBezier from ursina.mesh_importer import load_model from ursina.texture_importer import load_texture from ursina.string_utilities import camel_to_snake from textwrap import dedent from panda3d.core import Shader as Panda3dShader from ursina.shader import Shader from ursina import color try: from ursina.scene import instance as scene except: pass class Entity(NodePath): rotation_directions = (-1,-1,1) default_shader = None def __init__(self, add_to_scene_entities=True, **kwargs): super().__init__(self.__class__.__name__) self.name = camel_to_snake(self.type) self.enabled = True # disabled entities wil not be visible nor run code. self.visible = True self.ignore = False # if True, will not try to run code. self.eternal = False # eternal entities does not get destroyed on scene.clear() self.ignore_paused = False # if True, will still run when application is paused. useful when making a pause menu for example. self.ignore_input = False self.parent = scene # default parent is scene, which means it's in 3d space. to use UI space, set the parent to camera.ui instead. self.add_to_scene_entities = add_to_scene_entities # set to False to be ignored by the engine, but still get rendered. if add_to_scene_entities: scene.entities.append(self) self.model = None # set model with model='model_name' (without file type extention) self.color = color.white self.texture = None # set model with texture='texture_name'. requires a model to be set beforehand. self.render_queue = 0 self.double_sided = False if Entity.default_shader: self.shader = Entity.default_shader self.collision = False # toggle collision without changing collider. self.collider = None # set to 'box'/'sphere'/'mesh' for auto fitted collider. self.scripts = list() # add with add_script(class_instance). will assign an 'entity' variable to the script. self.animations = list() self.hovered = False # will return True if mouse hovers entity. self.origin = Vec3(0,0,0) self.position = Vec3(0,0,0) # right, up, forward. can also set self.x, self.y, self.z self.rotation = Vec3(0,0,0) # can also set self.rotation_x, self.rotation_y, self.rotation_z self.scale = Vec3(1,1,1) # can also set self.scale_x, self.scale_y, self.scale_z self.line_definition = None # returns a Traceback(filename, lineno, function, code_context, index). if application.trace_entity_definition and add_to_scene_entities: from inspect import getframeinfo, stack _stack = stack() caller = getframeinfo(_stack[1][0]) if len(_stack) > 2 and _stack[1].code_context and 'super().__init__()' in _stack[1].code_context[0]: caller = getframeinfo(_stack[2][0]) self.line_definition = caller if caller.code_context: self.code_context = caller.code_context[0] if (self.code_context.count('(') == self.code_context.count(')') and ' = ' in self.code_context and not 'name=' in self.code_context and not 'Ursina()' in self.code_context): self.name = self.code_context.split(' = ')[0].strip().replace('self.', '') # print('set name to:', self.code_context.split(' = ')[0].strip().replace('self.', '')) if application.print_entity_definition: print(f'{Path(caller.filename).name} -> {caller.lineno} -> {caller.code_context}') for key, value in kwargs.items(): setattr(self, key, value) if self.enabled and hasattr(self, 'on_enable'): if callable(self.on_enable): self.on_enable() elif isinstance(self.on_enable, Sequence): self.on_enable.start() elif not self.enabled and hasattr(self, 'on_disable'): if callable(self.on_disable): self.on_disable() elif isinstance(self.on_disable, Sequence): self.on_disable.start() def _list_to_vec(self, value): if isinstance(value, (int, float, complex)): return Vec3(value, value, value) if len(value) % 2 == 0: new_value = Vec2() for i in range(0, len(value), 2): new_value.add_x(value[i]) new_value.add_y(value[i+1]) if len(value) % 3 == 0: new_value = Vec3() for i in range(0, len(value), 3): new_value.add_x(value[i]) new_value.add_y(value[i+1]) new_value.add_z(value[i+2]) return new_value def enable(self): self.enabled = True def disable(self): self.enabled = False @property def enabled(self): if not hasattr(self, '_enabled'): return True return self._enabled @enabled.setter def enabled(self, value): if value and hasattr(self, 'on_enable') and not self.enabled: if callable(self.on_enable): self.on_enable() elif isinstance(self.on_disable, Sequence): self.on_enable.start() elif value == False and hasattr(self, 'on_disable') and self.enabled: if callable(self.on_disable): self.on_disable() elif isinstance(self.on_disable, Sequence): self.on_disable.start() if value == True: if hasattr(self, 'is_singleton') and not self.is_singleton(): self.unstash() else: if hasattr(self, 'is_singleton') and not self.is_singleton(): self.stash() self._enabled = value def __setattr__(self, name, value): if name == 'eternal': for c in self.children: c.eternal = value elif name == 'model': if value is None: if hasattr(self, 'model') and self.model: self.model.removeNode() # print('removed model') object.__setattr__(self, name, value) return None if isinstance(value, NodePath): # pass procedural model if self.model is not None and value != self.model: self.model.removeNode() object.__setattr__(self, name, value) elif isinstance(value, str): # pass model asset name m = load_model(value, application.asset_folder) if not m: m = load_model(value, application.internal_models_compressed_folder) if m: if self.model is not None: self.model.removeNode() object.__setattr__(self, name, m) # if isinstance(m, Mesh): # m.recipe = value # print('loaded model successively') else: # if '.' in value: # print(f'''trying to load model with specific filename extention. please omit it. '{value}' -> '{value.split('.')[0]}' ''') print('missing model:', value) return if self.model: self.model.reparentTo(self) self.model.setTransparency(TransparencyAttrib.M_dual) self.color = self.color # reapply color after changing model self.texture = self.texture # reapply texture after changing model self._vert_cache = None if isinstance(value, Mesh): if hasattr(value, 'on_assign'): value.on_assign(assigned_to=self) return elif name == 'color' and value is not None: if isinstance(value, str): value = color.hex(value) if not isinstance(value, Vec4): value = Vec4(value[0], value[1], value[2], value[3]) if self.model: self.model.setColorScaleOff() # prevent inheriting color from parent self.model.setColorScale(value) object.__setattr__(self, name, value) elif name == 'collision' and hasattr(self, 'collider') and self.collider: if value: self.collider.node_path.unstash() else: self.collider.node_path.stash() object.__setattr__(self, name, value) return elif name == 'render_queue': if self.model: self.model.setBin('fixed', value) elif name == 'double_sided': self.setTwoSided(value) try: super().__setattr__(name, value) except: pass # print('failed to set attribiute:', name) @property def parent(self): try: return self._parent except: return None @parent.setter def parent(self, value): self._parent = value if value is None: destroy(self) else: try: self.reparentTo(value) except: print('invalid parent:', value) @property def world_parent(self): return self.parent @world_parent.setter def world_parent(self, value): # change the parent, but keep position, rotation and scale self.reparent_to(value) @property def type(self): # get class name. return self.__class__.__name__ @property def types(self): # get all class names including those this inhertits from. from inspect import getmro return [c.__name__ for c in getmro(self.__class__)] @property def visible(self): return self._visible @visible.setter def visible(self, value): self._visible = value if value: self.show() else: self.hide() @property def visible_self(self): # set visibility of self, without affecting children. if not hasattr(self, '_visible_self'): return True return self._visible_self @visible_self.setter def visible_self(self, value): self._visible_self = value if not self.model: return if value: self.model.show() else: self.model.hide() @property def collider(self): return self._collider @collider.setter def collider(self, value): # destroy existing collider if value and hasattr(self, 'collider') and self._collider: self._collider.remove() self._collider = value if value == 'box': if self.model: # start, end = self.model.getTightBounds() # model_center = (start + end) / 2 self._collider = BoxCollider(entity=self, center=-self.origin, size=self.model_bounds) else: self._collider = BoxCollider(entity=self) self._collider.name = value elif value == 'sphere': self._collider = SphereCollider(entity=self, center=-self.origin) self._collider.name = value elif value == 'mesh' and self.model: self._collider = MeshCollider(entity=self, mesh=None, center=-self.origin) self._collider.name = value elif isinstance(value, Mesh): self._collider = MeshCollider(entity=self, mesh=value, center=-self.origin) elif isinstance(value, str): m = load_model(value) if not m: return self._collider = MeshCollider(entity=self, mesh=m, center=-self.origin) self._collider.name = value self.collision = bool(self.collider) return @property def origin(self): return self._origin @origin.setter def origin(self, value): if not self.model: self._origin = Vec3(0,0,0) return if not isinstance(value, (Vec2, Vec3)): value = self._list_to_vec(value) if isinstance(value, Vec2): value = Vec3(*value, self.origin_z) self._origin = value self.model.setPos(-value[0], -value[1], -value[2]) @property def origin_x(self): return self.origin[0] @origin_x.setter def origin_x(self, value): self.origin = (value, self.origin_y, self.origin_z) @property def origin_y(self): return self.origin[1] @origin_y.setter def origin_y(self, value): self.origin = (self.origin_x, value, self.origin_z) @property def origin_z(self): return self.origin[2] @origin_z.setter def origin_z(self, value): self.origin = (self.origin_x, self.origin_y, value) @property def world_position(self): return Vec3(self.get_position(render)) @world_position.setter def world_position(self, value): if not isinstance(value, (Vec2, Vec3)): value = self._list_to_vec(value) if isinstance(value, Vec2): value = Vec3(*value, self.z) self.setPos(render, Vec3(value[0], value[1], value[2])) @property def world_x(self): return self.getX(render) @property def world_y(self): return self.getY(render) @property def world_z(self): return self.getZ(render) @world_x.setter def world_x(self, value): self.setX(render, value) @world_y.setter def world_y(self, value): self.setY(render, value) @world_z.setter def world_z(self, value): self.setZ(render, value) @property def position(self): return Vec3(*self.getPos()) @position.setter def position(self, value): if not isinstance(value, (Vec2, Vec3)): value = self._list_to_vec(value) if isinstance(value, Vec2): value = Vec3(*value, self.z) self.setPos(value[0], value[1], value[2]) @property def x(self): return self.getX() @x.setter def x(self, value): self.setX(value) @property def y(self): return self.getY() @y.setter def y(self, value): self.setY(value) @property def z(self): return self.getZ() @z.setter def z(self, value): self.setZ(value) @property def X(self): # shortcut for int(entity.x) return int(self.x) @property def Y(self): # shortcut for int(entity.y) return int(self.y) @property def Z(self): # shortcut for int(entity.z) return int(self.z) @property def world_rotation(self): rotation = self.getHpr(scene) return Vec3(rotation[1], rotation[0], rotation[2]) * Entity.rotation_directions @world_rotation.setter def world_rotation(self, value): self.setHpr(scene, Vec3(value[1], value[0], value[2]) * Entity.rotation_directions) @property def world_rotation_x(self): return self.world_rotation[0] @world_rotation_x.setter def world_rotation_x(self, value): self.world_rotation = Vec3(value, self.world_rotation[1], self.world_rotation[2]) @property def world_rotation_y(self): return self.world_rotation[1] @world_rotation_y.setter def world_rotation_y(self, value): self.world_rotation = Vec3(self.world_rotation[0], value, self.world_rotation[2]) @property def world_rotation_z(self): return self.world_rotation[2] @world_rotation_z.setter def world_rotation_z(self, value): self.world_rotation = Vec3(self.world_rotation[0], self.world_rotation[1], value) @property def rotation(self): rotation = self.getHpr() return Vec3(rotation[1], rotation[0], rotation[2]) * Entity.rotation_directions @rotation.setter def rotation(self, value): if not isinstance(value, (Vec2, Vec3)): value = self._list_to_vec(value) if isinstance(value, Vec2): value = Vec3(*value, self.rotation_z) self.setHpr(Vec3(value[1], value[0], value[2]) * Entity.rotation_directions) @property def rotation_x(self): return self.rotation.x @rotation_x.setter def rotation_x(self, value): self.rotation = Vec3(value, self.rotation[1], self.rotation[2]) @property def rotation_y(self): return self.rotation.y @rotation_y.setter def rotation_y(self, value): self.rotation = Vec3(self.rotation[0], value, self.rotation[2]) @property def rotation_z(self): return self.rotation.z @rotation_z.setter def rotation_z(self, value): self.rotation = Vec3(self.rotation[0], self.rotation[1], value) @property def quat(self): return self.get_quat() @quat.setter def quat(self, value): self.set_quat(value) @property def world_scale(self): return Vec3(*self.getScale(base.render)) @world_scale.setter def world_scale(self, value): if isinstance(value, (int, float, complex)): value = Vec3(value, value, value) self.setScale(base.render, value) @property def world_scale_x(self): return self.getScale(base.render)[0] @world_scale_x.setter def world_scale_x(self, value): self.setScale(base.render, Vec3(value, self.world_scale_y, self.world_scale_z)) @property def world_scale_y(self): return self.getScale(base.render)[1] @world_scale_y.setter def world_scale_y(self, value): self.setScale(base.render, Vec3(self.world_scale_x, value, self.world_scale_z)) @property def world_scale_z(self): return self.getScale(base.render)[2] @world_scale_z.setter def world_scale_z(self, value): self.setScale(base.render, Vec3(self.world_scale_x, value, self.world_scale_z)) @property def scale(self): scale = self.getScale() return Vec3(scale[0], scale[1], scale[2]) @scale.setter def scale(self, value): if not isinstance(value, (Vec2, Vec3)): value = self._list_to_vec(value) if isinstance(value, Vec2): value = Vec3(*value, self.scale_z) value = [e if e!=0 else .001 for e in value] self.setScale(value[0], value[1], value[2]) @property def scale_x(self): return self.scale[0] @scale_x.setter def scale_x(self, value): self.setScale(value, self.scale_y, self.scale_z) @property def scale_y(self): return self.scale[1] @scale_y.setter def scale_y(self, value): self.setScale(self.scale_x, value, self.scale_z) @property def scale_z(self): return self.scale[2] @scale_z.setter def scale_z(self, value): self.setScale(self.scale_x, self.scale_y, value) @property def transform(self): # get/set position, rotation and scale return (self.position, self.rotation, self.scale) @transform.setter def transform(self, value): self.position, self.rotation, self.scale = value @property def world_transform(self): # get/set world_position, world_rotation and world_scale return (self.world_position, self.world_rotation, self.world_scale) @world_transform.setter def world_transform(self, value): self.world_position, self.world_rotation, self.world_scale = value @property def forward(self): # get forward direction. return render.getRelativeVector(self, (0, 0, 1)) @property def back(self): # get backwards direction. return -self.forward @property def right(self): # get right direction. return render.getRelativeVector(self, (1, 0, 0)) @property def left(self): # get left direction. return -self.right @property def up(self): # get up direction. return render.getRelativeVector(self, (0, 1, 0)) @property def down(self): # get down direction. return -self.up @property def screen_position(self): # get screen position(ui space) from world space. from ursina import camera p3 = camera.getRelativePoint(self, Vec3.zero()) full = camera.lens.getProjectionMat().xform(Vec4(*p3, 1)) recip_full3 = 1 / full[3] p2 = Vec3(full[0], full[1], full[2]) * recip_full3 screen_pos = Vec3(p2[0]*camera.aspect_ratio/2, p2[1]/2, 0) return screen_pos @property def shader(self): return self._shader @shader.setter def shader(self, value): self._shader = value if value is None: self.setShaderAuto() return if isinstance(value, Panda3dShader): #panda3d shader self.setShader(value) return if isinstance(value, Shader): if not value.compiled: value.compile() self.setShader(value._shader) value.entity = self for key, value in value.default_input.items(): self.set_shader_input(key, value) return print(value, 'is not a Shader') def set_shader_input(self, name, value): if isinstance(value, Texture): value = value._texture # make sure to send the panda3d texture to the shader super().set_shader_input(name, value) @property def texture(self): if not hasattr(self, '_texture'): return None return self._texture @texture.setter def texture(self, value): if value is None and self._texture: # print('remove texture') # self._texture = None self.model.clearTexture() # del self.texture # self.setTextureOff(True) return if value.__class__ is Texture: texture = value elif isinstance(value, str): texture = load_texture(value) # print('loaded texture:', texture) if texture is None: print('no texture:', value) return self.model.setTextureOff(False) if texture.__class__ is MovieTexture: self._texture = texture self.model.setTexture(texture, 1) return self._texture = texture if self.model: self.model.setTexture(texture._texture, 1) @property def texture_scale(self): if not hasattr(self, '_texture_scale'): return Vec2(1,1) return self._texture_scale @texture_scale.setter def texture_scale(self, value): self._texture_scale = value if self.model and self.texture: self.model.setTexScale(TextureStage.getDefault(), value[0], value[1]) self.set_shader_input('texture_scale', value) @property def texture_offset(self): return self._texture_offset @texture_offset.setter def texture_offset(self, value): if self.model and self.texture: self.model.setTexOffset(TextureStage.getDefault(), value[0], value[1]) self.texture = self.texture self.set_shader_input('texture_offset', value) self._texture_offset = value @property def tileset_size(self): return self._tileset_size @tileset_size.setter def tileset_size(self, value): self._tileset_size = value if self.model and self.texture: self.model.setTexScale(TextureStage.getDefault(), 1/value[0], 1/value[1]) @property def alpha(self): return self.color[3] @alpha.setter def alpha(self, value): if value > 1: value = value / 255 self.color = color.color(self.color.h, self.color.s, self.color.v, value) @property def always_on_top(self): return self._always_on_top @always_on_top.setter def always_on_top(self, value): self._always_on_top = value self.set_bin("fixed", 0) self.set_depth_write(not value) self.set_depth_test(not value) @property def unlit(self): return self._unlit @unlit.setter def unlit(self, value): self._unlit = value self.setLightOff(value) @property def billboard(self): # set to True to make this Entity always face the camera. return self._billboard @billboard.setter def billboard(self, value): self._billboard = value if value: self.setBillboardPointEye(value) def generate_sphere_map(self, size=512, name=f'sphere_map_{len(scene.entities)}'): from ursina import camera _name = 'textures/' + name + '.jpg' org_pos = camera.position camera.position = self.position base.saveSphereMap(_name, size=size) camera.position = org_pos print('saved sphere map:', name) self.model.setTexGen(TextureStage.getDefault(), TexGenAttrib.MEyeSphereMap) self.reflection_map = name def generate_cube_map(self, size=512, name=f'cube_map_{len(scene.entities)}'): from ursina import camera _name = 'textures/' + name org_pos = camera.position camera.position = self.position base.saveCubeMap(_name+'.jpg', size=size) camera.position = org_pos print('saved cube map:', name + '.jpg') self.model.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldCubeMap) self.reflection_map = _name + '#.jpg' self.model.setTexture(loader.loadCubeMap(_name + '#.jpg'), 1) @property def model_bounds(self): if self.model: bounds = self.model.getTightBounds() bounds = Vec3( Vec3(bounds[1][0], bounds[1][1], bounds[1][2]) # max point - Vec3(bounds[0][0], bounds[0][1], bounds[0][2]) # min point ) return bounds return Vec3(0,0,0) @property def model_center(self): if not self.model: return Vec3(0,0,0) return self.model.getTightBounds().getCenter() @property def bounds(self): return Vec3( self.model_bounds[0] * self.scale_x, self.model_bounds[1] * self.scale_y, self.model_bounds[2] * self.scale_z ) def reparent_to(self, entity): if entity is not None: self.wrtReparentTo(entity) self._parent = entity def get_position(self, relative_to=scene): return self.getPos(relative_to) def set_position(self, value, relative_to=scene): self.setPos(relative_to, Vec3(value[0], value[1], value[2])) def add_script(self, class_instance): if isinstance(class_instance, object) and type(class_instance) is not str: class_instance.entity = self class_instance.enabled = True setattr(self, camel_to_snake(class_instance.__class__.__name__), class_instance) self.scripts.append(class_instance) # print('added script:', camel_to_snake(name.__class__.__name__)) return class_instance def combine(self, analyze=False, auto_destroy=True, ignore=[]): from ursina.scripts.combine import combine self.model = combine(self, analyze, auto_destroy, ignore) return self.model def flip_faces(self): if not hasattr(self, '_vertex_order'): self._vertex_order = True self._vertex_order = not self._vertex_order if self._vertex_order: self.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullClockwise)) else: self.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise)) def look_at(self, target, axis='forward'): from panda3d.core import Quat if not isinstance(target, Entity): target = Vec3(*target) self.lookAt(target) if axis == 'forward': return rotation_offset = { 'back' : Quat(0,0,1,0), 'down' : Quat(-.707,.707,0,0), 'up' : Quat(-.707,-.707,0,0), 'right' : Quat(-.707,0,.707,0), 'left' : Quat(-.707,0,-.707,0), }[axis] self.setQuat(rotation_offset * self.getQuat()) def look_at_2d(self, target, axis='z'): from math import degrees, atan2 if isinstance(target, Entity): target = Vec3(target.world_position) pos = target - self.world_position if axis == 'z': self.rotation_z = degrees(atan2(pos[0], pos[1])) def has_ancestor(self, possible_ancestor): p = self if isinstance(possible_ancestor, Entity): # print('ENTITY') for i in range(100): if p.parent: if p.parent == possible_ancestor: return True p = p.parent if isinstance(possible_ancestor, list) or isinstance(possible_ancestor, tuple): # print('LIST OR TUPLE') for e in possible_ancestor: for i in range(100): if p.parent: if p.parent == e: return True break p = p.parent elif isinstance(possible_ancestor, str): print('CLASS NAME', possible_ancestor) for i in range(100): if p.parent: if p.parent.__class__.__name__ == possible_ancestor: return True break p = p.parent return False @property def children(self): return [e for e in scene.entities if e.parent == self] @property def attributes(self): # attribute names. used by duplicate() for instance. return ('name', 'enabled', 'eternal', 'visible', 'parent', 'origin', 'position', 'rotation', 'scale', 'model', 'color', 'texture', 'texture_scale', 'texture_offset', # 'world_position', 'world_x', 'world_y', 'world_z', # 'world_rotation', 'world_rotation_x', 'world_rotation_y', 'world_rotation_z', # 'world_scale', 'world_scale_x', 'world_scale_y', 'world_scale_z', # 'x', 'y', 'z', # 'origin_x', 'origin_y', 'origin_z', # 'rotation_x', 'rotation_y', 'rotation_z', # 'scale_x', 'scale_y', 'scale_z', 'render_queue', 'always_on_top', 'collision', 'collider', 'scripts') #------------ # ANIMATIONS #------------ def animate(self, name, value, duration=.1, delay=0, curve=curve.in_expo, loop=False, resolution=None, interrupt='kill', time_step=None, auto_destroy=True): if duration == 0 and delay == 0: setattr(self, name, value) return None if delay: from ursina.ursinastuff import invoke return invoke(self.animate, name, value, duration=duration, curve=curve, loop=loop, resolution=resolution, time_step=time_step, auto_destroy=auto_destroy, delay=delay) animator_name = name + '_animator' # print('start animating value:', name, animator_name ) if interrupt and hasattr(self, animator_name): getattr(getattr(self, animator_name), interrupt)() # call kill() or finish() depending on what the interrupt value is. # print('interrupt', interrupt, animator_name) sequence = Sequence(loop=loop, time_step=time_step, auto_destroy=auto_destroy) setattr(self, animator_name, sequence) self.animations.append(sequence) if not resolution: resolution = max(int(duration * 60), 1) for i in range(resolution+1): t = i / resolution t = curve(t) sequence.append(Wait(duration / resolution)) sequence.append(Func(setattr, self, name, lerp(getattr(self, name), value, t))) sequence.start() return sequence def animate_position(self, value, duration=.1, **kwargs): x = self.animate('x', value[0], duration, **kwargs) y = self.animate('y', value[1], duration, **kwargs) z = None if len(value) > 2: z = self.animate('z', value[2], duration, **kwargs) return x, y, z def animate_rotation(self, value, duration=.1, **kwargs): x = self.animate('rotation_x', value[0], duration, **kwargs) y = self.animate('rotation_y', value[1], duration, **kwargs) z = self.animate('rotation_z', value[2], duration, **kwargs) return x, y, z def animate_scale(self, value, duration=.1, **kwargs): if isinstance(value, (int, float, complex)): value = Vec3(value, value, value) elif isinstance(value, tuple) and len(value) == 2: value = Vec3(*value, self.z) return self.animate('scale', value, duration, **kwargs) # generate animation functions for e in ('x', 'y', 'z', 'rotation_x', 'rotation_y', 'rotation_z', 'scale_x', 'scale_y', 'scale_z'): exec(dedent(f''' def animate_{e}(self, value, duration=.1, delay=0, **kwargs): return self.animate('{e}', value, duration=duration, delay=delay, **kwargs) ''')) def shake(self, duration=.2, magnitude=1, speed=.05, direction=(1,1)): import random s = Sequence() original_position = self.world_position for i in range(int(duration / speed)): s.append(Func(self.set_position, Vec3( original_position[0] + (random.uniform(-.1, .1) * magnitude * direction[0]), original_position[1] + (random.uniform(-.1, .1) * magnitude * direction[1]), original_position[2], ))) s.append(Wait(speed)) s.append(Func(setattr, self, 'world_position', original_position)) s.start() return s def animate_color(self, value, duration=.1, interrupt='finish', **kwargs): return self.animate('color', value, duration, interrupt=interrupt, **kwargs) def fade_out(self, value=0, duration=.5, **kwargs): return self.animate('color', Vec4(self.color[0], self.color[1], self.color[2], value), duration, **kwargs) def fade_in(self, value=1, duration=.5, **kwargs): return self.animate('color', Vec4(self.color[0], self.color[1], self.color[2], value), duration, **kwargs) def blink(self, value=color.clear, duration=.1, delay=0, curve=curve.in_expo_boomerang, interrupt='finish', **kwargs): return self.animate_color(value, duration=duration, delay=delay, curve=curve, interrupt=interrupt, **kwargs) def intersects(self, traverse_target=scene, ignore=(), debug=False): if isinstance(self.collider, MeshCollider): raise Exception('''error: mesh colliders can't intersect other shapes, only primitive shapes can. Mesh colliders can "recieve" collisions though.''') from ursina.hit_info import HitInfo if not self.collision or not self.collider: self.hit = HitInfo(hit=False) return self.hit from ursina import distance if not hasattr(self, '_picker'): from panda3d.core import CollisionTraverser, CollisionNode, CollisionHandlerQueue from panda3d.core import CollisionRay, CollisionSegment, CollisionBox self._picker = CollisionTraverser() # Make a traverser self._pq = CollisionHandlerQueue() # Make a handler self._pickerNode = CollisionNode('raycaster') self._pickerNode.set_into_collide_mask(0) self._pickerNP = self.attach_new_node(self._pickerNode) self._picker.addCollider(self._pickerNP, self._pq) self._pickerNP.show() self._pickerNode.addSolid(self._collider.shape) if debug: self._pickerNP.show() else: self._pickerNP.hide() self._picker.traverse(traverse_target) if self._pq.get_num_entries() == 0: self.hit = HitInfo(hit=False) return self.hit ignore += (self, ) ignore += tuple([e for e in scene.entities if not e.collision]) self._pq.sort_entries() self.entries = [ # filter out ignored entities e for e in self._pq.getEntries() if e.get_into_node_path().parent not in ignore ] if len(self.entries) == 0: self.hit = HitInfo(hit=False, distance=0) return self.hit collision = self.entries[0] nP = collision.get_into_node_path().parent point = collision.get_surface_point(nP) point = Vec3(*point) world_point = collision.get_surface_point(render) world_point = Vec3(*world_point) hit_dist = distance(self.world_position, world_point) self.hit = HitInfo(hit=True) self.hit.entity = next(e for e in scene.entities if e == nP) self.hit.point = point self.hit.world_point = world_point self.hit.distance = hit_dist normal = collision.get_surface_normal(collision.get_into_node_path().parent).normalized() self.hit.normal = Vec3(*normal) normal = collision.get_surface_normal(render).normalized() self.hit.world_normal = Vec3(*normal) self.hit.entities = [] for collision in self.entries: self.hit.entities.append(next(e for e in scene.entities if e == collision.get_into_node_path().parent)) return self.hit if __name__ == '__main__': from ursina import * app = Ursina() e = Entity(model='quad', color=color.orange, position=(0,0,1), scale=1.5, rotation=(0,0,45), texture='brick') '''example of inheriting Entity''' class Player(Entity): def __init__(self, **kwargs): super().__init__() self.model='cube' self.color = color.red self.scale_y = 2 for key, value in kwargs.items(): setattr(self, key, value) # input and update functions gets automatically called by the engine def input(self, key): if key == 'space': # self.color = self.color.inverse() self.animate_x(2, duration=1) def update(self): self.x += held_keys['d'] * time.dt * 10 self.x -= held_keys['a'] * time.dt * 10 player = Player(x=-1) # test e = Entity(model='cube') # e.animate_x(3, duration=2, delay=.5, loop=True) # e.animate_position(Vec3(1,1,1), duration=1, loop=True) # e.animate_rotation(Vec3(45,45,45)) # e.animate_scale(2, duration=1, curve=curve.out_expo_boomerang, loop=True) # e.animate_color(color.green, loop=True) # e.shake() # e.fade_out(delay=.5) # e.fade_in(delay=2.5) e.blink(color.red, duration=1, curve=curve.linear_boomerang, loop=True) app.run()
import sys import importlib import glob from pathlib import Path from panda3d.core import NodePath from ursina.vec3 import Vec3 from panda3d.core import Vec4, Vec2 from panda3d.core import TransparencyAttrib from panda3d.core import Shader from panda3d.core import TextureStage, TexGenAttrib from ursina.texture import Texture from panda3d.core import MovieTexture from panda3d.core import TextureStage from panda3d.core import CullFaceAttrib from ursina import application from ursina.collider import * from ursina.mesh import Mesh from ursina.sequence import Sequence, Func, Wait from ursina.ursinamath import lerp from ursina import curve from ursina.curve import CubicBezier from ursina.mesh_importer import load_model from ursina.texture_importer import load_texture from ursina.string_utilities import camel_to_snake from textwrap import dedent from panda3d.core import Shader as Panda3dShader from ursina.shader import Shader from ursina import color try: from ursina.scene import instance as scene except: pass class Entity(NodePath): rotation_directions = (-1,-1,1) default_shader = None def __init__(self, add_to_scene_entities=True, **kwargs): super().__init__(self.__class__.__name__) self.name = camel_to_snake(self.type) self.enabled = True # disabled entities wil not be visible nor run code. self.visible = True self.ignore = False # if True, will not try to run code. self.eternal = False # eternal entities does not get destroyed on scene.clear() self.ignore_paused = False # if True, will still run when application is paused. useful when making a pause menu for example. self.ignore_input = False self.parent = scene # default parent is scene, which means it's in 3d space. to use UI space, set the parent to camera.ui instead. self.add_to_scene_entities = add_to_scene_entities # set to False to be ignored by the engine, but still get rendered. if add_to_scene_entities: scene.entities.append(self) self.model = None # set model with model='model_name' (without file type extention) self.color = color.white self.texture = None # set model with texture='texture_name'. requires a model to be set beforehand. self.render_queue = 0 self.double_sided = False if Entity.default_shader: self.shader = Entity.default_shader self.collision = False # toggle collision without changing collider. self.collider = None # set to 'box'/'sphere'/'mesh' for auto fitted collider. self.scripts = list() # add with add_script(class_instance). will assign an 'entity' variable to the script. self.animations = list() self.hovered = False # will return True if mouse hovers entity. self.origin = Vec3(0,0,0) self.position = Vec3(0,0,0) # right, up, forward. can also set self.x, self.y, self.z self.rotation = Vec3(0,0,0) # can also set self.rotation_x, self.rotation_y, self.rotation_z self.scale = Vec3(1,1,1) # can also set self.scale_x, self.scale_y, self.scale_z self.line_definition = None # returns a Traceback(filename, lineno, function, code_context, index). if application.trace_entity_definition and add_to_scene_entities: from inspect import getframeinfo, stack _stack = stack() caller = getframeinfo(_stack[1][0]) if len(_stack) > 2 and _stack[1].code_context and 'super().__init__()' in _stack[1].code_context[0]: caller = getframeinfo(_stack[2][0]) self.line_definition = caller if caller.code_context: self.code_context = caller.code_context[0] if (self.code_context.count('(') == self.code_context.count(')') and ' = ' in self.code_context and not 'name=' in self.code_context and not 'Ursina()' in self.code_context): self.name = self.code_context.split(' = ')[0].strip().replace('self.', '') # print('set name to:', self.code_context.split(' = ')[0].strip().replace('self.', '')) if application.print_entity_definition: print(f'{Path(caller.filename).name} -> {caller.lineno} -> {caller.code_context}') for key, value in kwargs.items(): setattr(self, key, value) if self.enabled and hasattr(self, 'on_enable'): if callable(self.on_enable): self.on_enable() elif isinstance(self.on_enable, Sequence): self.on_enable.start() elif not self.enabled and hasattr(self, 'on_disable'): if callable(self.on_disable): self.on_disable() elif isinstance(self.on_disable, Sequence): self.on_disable.start() def _list_to_vec(self, value): if isinstance(value, (int, float, complex)): return Vec3(value, value, value) if len(value) % 2 == 0: new_value = Vec2() for i in range(0, len(value), 2): new_value.add_x(value[i]) new_value.add_y(value[i+1]) if len(value) % 3 == 0: new_value = Vec3() for i in range(0, len(value), 3): new_value.add_x(value[i]) new_value.add_y(value[i+1]) new_value.add_z(value[i+2]) return new_value def enable(self): self.enabled = True def disable(self): self.enabled = False @property def enabled(self): if not hasattr(self, '_enabled'): return True return self._enabled @enabled.setter def enabled(self, value): if value and hasattr(self, 'on_enable') and not self.enabled: if callable(self.on_enable): self.on_enable() elif isinstance(self.on_disable, Sequence): self.on_enable.start() elif value == False and hasattr(self, 'on_disable') and self.enabled: if callable(self.on_disable): self.on_disable() elif isinstance(self.on_disable, Sequence): self.on_disable.start() if value == True: if hasattr(self, 'is_singleton') and not self.is_singleton(): self.unstash() else: if hasattr(self, 'is_singleton') and not self.is_singleton(): self.stash() self._enabled = value def __setattr__(self, name, value): if name == 'eternal': for c in self.children: c.eternal = value elif name == 'model': if value is None: if hasattr(self, 'model') and self.model: self.model.removeNode() # print('removed model') object.__setattr__(self, name, value) return None if isinstance(value, NodePath): # pass procedural model if self.model is not None and value != self.model: self.model.removeNode() object.__setattr__(self, name, value) elif isinstance(value, str): # pass model asset name m = load_model(value, application.asset_folder) if not m: m = load_model(value, application.internal_models_compressed_folder) if m: if self.model is not None: self.model.removeNode() object.__setattr__(self, name, m) # if isinstance(m, Mesh): # m.recipe = value # print('loaded model successively') else: # if '.' in value: # print(f'''trying to load model with specific filename extention. please omit it. '{value}' -> '{value.split('.')[0]}' ''') print('missing model:', value) return if self.model: self.model.reparentTo(self) self.model.setTransparency(TransparencyAttrib.M_dual) self.color = self.color # reapply color after changing model self.texture = self.texture # reapply texture after changing model self._vert_cache = None if isinstance(value, Mesh): if hasattr(value, 'on_assign'): value.on_assign(assigned_to=self) return elif name == 'color' and value is not None: if isinstance(value, str): value = color.hex(value) if not isinstance(value, Vec4): value = Vec4(value[0], value[1], value[2], value[3]) if self.model: self.model.setColorScaleOff() # prevent inheriting color from parent self.model.setColorScale(value) object.__setattr__(self, name, value) elif name == 'collision' and hasattr(self, 'collider') and self.collider: if value: self.collider.node_path.unstash() else: self.collider.node_path.stash() object.__setattr__(self, name, value) return elif name == 'render_queue': if self.model: self.model.setBin('fixed', value) elif name == 'double_sided': self.setTwoSided(value) try: super().__setattr__(name, value) except: pass # print('failed to set attribiute:', name) @property def parent(self): try: return self._parent except: return None @parent.setter def parent(self, value): self._parent = value if value is None: destroy(self) else: try: self.reparentTo(value) except: print('invalid parent:', value) @property def world_parent(self): return self.parent @world_parent.setter def world_parent(self, value): # change the parent, but keep position, rotation and scale self.reparent_to(value) @property def type(self): # get class name. return self.__class__.__name__ @property def types(self): # get all class names including those this inhertits from. from inspect import getmro return [c.__name__ for c in getmro(self.__class__)] @property def visible(self): return self._visible @visible.setter def visible(self, value): self._visible = value if value: self.show() else: self.hide() @property def visible_self(self): # set visibility of self, without affecting children. if not hasattr(self, '_visible_self'): return True return self._visible_self @visible_self.setter def visible_self(self, value): self._visible_self = value if not self.model: return if value: self.model.show() else: self.model.hide() @property def collider(self): return self._collider @collider.setter def collider(self, value): # destroy existing collider if value and hasattr(self, 'collider') and self._collider: self._collider.remove() self._collider = value if value == 'box': if self.model: # start, end = self.model.getTightBounds() # model_center = (start + end) / 2 self._collider = BoxCollider(entity=self, center=-self.origin, size=self.model_bounds) else: self._collider = BoxCollider(entity=self) self._collider.name = value elif value == 'sphere': self._collider = SphereCollider(entity=self, center=-self.origin) self._collider.name = value elif value == 'mesh' and self.model: self._collider = MeshCollider(entity=self, mesh=None, center=-self.origin) self._collider.name = value elif isinstance(value, Mesh): self._collider = MeshCollider(entity=self, mesh=value, center=-self.origin) elif isinstance(value, str): m = load_model(value) if not m: return self._collider = MeshCollider(entity=self, mesh=m, center=-self.origin) self._collider.name = value self.collision = bool(self.collider) return @property def origin(self): return self._origin @origin.setter def origin(self, value): if not self.model: self._origin = Vec3(0,0,0) return if not isinstance(value, (Vec2, Vec3)): value = self._list_to_vec(value) if isinstance(value, Vec2): value = Vec3(*value, self.origin_z) self._origin = value self.model.setPos(-value[0], -value[1], -value[2]) @property def origin_x(self): return self.origin[0] @origin_x.setter def origin_x(self, value): self.origin = (value, self.origin_y, self.origin_z) @property def origin_y(self): return self.origin[1] @origin_y.setter def origin_y(self, value): self.origin = (self.origin_x, value, self.origin_z) @property def origin_z(self): return self.origin[2] @origin_z.setter def origin_z(self, value): self.origin = (self.origin_x, self.origin_y, value) @property def world_position(self): return Vec3(self.get_position(render)) @world_position.setter def world_position(self, value): if not isinstance(value, (Vec2, Vec3)): value = self._list_to_vec(value) if isinstance(value, Vec2): value = Vec3(*value, self.z) self.setPos(render, Vec3(value[0], value[1], value[2])) @property def world_x(self): return self.getX(render) @property def world_y(self): return self.getY(render) @property def world_z(self): return self.getZ(render) @world_x.setter def world_x(self, value): self.setX(render, value) @world_y.setter def world_y(self, value): self.setY(render, value) @world_z.setter def world_z(self, value): self.setZ(render, value) @property def position(self): return Vec3(*self.getPos()) @position.setter def position(self, value): if not isinstance(value, (Vec2, Vec3)): value = self._list_to_vec(value) if isinstance(value, Vec2): value = Vec3(*value, self.z) self.setPos(value[0], value[1], value[2]) @property def x(self): return self.getX() @x.setter def x(self, value): self.setX(value) @property def y(self): return self.getY() @y.setter def y(self, value): self.setY(value) @property def z(self): return self.getZ() @z.setter def z(self, value): self.setZ(value) @property def X(self): # shortcut for int(entity.x) return int(self.x) @property def Y(self): # shortcut for int(entity.y) return int(self.y) @property def Z(self): # shortcut for int(entity.z) return int(self.z) @property def world_rotation(self): rotation = self.getHpr(scene) return Vec3(rotation[1], rotation[0], rotation[2]) * Entity.rotation_directions @world_rotation.setter def world_rotation(self, value): self.setHpr(scene, Vec3(value[1], value[0], value[2]) * Entity.rotation_directions) @property def world_rotation_x(self): return self.world_rotation[0] @world_rotation_x.setter def world_rotation_x(self, value): self.world_rotation = Vec3(value, self.world_rotation[1], self.world_rotation[2]) @property def world_rotation_y(self): return self.world_rotation[1] @world_rotation_y.setter def world_rotation_y(self, value): self.world_rotation = Vec3(self.world_rotation[0], value, self.world_rotation[2]) @property def world_rotation_z(self): return self.world_rotation[2] @world_rotation_z.setter def world_rotation_z(self, value): self.world_rotation = Vec3(self.world_rotation[0], self.world_rotation[1], value) @property def rotation(self): rotation = self.getHpr() return Vec3(rotation[1], rotation[0], rotation[2]) * Entity.rotation_directions @rotation.setter def rotation(self, value): if not isinstance(value, (Vec2, Vec3)): value = self._list_to_vec(value) if isinstance(value, Vec2): value = Vec3(*value, self.rotation_z) self.setHpr(Vec3(value[1], value[0], value[2]) * Entity.rotation_directions) @property def rotation_x(self): return self.rotation.x @rotation_x.setter def rotation_x(self, value): self.rotation = Vec3(value, self.rotation[1], self.rotation[2]) @property def rotation_y(self): return self.rotation.y @rotation_y.setter def rotation_y(self, value): self.rotation = Vec3(self.rotation[0], value, self.rotation[2]) @property def rotation_z(self): return self.rotation.z @rotation_z.setter def rotation_z(self, value): self.rotation = Vec3(self.rotation[0], self.rotation[1], value) @property def quat(self): return self.get_quat() @quat.setter def quat(self, value): self.set_quat(value) @property def world_scale(self): return Vec3(*self.getScale(base.render)) @world_scale.setter def world_scale(self, value): if isinstance(value, (int, float, complex)): value = Vec3(value, value, value) self.setScale(base.render, value) @property def world_scale_x(self): return self.getScale(base.render)[0] @world_scale_x.setter def world_scale_x(self, value): self.setScale(base.render, Vec3(value, self.world_scale_y, self.world_scale_z)) @property def world_scale_y(self): return self.getScale(base.render)[1] @world_scale_y.setter def world_scale_y(self, value): self.setScale(base.render, Vec3(self.world_scale_x, value, self.world_scale_z)) @property def world_scale_z(self): return self.getScale(base.render)[2] @world_scale_z.setter def world_scale_z(self, value): self.setScale(base.render, Vec3(self.world_scale_x, value, self.world_scale_z)) @property def scale(self): scale = self.getScale() return Vec3(scale[0], scale[1], scale[2]) @scale.setter def scale(self, value): if not isinstance(value, (Vec2, Vec3)): value = self._list_to_vec(value) if isinstance(value, Vec2): value = Vec3(*value, self.scale_z) value = [e if e!=0 else .001 for e in value] self.setScale(value[0], value[1], value[2]) @property def scale_x(self): return self.scale[0] @scale_x.setter def scale_x(self, value): self.setScale(value, self.scale_y, self.scale_z) @property def scale_y(self): return self.scale[1] @scale_y.setter def scale_y(self, value): self.setScale(self.scale_x, value, self.scale_z) @property def scale_z(self): return self.scale[2] @scale_z.setter def scale_z(self, value): self.setScale(self.scale_x, self.scale_y, value) @property def transform(self): # get/set position, rotation and scale return (self.position, self.rotation, self.scale) @transform.setter def transform(self, value): self.position, self.rotation, self.scale = value @property def world_transform(self): # get/set world_position, world_rotation and world_scale return (self.world_position, self.world_rotation, self.world_scale) @world_transform.setter def world_transform(self, value): self.world_position, self.world_rotation, self.world_scale = value @property def forward(self): # get forward direction. return render.getRelativeVector(self, (0, 0, 1)) @property def back(self): # get backwards direction. return -self.forward @property def right(self): # get right direction. return render.getRelativeVector(self, (1, 0, 0)) @property def left(self): # get left direction. return -self.right @property def up(self): # get up direction. return render.getRelativeVector(self, (0, 1, 0)) @property def down(self): # get down direction. return -self.up @property def screen_position(self): # get screen position(ui space) from world space. from ursina import camera p3 = camera.getRelativePoint(self, Vec3.zero()) full = camera.lens.getProjectionMat().xform(Vec4(*p3, 1)) recip_full3 = 1 / full[3] p2 = Vec3(full[0], full[1], full[2]) * recip_full3 screen_pos = Vec3(p2[0]*camera.aspect_ratio/2, p2[1]/2, 0) return screen_pos @property def shader(self): return self._shader @shader.setter def shader(self, value): self._shader = value if value is None: self.setShaderAuto() return if isinstance(value, Panda3dShader): #panda3d shader self.setShader(value) return if isinstance(value, Shader): if not value.compiled: value.compile() self.setShader(value._shader) value.entity = self for key, value in value.default_input.items(): self.set_shader_input(key, value) return print(value, 'is not a Shader') def set_shader_input(self, name, value): if isinstance(value, Texture): value = value._texture # make sure to send the panda3d texture to the shader super().set_shader_input(name, value) @property def texture(self): if not hasattr(self, '_texture'): return None return self._texture @texture.setter def texture(self, value): if value is None and self._texture: # print('remove texture') # self._texture = None self.model.clearTexture() # del self.texture # self.setTextureOff(True) return if value.__class__ is Texture: texture = value elif isinstance(value, str): texture = load_texture(value) # print('loaded texture:', texture) if texture is None: print('no texture:', value) return self.model.setTextureOff(False) if texture.__class__ is MovieTexture: self._texture = texture self.model.setTexture(texture, 1) return self._texture = texture if self.model: self.model.setTexture(texture._texture, 1) @property def texture_scale(self): if not hasattr(self, '_texture_scale'): return Vec2(1,1) return self._texture_scale @texture_scale.setter def texture_scale(self, value): self._texture_scale = value if self.model and self.texture: self.model.setTexScale(TextureStage.getDefault(), value[0], value[1]) self.set_shader_input('texture_scale', value) @property def texture_offset(self): return self._texture_offset @texture_offset.setter def texture_offset(self, value): if self.model and self.texture: self.model.setTexOffset(TextureStage.getDefault(), value[0], value[1]) self.texture = self.texture self.set_shader_input('texture_offset', value) self._texture_offset = value @property def tileset_size(self): return self._tileset_size @tileset_size.setter def tileset_size(self, value): self._tileset_size = value if self.model and self.texture: self.model.setTexScale(TextureStage.getDefault(), 1/value[0], 1/value[1]) @property def alpha(self): return self.color[3] @alpha.setter def alpha(self, value): if value > 1: value = value / 255 self.color = color.color(self.color.h, self.color.s, self.color.v, value) @property def always_on_top(self): return self._always_on_top @always_on_top.setter def always_on_top(self, value): self._always_on_top = value self.set_bin("fixed", 0) self.set_depth_write(not value) self.set_depth_test(not value) @property def unlit(self): return self._unlit @unlit.setter def unlit(self, value): self._unlit = value self.setLightOff(value) @property def billboard(self): # set to True to make this Entity always face the camera. return self._billboard @billboard.setter def billboard(self, value): self._billboard = value if value: self.setBillboardPointEye(value) def generate_sphere_map(self, size=512, name=f'sphere_map_{len(scene.entities)}'): from ursina import camera _name = 'textures/' + name + '.jpg' org_pos = camera.position camera.position = self.position base.saveSphereMap(_name, size=size) camera.position = org_pos print('saved sphere map:', name) self.model.setTexGen(TextureStage.getDefault(), TexGenAttrib.MEyeSphereMap) self.reflection_map = name def generate_cube_map(self, size=512, name=f'cube_map_{len(scene.entities)}'): from ursina import camera _name = 'textures/' + name org_pos = camera.position camera.position = self.position base.saveCubeMap(_name+'.jpg', size=size) camera.position = org_pos print('saved cube map:', name + '.jpg') self.model.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldCubeMap) self.reflection_map = _name + '#.jpg' self.model.setTexture(loader.loadCubeMap(_name + '#.jpg'), 1) @property def model_bounds(self): if self.model: bounds = self.model.getTightBounds() bounds = Vec3( Vec3(bounds[1][0], bounds[1][1], bounds[1][2]) # max point - Vec3(bounds[0][0], bounds[0][1], bounds[0][2]) # min point ) return bounds return Vec3(0,0,0) @property def model_center(self): if not self.model: return Vec3(0,0,0) return self.model.getTightBounds().getCenter() @property def bounds(self): return Vec3( self.model_bounds[0] * self.scale_x, self.model_bounds[1] * self.scale_y, self.model_bounds[2] * self.scale_z ) def reparent_to(self, entity): if entity is not None: self.wrtReparentTo(entity) self._parent = entity def get_position(self, relative_to=scene): return self.getPos(relative_to) def set_position(self, value, relative_to=scene): self.setPos(relative_to, Vec3(value[0], value[1], value[2])) def add_script(self, class_instance): if isinstance(class_instance, object) and type(class_instance) is not str: class_instance.entity = self class_instance.enabled = True setattr(self, camel_to_snake(class_instance.__class__.__name__), class_instance) self.scripts.append(class_instance) # print('added script:', camel_to_snake(name.__class__.__name__)) return class_instance def combine(self, analyze=False, auto_destroy=True, ignore=[]): from ursina.scripts.combine import combine self.model = combine(self, analyze, auto_destroy, ignore) return self.model def flip_faces(self): if not hasattr(self, '_vertex_order'): self._vertex_order = True self._vertex_order = not self._vertex_order if self._vertex_order: self.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullClockwise)) else: self.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise)) def look_at(self, target, axis='forward'): from panda3d.core import Quat if not isinstance(target, Entity): target = Vec3(*target) self.lookAt(target) if axis == 'forward': return rotation_offset = { 'back' : Quat(0,0,1,0), 'down' : Quat(-.707,.707,0,0), 'up' : Quat(-.707,-.707,0,0), 'right' : Quat(-.707,0,.707,0), 'left' : Quat(-.707,0,-.707,0), }[axis] self.setQuat(rotation_offset * self.getQuat()) def look_at_2d(self, target, axis='z'): from math import degrees, atan2 if isinstance(target, Entity): target = Vec3(target.world_position) pos = target - self.world_position if axis == 'z': self.rotation_z = degrees(atan2(pos[0], pos[1])) def has_ancestor(self, possible_ancestor): p = self if isinstance(possible_ancestor, Entity): # print('ENTITY') for i in range(100): if p.parent: if p.parent == possible_ancestor: return True p = p.parent if isinstance(possible_ancestor, list) or isinstance(possible_ancestor, tuple): # print('LIST OR TUPLE') for e in possible_ancestor: for i in range(100): if p.parent: if p.parent == e: return True break p = p.parent elif isinstance(possible_ancestor, str): print('CLASS NAME', possible_ancestor) for i in range(100): if p.parent: if p.parent.__class__.__name__ == possible_ancestor: return True break p = p.parent return False @property def children(self): return [e for e in scene.entities if e.parent == self] @property def attributes(self): # attribute names. used by duplicate() for instance. return ('name', 'enabled', 'eternal', 'visible', 'parent', 'origin', 'position', 'rotation', 'scale', 'model', 'color', 'texture', 'texture_scale', 'texture_offset', # 'world_position', 'world_x', 'world_y', 'world_z', # 'world_rotation', 'world_rotation_x', 'world_rotation_y', 'world_rotation_z', # 'world_scale', 'world_scale_x', 'world_scale_y', 'world_scale_z', # 'x', 'y', 'z', # 'origin_x', 'origin_y', 'origin_z', # 'rotation_x', 'rotation_y', 'rotation_z', # 'scale_x', 'scale_y', 'scale_z', 'render_queue', 'always_on_top', 'collision', 'collider', 'scripts') #------------ # ANIMATIONS #------------ def animate(self, name, value, duration=.1, delay=0, curve=curve.in_expo, loop=False, resolution=None, interrupt='kill', time_step=None, auto_destroy=True): if duration == 0 and delay == 0: setattr(self, name, value) return None if delay: from ursina.ursinastuff import invoke return invoke(self.animate, name, value, duration=duration, curve=curve, loop=loop, resolution=resolution, time_step=time_step, auto_destroy=auto_destroy, delay=delay) animator_name = name + '_animator' # print('start animating value:', name, animator_name ) if interrupt and hasattr(self, animator_name): getattr(getattr(self, animator_name), interrupt)() # call kill() or finish() depending on what the interrupt value is. # print('interrupt', interrupt, animator_name) sequence = Sequence(loop=loop, time_step=time_step, auto_destroy=auto_destroy) setattr(self, animator_name, sequence) self.animations.append(sequence) if not resolution: resolution = max(int(duration * 60), 1) for i in range(resolution+1): t = i / resolution t = curve(t) sequence.append(Wait(duration / resolution)) sequence.append(Func(setattr, self, name, lerp(getattr(self, name), value, t))) sequence.start() return sequence def animate_position(self, value, duration=.1, **kwargs): x = self.animate('x', value[0], duration, **kwargs) y = self.animate('y', value[1], duration, **kwargs) z = None if len(value) > 2: z = self.animate('z', value[2], duration, **kwargs) return x, y, z def animate_rotation(self, value, duration=.1, **kwargs): x = self.animate('rotation_x', value[0], duration, **kwargs) y = self.animate('rotation_y', value[1], duration, **kwargs) z = self.animate('rotation_z', value[2], duration, **kwargs) return x, y, z def animate_scale(self, value, duration=.1, **kwargs): if isinstance(value, (int, float, complex)): value = Vec3(value, value, value) elif isinstance(value, tuple) and len(value) == 2: value = Vec3(*value, self.z) return self.animate('scale', value, duration, **kwargs) # generate animation functions for e in ('x', 'y', 'z', 'rotation_x', 'rotation_y', 'rotation_z', 'scale_x', 'scale_y', 'scale_z'): exec(dedent(f''' def animate_{e}(self, value, duration=.1, delay=0, **kwargs): return self.animate('{e}', value, duration=duration, delay=delay, **kwargs) ''')) def shake(self, duration=.2, magnitude=1, speed=.05, direction=(1,1)): import random s = Sequence() original_position = self.world_position for i in range(int(duration / speed)): s.append(Func(self.set_position, Vec3( original_position[0] + (random.uniform(-.1, .1) * magnitude * direction[0]), original_position[1] + (random.uniform(-.1, .1) * magnitude * direction[1]), original_position[2], ))) s.append(Wait(speed)) s.append(Func(setattr, self, 'world_position', original_position)) s.start() return s def animate_color(self, value, duration=.1, interrupt='finish', **kwargs): return self.animate('color', value, duration, interrupt=interrupt, **kwargs) def fade_out(self, value=0, duration=.5, **kwargs): return self.animate('color', Vec4(self.color[0], self.color[1], self.color[2], value), duration, **kwargs) def fade_in(self, value=1, duration=.5, **kwargs): return self.animate('color', Vec4(self.color[0], self.color[1], self.color[2], value), duration, **kwargs) def blink(self, value=color.clear, duration=.1, delay=0, curve=curve.in_expo_boomerang, interrupt='finish', **kwargs): return self.animate_color(value, duration=duration, delay=delay, curve=curve, interrupt=interrupt, **kwargs) def intersects(self, traverse_target=scene, ignore=(), debug=False): if isinstance(self.collider, MeshCollider): raise Exception('''error: mesh colliders can't intersect other shapes, only primitive shapes can. Mesh colliders can "recieve" collisions though.''') from ursina.hit_info import HitInfo if not self.collision or not self.collider: self.hit = HitInfo(hit=False) return self.hit from ursina import distance if not hasattr(self, '_picker'): from panda3d.core import CollisionTraverser, CollisionNode, CollisionHandlerQueue from panda3d.core import CollisionRay, CollisionSegment, CollisionBox self._picker = CollisionTraverser() # Make a traverser self._pq = CollisionHandlerQueue() # Make a handler self._pickerNode = CollisionNode('raycaster') self._pickerNode.set_into_collide_mask(0) self._pickerNP = self.attach_new_node(self._pickerNode) self._picker.addCollider(self._pickerNP, self._pq) self._pickerNP.show() self._pickerNode.addSolid(self._collider.shape) if debug: self._pickerNP.show() else: self._pickerNP.hide() self._picker.traverse(traverse_target) if self._pq.get_num_entries() == 0: self.hit = HitInfo(hit=False) return self.hit ignore += (self, ) ignore += tuple([e for e in scene.entities if not e.collision]) self._pq.sort_entries() self.entries = [ # filter out ignored entities e for e in self._pq.getEntries() if e.get_into_node_path().parent not in ignore ] if len(self.entries) == 0: self.hit = HitInfo(hit=False, distance=0) return self.hit collision = self.entries[0] nP = collision.get_into_node_path().parent point = collision.get_surface_point(nP) point = Vec3(*point) world_point = collision.get_surface_point(render) world_point = Vec3(*world_point) hit_dist = distance(self.world_position, world_point) self.hit = HitInfo(hit=True) self.hit.entity = next(e for e in scene.entities if e == nP) self.hit.point = point self.hit.world_point = world_point self.hit.distance = hit_dist normal = collision.get_surface_normal(collision.get_into_node_path().parent).normalized() self.hit.normal = Vec3(*normal) normal = collision.get_surface_normal(render).normalized() self.hit.world_normal = Vec3(*normal) self.hit.entities = [] for collision in self.entries: self.hit.entities.append(next(e for e in scene.entities if e == collision.get_into_node_path().parent)) return self.hit if __name__ == '__main__': from ursina import * app = Ursina() e = Entity(model='quad', color=color.orange, position=(0,0,1), scale=1.5, rotation=(0,0,45), texture='brick') '''example of inheriting Entity''' class Player(Entity): def __init__(self, **kwargs): super().__init__() self.model='cube' self.color = color.red self.scale_y = 2 for key, value in kwargs.items(): setattr(self, key, value) # input and update functions gets automatically called by the engine def input(self, key): if key == 'space': # self.color = self.color.inverse() self.animate_x(2, duration=1) def update(self): self.x += held_keys['d'] * time.dt * 10 self.x -= held_keys['a'] * time.dt * 10 player = Player(x=-1) # test e = Entity(model='cube') # e.animate_x(3, duration=2, delay=.5, loop=True) # e.animate_position(Vec3(1,1,1), duration=1, loop=True) # e.animate_rotation(Vec3(45,45,45)) # e.animate_scale(2, duration=1, curve=curve.out_expo_boomerang, loop=True) # e.animate_color(color.green, loop=True) # e.shake() # e.fade_out(delay=.5) # e.fade_in(delay=2.5) e.blink(color.red, duration=1, curve=curve.linear_boomerang, loop=True) app.run()
''' Copyright (C) 2021 CG Cookie http://cgcookie.com hello@cgcookie.com Created by Jonathan Denning, Jonathan Williamson, and Patrick Moore This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import math import time from ..rftool import RFTool from ..rfwidgets.rfwidget_default import RFWidget_Default_Factory from ..rfwidgets.rfwidget_brushfalloff import RFWidget_BrushFalloff_Factory from ...addon_common.common.maths import ( Vec, Vec2D, Point, Point2D, Direction, Accel2D, Color, closest_point_segment, ) from ...addon_common.common.fsm import FSM from ...addon_common.common.boundvar import BoundBool, BoundInt, BoundFloat, BoundString from ...addon_common.common.profiler import profiler from ...addon_common.common.utils import iter_pairs, delay_exec from ...config.options import options, themes class Relax(RFTool): name = 'Relax' description = 'Relax the vertex positions to smooth out topology' icon = 'relax-icon.png' help = 'relax.md' shortcut = 'relax tool' quick_shortcut = 'relax quick' statusbar = '{{brush}} Relax\t{{brush alt}} Relax selection\t{{brush radius}} Brush size\t{{brush strength}} Brush strength\t{{brush falloff}} Brush falloff' ui_config = 'relax_options.html' RFWidget_Default = RFWidget_Default_Factory.create('Relax default') RFWidget_BrushFalloff = RFWidget_BrushFalloff_Factory.create( 'Relax brush', BoundInt('''options['relax radius']''', min_value=1), BoundFloat('''options['relax falloff']''', min_value=0.00, max_value=100.0), BoundFloat('''options['relax strength']''', min_value=0.01, max_value=1.0), fill_color=themes['relax'], ) @RFTool.on_init def init(self): self.rfwidgets = { 'default': self.RFWidget_Default(self), 'brushstroke': self.RFWidget_BrushFalloff(self), } self.rfwidget = None def reset_algorithm_options(self): options.reset(keys=[ 'relax steps', 'relax force multiplier', 'relax edge length', 'relax face radius', 'relax face sides', 'relax face angles', 'relax correct flipped faces', 'relax straight edges', ]) def disable_all_options(self): for key in [ 'relax edge length', 'relax face radius', 'relax face sides', 'relax face angles', 'relax correct flipped faces', 'relax straight edges', ]: options[key] = False def reset_current_brush(self): options.reset(keys={'relax radius', 'relax falloff', 'relax strength'}) self.document.body.getElementById(f'relax-current-radius').dirty(cause='copied preset to current brush') self.document.body.getElementById(f'relax-current-strength').dirty(cause='copied preset to current brush') self.document.body.getElementById(f'relax-current-falloff').dirty(cause='copied preset to current brush') def update_preset_name(self, n): name = options[f'relax preset {n} name'] self.document.body.getElementById(f'relax-preset-{n}-summary').innerText = f'Preset: {name}' def copy_current_to_preset(self, n): options[f'relax preset {n} radius'] = options['relax radius'] options[f'relax preset {n} strength'] = options['relax strength'] options[f'relax preset {n} falloff'] = options['relax falloff'] self.document.body.getElementById(f'relax-preset-{n}-radius').dirty(cause='copied current brush to preset') self.document.body.getElementById(f'relax-preset-{n}-strength').dirty(cause='copied current brush to preset') self.document.body.getElementById(f'relax-preset-{n}-falloff').dirty(cause='copied current brush to preset') def copy_preset_to_current(self, n): options['relax radius'] = options[f'relax preset {n} radius'] options['relax strength'] = options[f'relax preset {n} strength'] options['relax falloff'] = options[f'relax preset {n} falloff'] self.document.body.getElementById(f'relax-current-radius').dirty(cause='copied preset to current brush') self.document.body.getElementById(f'relax-current-strength').dirty(cause='copied preset to current brush') self.document.body.getElementById(f'relax-current-falloff').dirty(cause='copied preset to current brush') @RFTool.on_ui_setup def ui(self): self.update_preset_name(1) self.update_preset_name(2) self.update_preset_name(3) self.update_preset_name(4) @RFTool.on_reset def reset(self): self.sel_only = False @FSM.on_state('main') def main(self): if self.actions.using_onlymods(['brush', 'brush alt', 'brush radius', 'brush falloff', 'brush strength']): self.rfwidget = self.rfwidgets['brushstroke'] else: self.rfwidget = self.rfwidgets['default'] if self.rfcontext.actions.pressed(['brush', 'brush alt'], unpress=False): self.sel_only = self.rfcontext.actions.using('brush alt') self.rfcontext.actions.unpress() self.rfcontext.undo_push('relax') return 'relax' if self.rfcontext.actions.pressed('pie menu alt0', unpress=False): def callback(option): if option is None: return self.copy_preset_to_current(option) self.rfcontext.show_pie_menu([ (f'Preset: {options['relax preset 1 name']}', 1), (f'Preset: {options['relax preset 2 name']}', 2), (f'Preset: {options['relax preset 3 name']}', 3), (f'Preset: {options['relax preset 4 name']}', 4), ], callback) return # if self.rfcontext.actions.pressed('select single'): # self.rfcontext.undo_push('select') # self.rfcontext.deselect_all() # return 'select' # if self.rfcontext.actions.pressed('select single add'): # face,_ = self.rfcontext.accel_nearest2D_face(max_dist=10) # if not face: return # if face.select: # self.mousedown = self.rfcontext.actions.mouse # return 'selectadd/deselect' # return 'select' # if self.rfcontext.actions.pressed({'select smart', 'select smart add'}, unpress=False): # if self.rfcontext.actions.pressed('select smart'): # self.rfcontext.deselect_all() # self.rfcontext.actions.unpress() # edge,_ = self.rfcontext.accel_nearest2D_edge(max_dist=10) # if not edge: return # faces = set() # walk = {edge} # touched = set() # while walk: # edge = walk.pop() # if edge in touched: continue # touched.add(edge) # nfaces = set(f for f in edge.link_faces if f not in faces and len(f.edges) == 4) # walk |= {f.opposite_edge(edge) for f in nfaces} # faces |= nfaces # self.rfcontext.select(faces, only=False) # return # @FSM.on_state('selectadd/deselect') # def selectadd_deselect(self): # if not self.rfcontext.actions.using(['select single','select single add']): # self.rfcontext.undo_push('deselect') # face,_ = self.rfcontext.accel_nearest2D_face() # if face and face.select: self.rfcontext.deselect(face) # return 'main' # delta = Vec2D(self.rfcontext.actions.mouse - self.mousedown) # if delta.length > self.drawing.scale(5): # self.rfcontext.undo_push('select add') # return 'select' # @FSM.on_state('select') # def select(self): # if not self.rfcontext.actions.using(['select single','select single add']): # return 'main' # bmf,_ = self.rfcontext.accel_nearest2D_face(max_dist=10) # if not bmf or bmf.select: return # self.rfcontext.select(bmf, supparts=False, only=False) @FSM.on_state('relax', 'enter') def relax_enter(self): self._time = time.time() self._timer = self.actions.start_timer(120) opt_mask_boundary = options['relax mask boundary'] opt_mask_symmetry = options['relax mask symmetry'] opt_mask_occluded = options['relax mask occluded'] opt_mask_selected = options['relax mask selected'] opt_steps = options['relax steps'] opt_edge_length = options['relax edge length'] opt_face_radius = options['relax face radius'] opt_face_sides = options['relax face sides'] opt_face_angles = options['relax face angles'] opt_correct_flipped = options['relax correct flipped faces'] opt_straight_edges = options['relax straight edges'] opt_mult = options['relax force multiplier'] is_visible = lambda bmv: self.rfcontext.is_visible(bmv.co, bmv.normal, occlusion_test_override=True) self._bmverts = [] self._boundary = [] for bmv in self.rfcontext.iter_verts(): if self.sel_only and not bmv.select: continue if opt_mask_boundary == 'exclude' and bmv.is_on_boundary(): continue if opt_mask_symmetry == 'exclude' and bmv.is_on_symmetry_plane(): continue if opt_mask_occluded == 'exclude' and not is_visible(bmv): continue if opt_mask_selected == 'exclude' and bmv.select: continue if opt_mask_selected == 'only' and not bmv.select: continue self._bmverts.append(bmv) if opt_mask_boundary == 'slide': # find all boundary edges self._boundary = [(bme.verts[0].co, bme.verts[1].co) for bme in self.rfcontext.iter_edges() if not bme.is_manifold] # print(f'Relaxing max of {len(self._bmverts)} bmverts') self.rfcontext.split_target_visualization(verts=self._bmverts) @FSM.on_state('relax', 'exit') def relax_exit(self): self.rfcontext.update_verts_faces(self._bmverts) self.rfcontext.clear_split_target_visualization() self._timer.done() @FSM.on_state('relax') def relax(self): st = time.time() if self.rfcontext.actions.released(['brush','brush alt']): return 'main' if self.rfcontext.actions.pressed('cancel'): self.rfcontext.undo_cancel() return 'main' if not self.rfcontext.actions.timer: return hit_pos = self.rfcontext.actions.hit_pos if not hit_pos: return # collect data for smoothing radius = self.rfwidgets['brushstroke'].get_scaled_radius() nearest = self.rfcontext.nearest_verts_point(hit_pos, radius, bmverts=self._bmverts) verts,edges,faces,vert_strength = set(),set(),set(),dict() for bmv,d in nearest: verts.add(bmv) edges.update(bmv.link_edges) faces.update(bmv.link_faces) vert_strength[bmv] = self.rfwidgets['brushstroke'].get_strength_dist(d) / radius # self.rfcontext.select(verts) if not verts or not edges: return vert_strength = vert_strength or {} # gather options opt_mask_boundary = options['relax mask boundary'] opt_mask_symmetry = options['relax mask symmetry'] # opt_mask_occluded = options['relax mask hidden'] # opt_mask_selected = options['relax mask selected'] opt_steps = options['relax steps'] opt_edge_length = options['relax edge length'] opt_face_radius = options['relax face radius'] opt_face_sides = options['relax face sides'] opt_face_angles = options['relax face angles'] opt_correct_flipped = options['relax correct flipped faces'] opt_straight_edges = options['relax straight edges'] opt_mult = options['relax force multiplier'] cur_time = time.time() time_delta = cur_time - self._time self._time = cur_time strength = (5.0 / opt_steps) * self.rfwidgets['brushstroke'].strength * time_delta radius = self.rfwidgets['brushstroke'].get_scaled_radius() # capture all verts involved in relaxing chk_verts = set(verts) chk_verts.update(self.rfcontext.get_edges_verts(edges)) chk_verts.update(self.rfcontext.get_faces_verts(faces)) chk_edges = self.rfcontext.get_verts_link_edges(chk_verts) chk_faces = self.rfcontext.get_verts_link_faces(chk_verts) displace = {} def reset_forces(): nonlocal displace displace.clear() def add_force(bmv, f): nonlocal displace, verts, vert_strength if bmv not in verts or bmv not in vert_strength: return cur = displace[bmv] if bmv in displace else Vec((0,0,0)) displace[bmv] = cur + f def relax_2d(): pass def relax_3d(): reset_forces() # compute average edge length avg_edge_len = sum(bme.calc_length() for bme in edges) / len(edges) # push edges closer to average edge length if opt_edge_length: for bme in chk_edges: if bme not in edges: continue bmv0,bmv1 = bme.verts vec = bme.vector() edge_len = vec.length f = vec * (0.1 * (avg_edge_len - edge_len) * strength) #/ edge_len add_force(bmv0, -f) add_force(bmv1, +f) # push verts if neighboring faces seem flipped (still WiP!) if opt_correct_flipped: bmf_flipped = { bmf for bmf in chk_faces if bmf.is_flipped() } for bmf in bmf_flipped: # find a non-flipped neighboring face for bme in bmf.edges: bmfs = set(bme.link_faces) bmfs.discard(bmf) if len(bmfs) != 1: continue bmf_other = next(iter(bmfs)) if bmf_other not in chk_faces: continue if bmf_other in bmf_flipped: continue # pull edge toward bmf_other center bmf_other_center = bmf_other.center() bme_center = bme.calc_center() vec = bmf_other_center - bme_center bmv0,bmv1 = bme.verts add_force(bmv0, vec * strength * 5) add_force(bmv1, vec * strength * 5) # push verts to straighten edges (still WiP!) if opt_straight_edges: for bmv in chk_verts: if bmv.is_boundary: continue bmes = bmv.link_edges #if len(bmes) != 4: continue center = Point.average(bme.other_vert(bmv).co for bme in bmes) add_force(bmv, (center - bmv.co) * 0.1) # attempt to "square" up the faces for bmf in chk_faces: if bmf not in faces: continue bmvs = bmf.verts cnt = len(bmvs) ctr = Point.average(bmv.co for bmv in bmvs) rels = [bmv.co - ctr for bmv in bmvs] # push verts toward average dist from verts to face center if opt_face_radius: avg_rel_len = sum(rel.length for rel in rels) / cnt for rel, bmv in zip(rels, bmvs): rel_len = rel.length f = rel * ((avg_rel_len - rel_len) * strength * 2) #/ rel_len add_force(bmv, f) # push verts toward equal edge lengths if opt_face_sides: avg_face_edge_len = sum(bme.length for bme in bmf.edges) / cnt for bme in bmf.edges: bmv0, bmv1 = bme.verts vec = bme.vector() edge_len = vec.length f = vec * ((avg_face_edge_len - edge_len) * strength) / edge_len add_force(bmv0, f * -0.5) add_force(bmv1, f * 0.5) # push verts toward equal spread if opt_face_angles: avg_angle = 2.0 * math.pi / cnt for i0 in range(cnt): i1 = (i0 + 1) % cnt rel0,bmv0 = rels[i0],bmvs[i0] rel1,bmv1 = rels[i1],bmvs[i1] if rel0.length < 0.00001 or rel1.length < 0.00001: continue vec = bmv1.co - bmv0.co vec_len = vec.length fvec0 = rel0.cross(vec).cross(rel0).normalize() fvec1 = rel1.cross(rel1.cross(vec)).normalize() angle = rel0.angle(rel1) f_mag = (0.05 * (avg_angle - angle) * strength) / cnt #/ vec_len add_force(bmv0, fvec0 * -f_mag) add_force(bmv1, fvec1 * -f_mag) # perform smoothing for step in range(opt_steps): if options['relax algorithm'] == '3D': relax_3d() elif options['relax algorithm'] == '2D': relax_2d() if len(displace) <= 1: continue # compute max displacement length displace_max = max(displace[bmv].length * (opt_mult * vert_strength[bmv]) for bmv in displace) if displace_max > radius * 0.125: # limit the displace_max mult = radius * 0.125 / displace_max else: mult = 1.0 # update for bmv in displace: co = bmv.co + displace[bmv] * (opt_mult * vert_strength[bmv]) * mult if opt_mask_symmetry == 'maintain' and bmv.is_on_symmetry_plane(): snap_to_symmetry = self.rfcontext.symmetry_planes_for_point(bmv.co) co = self.rfcontext.snap_to_symmetry(co, snap_to_symmetry) if opt_mask_boundary == 'slide' and bmv.is_on_boundary(): p, d = None, None for (v0, v1) in self._boundary: p_ = closest_point_segment(co, v0, v1) d_ = (p_ - co).length if p is None or d_ < d: p, d = p_, d_ if p is not None: co = p bmv.co = co self.rfcontext.snap_vert(bmv) self.rfcontext.update_verts_faces(displace) # print(f'relaxed {len(verts)} ({len(chk_verts)}) in {time.time() - st} with {strength}') self.rfcontext.dirty()
''' Copyright (C) 2021 CG Cookie http://cgcookie.com hello@cgcookie.com Created by Jonathan Denning, Jonathan Williamson, and Patrick Moore This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import math import time from ..rftool import RFTool from ..rfwidgets.rfwidget_default import RFWidget_Default_Factory from ..rfwidgets.rfwidget_brushfalloff import RFWidget_BrushFalloff_Factory from ...addon_common.common.maths import ( Vec, Vec2D, Point, Point2D, Direction, Accel2D, Color, closest_point_segment, ) from ...addon_common.common.fsm import FSM from ...addon_common.common.boundvar import BoundBool, BoundInt, BoundFloat, BoundString from ...addon_common.common.profiler import profiler from ...addon_common.common.utils import iter_pairs, delay_exec from ...config.options import options, themes class Relax(RFTool): name = 'Relax' description = 'Relax the vertex positions to smooth out topology' icon = 'relax-icon.png' help = 'relax.md' shortcut = 'relax tool' quick_shortcut = 'relax quick' statusbar = '{{brush}} Relax\t{{brush alt}} Relax selection\t{{brush radius}} Brush size\t{{brush strength}} Brush strength\t{{brush falloff}} Brush falloff' ui_config = 'relax_options.html' RFWidget_Default = RFWidget_Default_Factory.create('Relax default') RFWidget_BrushFalloff = RFWidget_BrushFalloff_Factory.create( 'Relax brush', BoundInt('''options['relax radius']''', min_value=1), BoundFloat('''options['relax falloff']''', min_value=0.00, max_value=100.0), BoundFloat('''options['relax strength']''', min_value=0.01, max_value=1.0), fill_color=themes['relax'], ) @RFTool.on_init def init(self): self.rfwidgets = { 'default': self.RFWidget_Default(self), 'brushstroke': self.RFWidget_BrushFalloff(self), } self.rfwidget = None def reset_algorithm_options(self): options.reset(keys=[ 'relax steps', 'relax force multiplier', 'relax edge length', 'relax face radius', 'relax face sides', 'relax face angles', 'relax correct flipped faces', 'relax straight edges', ]) def disable_all_options(self): for key in [ 'relax edge length', 'relax face radius', 'relax face sides', 'relax face angles', 'relax correct flipped faces', 'relax straight edges', ]: options[key] = False def reset_current_brush(self): options.reset(keys={'relax radius', 'relax falloff', 'relax strength'}) self.document.body.getElementById(f'relax-current-radius').dirty(cause='copied preset to current brush') self.document.body.getElementById(f'relax-current-strength').dirty(cause='copied preset to current brush') self.document.body.getElementById(f'relax-current-falloff').dirty(cause='copied preset to current brush') def update_preset_name(self, n): name = options[f'relax preset {n} name'] self.document.body.getElementById(f'relax-preset-{n}-summary').innerText = f'Preset: {name}' def copy_current_to_preset(self, n): options[f'relax preset {n} radius'] = options['relax radius'] options[f'relax preset {n} strength'] = options['relax strength'] options[f'relax preset {n} falloff'] = options['relax falloff'] self.document.body.getElementById(f'relax-preset-{n}-radius').dirty(cause='copied current brush to preset') self.document.body.getElementById(f'relax-preset-{n}-strength').dirty(cause='copied current brush to preset') self.document.body.getElementById(f'relax-preset-{n}-falloff').dirty(cause='copied current brush to preset') def copy_preset_to_current(self, n): options['relax radius'] = options[f'relax preset {n} radius'] options['relax strength'] = options[f'relax preset {n} strength'] options['relax falloff'] = options[f'relax preset {n} falloff'] self.document.body.getElementById(f'relax-current-radius').dirty(cause='copied preset to current brush') self.document.body.getElementById(f'relax-current-strength').dirty(cause='copied preset to current brush') self.document.body.getElementById(f'relax-current-falloff').dirty(cause='copied preset to current brush') @RFTool.on_ui_setup def ui(self): self.update_preset_name(1) self.update_preset_name(2) self.update_preset_name(3) self.update_preset_name(4) @RFTool.on_reset def reset(self): self.sel_only = False @FSM.on_state('main') def main(self): if self.actions.using_onlymods(['brush', 'brush alt', 'brush radius', 'brush falloff', 'brush strength']): self.rfwidget = self.rfwidgets['brushstroke'] else: self.rfwidget = self.rfwidgets['default'] if self.rfcontext.actions.pressed(['brush', 'brush alt'], unpress=False): self.sel_only = self.rfcontext.actions.using('brush alt') self.rfcontext.actions.unpress() self.rfcontext.undo_push('relax') return 'relax' if self.rfcontext.actions.pressed('pie menu alt0', unpress=False): def callback(option): if option is None: return self.copy_preset_to_current(option) self.rfcontext.show_pie_menu([ (f'Preset: {options["relax preset 1 name"]}', 1), (f'Preset: {options["relax preset 2 name"]}', 2), (f'Preset: {options["relax preset 3 name"]}', 3), (f'Preset: {options["relax preset 4 name"]}', 4), ], callback) return # if self.rfcontext.actions.pressed('select single'): # self.rfcontext.undo_push('select') # self.rfcontext.deselect_all() # return 'select' # if self.rfcontext.actions.pressed('select single add'): # face,_ = self.rfcontext.accel_nearest2D_face(max_dist=10) # if not face: return # if face.select: # self.mousedown = self.rfcontext.actions.mouse # return 'selectadd/deselect' # return 'select' # if self.rfcontext.actions.pressed({'select smart', 'select smart add'}, unpress=False): # if self.rfcontext.actions.pressed('select smart'): # self.rfcontext.deselect_all() # self.rfcontext.actions.unpress() # edge,_ = self.rfcontext.accel_nearest2D_edge(max_dist=10) # if not edge: return # faces = set() # walk = {edge} # touched = set() # while walk: # edge = walk.pop() # if edge in touched: continue # touched.add(edge) # nfaces = set(f for f in edge.link_faces if f not in faces and len(f.edges) == 4) # walk |= {f.opposite_edge(edge) for f in nfaces} # faces |= nfaces # self.rfcontext.select(faces, only=False) # return # @FSM.on_state('selectadd/deselect') # def selectadd_deselect(self): # if not self.rfcontext.actions.using(['select single','select single add']): # self.rfcontext.undo_push('deselect') # face,_ = self.rfcontext.accel_nearest2D_face() # if face and face.select: self.rfcontext.deselect(face) # return 'main' # delta = Vec2D(self.rfcontext.actions.mouse - self.mousedown) # if delta.length > self.drawing.scale(5): # self.rfcontext.undo_push('select add') # return 'select' # @FSM.on_state('select') # def select(self): # if not self.rfcontext.actions.using(['select single','select single add']): # return 'main' # bmf,_ = self.rfcontext.accel_nearest2D_face(max_dist=10) # if not bmf or bmf.select: return # self.rfcontext.select(bmf, supparts=False, only=False) @FSM.on_state('relax', 'enter') def relax_enter(self): self._time = time.time() self._timer = self.actions.start_timer(120) opt_mask_boundary = options['relax mask boundary'] opt_mask_symmetry = options['relax mask symmetry'] opt_mask_occluded = options['relax mask occluded'] opt_mask_selected = options['relax mask selected'] opt_steps = options['relax steps'] opt_edge_length = options['relax edge length'] opt_face_radius = options['relax face radius'] opt_face_sides = options['relax face sides'] opt_face_angles = options['relax face angles'] opt_correct_flipped = options['relax correct flipped faces'] opt_straight_edges = options['relax straight edges'] opt_mult = options['relax force multiplier'] is_visible = lambda bmv: self.rfcontext.is_visible(bmv.co, bmv.normal, occlusion_test_override=True) self._bmverts = [] self._boundary = [] for bmv in self.rfcontext.iter_verts(): if self.sel_only and not bmv.select: continue if opt_mask_boundary == 'exclude' and bmv.is_on_boundary(): continue if opt_mask_symmetry == 'exclude' and bmv.is_on_symmetry_plane(): continue if opt_mask_occluded == 'exclude' and not is_visible(bmv): continue if opt_mask_selected == 'exclude' and bmv.select: continue if opt_mask_selected == 'only' and not bmv.select: continue self._bmverts.append(bmv) if opt_mask_boundary == 'slide': # find all boundary edges self._boundary = [(bme.verts[0].co, bme.verts[1].co) for bme in self.rfcontext.iter_edges() if not bme.is_manifold] # print(f'Relaxing max of {len(self._bmverts)} bmverts') self.rfcontext.split_target_visualization(verts=self._bmverts) @FSM.on_state('relax', 'exit') def relax_exit(self): self.rfcontext.update_verts_faces(self._bmverts) self.rfcontext.clear_split_target_visualization() self._timer.done() @FSM.on_state('relax') def relax(self): st = time.time() if self.rfcontext.actions.released(['brush','brush alt']): return 'main' if self.rfcontext.actions.pressed('cancel'): self.rfcontext.undo_cancel() return 'main' if not self.rfcontext.actions.timer: return hit_pos = self.rfcontext.actions.hit_pos if not hit_pos: return # collect data for smoothing radius = self.rfwidgets['brushstroke'].get_scaled_radius() nearest = self.rfcontext.nearest_verts_point(hit_pos, radius, bmverts=self._bmverts) verts,edges,faces,vert_strength = set(),set(),set(),dict() for bmv,d in nearest: verts.add(bmv) edges.update(bmv.link_edges) faces.update(bmv.link_faces) vert_strength[bmv] = self.rfwidgets['brushstroke'].get_strength_dist(d) / radius # self.rfcontext.select(verts) if not verts or not edges: return vert_strength = vert_strength or {} # gather options opt_mask_boundary = options['relax mask boundary'] opt_mask_symmetry = options['relax mask symmetry'] # opt_mask_occluded = options['relax mask hidden'] # opt_mask_selected = options['relax mask selected'] opt_steps = options['relax steps'] opt_edge_length = options['relax edge length'] opt_face_radius = options['relax face radius'] opt_face_sides = options['relax face sides'] opt_face_angles = options['relax face angles'] opt_correct_flipped = options['relax correct flipped faces'] opt_straight_edges = options['relax straight edges'] opt_mult = options['relax force multiplier'] cur_time = time.time() time_delta = cur_time - self._time self._time = cur_time strength = (5.0 / opt_steps) * self.rfwidgets['brushstroke'].strength * time_delta radius = self.rfwidgets['brushstroke'].get_scaled_radius() # capture all verts involved in relaxing chk_verts = set(verts) chk_verts.update(self.rfcontext.get_edges_verts(edges)) chk_verts.update(self.rfcontext.get_faces_verts(faces)) chk_edges = self.rfcontext.get_verts_link_edges(chk_verts) chk_faces = self.rfcontext.get_verts_link_faces(chk_verts) displace = {} def reset_forces(): nonlocal displace displace.clear() def add_force(bmv, f): nonlocal displace, verts, vert_strength if bmv not in verts or bmv not in vert_strength: return cur = displace[bmv] if bmv in displace else Vec((0,0,0)) displace[bmv] = cur + f def relax_2d(): pass def relax_3d(): reset_forces() # compute average edge length avg_edge_len = sum(bme.calc_length() for bme in edges) / len(edges) # push edges closer to average edge length if opt_edge_length: for bme in chk_edges: if bme not in edges: continue bmv0,bmv1 = bme.verts vec = bme.vector() edge_len = vec.length f = vec * (0.1 * (avg_edge_len - edge_len) * strength) #/ edge_len add_force(bmv0, -f) add_force(bmv1, +f) # push verts if neighboring faces seem flipped (still WiP!) if opt_correct_flipped: bmf_flipped = { bmf for bmf in chk_faces if bmf.is_flipped() } for bmf in bmf_flipped: # find a non-flipped neighboring face for bme in bmf.edges: bmfs = set(bme.link_faces) bmfs.discard(bmf) if len(bmfs) != 1: continue bmf_other = next(iter(bmfs)) if bmf_other not in chk_faces: continue if bmf_other in bmf_flipped: continue # pull edge toward bmf_other center bmf_other_center = bmf_other.center() bme_center = bme.calc_center() vec = bmf_other_center - bme_center bmv0,bmv1 = bme.verts add_force(bmv0, vec * strength * 5) add_force(bmv1, vec * strength * 5) # push verts to straighten edges (still WiP!) if opt_straight_edges: for bmv in chk_verts: if bmv.is_boundary: continue bmes = bmv.link_edges #if len(bmes) != 4: continue center = Point.average(bme.other_vert(bmv).co for bme in bmes) add_force(bmv, (center - bmv.co) * 0.1) # attempt to "square" up the faces for bmf in chk_faces: if bmf not in faces: continue bmvs = bmf.verts cnt = len(bmvs) ctr = Point.average(bmv.co for bmv in bmvs) rels = [bmv.co - ctr for bmv in bmvs] # push verts toward average dist from verts to face center if opt_face_radius: avg_rel_len = sum(rel.length for rel in rels) / cnt for rel, bmv in zip(rels, bmvs): rel_len = rel.length f = rel * ((avg_rel_len - rel_len) * strength * 2) #/ rel_len add_force(bmv, f) # push verts toward equal edge lengths if opt_face_sides: avg_face_edge_len = sum(bme.length for bme in bmf.edges) / cnt for bme in bmf.edges: bmv0, bmv1 = bme.verts vec = bme.vector() edge_len = vec.length f = vec * ((avg_face_edge_len - edge_len) * strength) / edge_len add_force(bmv0, f * -0.5) add_force(bmv1, f * 0.5) # push verts toward equal spread if opt_face_angles: avg_angle = 2.0 * math.pi / cnt for i0 in range(cnt): i1 = (i0 + 1) % cnt rel0,bmv0 = rels[i0],bmvs[i0] rel1,bmv1 = rels[i1],bmvs[i1] if rel0.length < 0.00001 or rel1.length < 0.00001: continue vec = bmv1.co - bmv0.co vec_len = vec.length fvec0 = rel0.cross(vec).cross(rel0).normalize() fvec1 = rel1.cross(rel1.cross(vec)).normalize() angle = rel0.angle(rel1) f_mag = (0.05 * (avg_angle - angle) * strength) / cnt #/ vec_len add_force(bmv0, fvec0 * -f_mag) add_force(bmv1, fvec1 * -f_mag) # perform smoothing for step in range(opt_steps): if options['relax algorithm'] == '3D': relax_3d() elif options['relax algorithm'] == '2D': relax_2d() if len(displace) <= 1: continue # compute max displacement length displace_max = max(displace[bmv].length * (opt_mult * vert_strength[bmv]) for bmv in displace) if displace_max > radius * 0.125: # limit the displace_max mult = radius * 0.125 / displace_max else: mult = 1.0 # update for bmv in displace: co = bmv.co + displace[bmv] * (opt_mult * vert_strength[bmv]) * mult if opt_mask_symmetry == 'maintain' and bmv.is_on_symmetry_plane(): snap_to_symmetry = self.rfcontext.symmetry_planes_for_point(bmv.co) co = self.rfcontext.snap_to_symmetry(co, snap_to_symmetry) if opt_mask_boundary == 'slide' and bmv.is_on_boundary(): p, d = None, None for (v0, v1) in self._boundary: p_ = closest_point_segment(co, v0, v1) d_ = (p_ - co).length if p is None or d_ < d: p, d = p_, d_ if p is not None: co = p bmv.co = co self.rfcontext.snap_vert(bmv) self.rfcontext.update_verts_faces(displace) # print(f'relaxed {len(verts)} ({len(chk_verts)}) in {time.time() - st} with {strength}') self.rfcontext.dirty()
# -*- encoding: utf-8 -*- """ Created by Ênio Viana at 15/05/2021 """ from py_dss_interface.models.Example.ExampleBase import ExampleBase dss = ExampleBase("13").dss # Integer methods print(45 * '=' + ' Integer Methods' + 45 * '=') print(f'dss.dssprogress_pct_progress(): {dss.dssprogress_pct_progress(12.5)}') print(f'dss.dssprogress_show(): {dss.dssprogress_show()}') print(f'dss.dssprogress_close(): {dss.dssprogress_close()}') # String methods print(45 * '=' + ' String Methods ' + 45 * '=') print(f'dss.dssprogress_caption(): {dss.dssprogress_caption('My Caption')}')
# -*- encoding: utf-8 -*- """ Created by Ênio Viana at 15/05/2021 """ from py_dss_interface.models.Example.ExampleBase import ExampleBase dss = ExampleBase("13").dss # Integer methods print(45 * '=' + ' Integer Methods' + 45 * '=') print(f'dss.dssprogress_pct_progress(): {dss.dssprogress_pct_progress(12.5)}') print(f'dss.dssprogress_show(): {dss.dssprogress_show()}') print(f'dss.dssprogress_close(): {dss.dssprogress_close()}') # String methods print(45 * '=' + ' String Methods ' + 45 * '=') print(f'dss.dssprogress_caption(): {dss.dssprogress_caption("My Caption")}')
import re from nonebot import on_command, export, logger from nonebot.typing import T_State from nonebot.adapters.cqhttp.bot import Bot from nonebot.adapters.cqhttp.event import MessageEvent, GroupMessageEvent, PrivateMessageEvent from nonebot.adapters.cqhttp.permission import GROUP, PRIVATE_FRIEND from nonebot.adapters.cqhttp import MessageSegment, Message from omega_miya.utils.Omega_plugin_utils import init_export, init_permission_state from .utils import pic_2_base64, get_saucenao_identify_result, get_ascii2d_identify_result # Custom plugin usage text __plugin_name__ = '识图' __plugin_usage__ = r'''【识图助手】 使用SauceNAO/ascii2d识别各类图片、插画 群组/私聊可用 **Permission** Friend Private Command & Lv.50 or AuthNode **AuthNode** basic **Usage** /识图''' # 声明本插件可配置的权限节点 __plugin_auth_node__ = [ 'basic' ] # Init plugin export init_export(export(), __plugin_name__, __plugin_usage__, __plugin_auth_node__) # 注册事件响应器 search_image = on_command( '识图', aliases={'搜图'}, # 使用run_preprocessor拦截权限管理, 在default_state初始化所需权限 state=init_permission_state( name='search_image', command=True, level=50, auth_node='basic'), permission=GROUP | PRIVATE_FRIEND, priority=20, block=True) # 修改默认参数处理 @search_image.args_parser async def parse(bot: Bot, event: MessageEvent, state: T_State): args = str(event.get_message()).strip().split() if not args: await search_image.reject('你似乎没有发送有效的消息呢QAQ, 请重新发送:') state[state["_current_key"]] = args[0] if state[state["_current_key"]] == '取消': await search_image.finish('操作已取消') @search_image.handle() async def handle_first_receive(bot: Bot, event: MessageEvent, state: T_State): if event.reply: img_url = str(event.reply.message).strip() if re.match(r'^(\[CQ:image,file=[abcdef\d]{32}\.image,url=.+?])$', img_url): state['image_url'] = img_url args = str(event.get_plaintext()).strip().lower().split() if args: await search_image.finish('该命令不支持参数QAQ') @search_image.got('image_url', prompt='请发送你想要识别的图片:') async def handle_draw(bot: Bot, event: MessageEvent, state: T_State): if isinstance(event, GroupMessageEvent): group_id = event.group_id else: group_id = 'Private event' image_url = state['image_url'] if not re.match(r'^(\[CQ:image,file=[abcdef\d]{32}\.image,url=.+?])$', image_url): await search_image.reject('你发送的似乎不是图片呢, 请重新发送, 取消命令请发送【取消】:') # 提取图片url image_url = re.sub(r'^(\[CQ:image,file=[abcdef\d]{32}\.image,url=)', '', image_url) image_url = re.sub(r'(])$', '', image_url) try: has_error = False await search_image.send('获取识别结果中, 请稍后~') identify_result = [] identify_saucenao_result = await get_saucenao_identify_result(url=image_url) if identify_saucenao_result.success(): identify_result.extend(identify_saucenao_result.result) else: has_error = True # saucenao 没有结果时再使用 ascii2d 进行搜索 if not identify_result: identify_ascii2d_result = await get_ascii2d_identify_result(url=image_url) # 合并搜索结果 if identify_ascii2d_result.success(): identify_result.extend(identify_ascii2d_result.result) else: has_error = True if identify_result: for item in identify_result: try: if type(item['ext_urls']) == list: ext_urls = '' for urls in item['ext_urls']: ext_urls += f'{urls}\n' ext_urls = ext_urls.strip() else: ext_urls = item['ext_urls'] ext_urls = ext_urls.strip() img_b64 = await pic_2_base64(item['thumbnail']) if not img_b64.success(): msg = f"识别结果: {item["index_name"]}\n\n相似度: {item["similarity"]}\n资源链接: {ext_urls}" await search_image.send(msg) else: img_seg = MessageSegment.image(img_b64.result) msg = f"识别结果: {item["index_name"]}\n\n相似度: {item["similarity"]}\n资源链接: {ext_urls}\n{img_seg}" await search_image.send(Message(msg)) except Exception as e: logger.warning(f'处理和发送识别结果时发生了错误: {repr(e)}') continue logger.info(f"{group_id} / {event.user_id} 使用searchimage成功搜索了一张图片") return elif not identify_result and has_error: await search_image.send('识图过程中获取信息失败QAQ, 请重试一下吧') logger.info(f"{group_id} / {event.user_id} 使用了searchimage, 但在识图过程中获取信息失败") return else: await search_image.send('没有找到相似度足够高的图片QAQ') logger.info(f"{group_id} / {event.user_id} 使用了searchimage, 但没有找到相似的图片") return except Exception as e: await search_image.send('识图失败, 发生了意外的错误QAQ, 请稍后重试') logger.error(f"{group_id} / {event.user_id} 使用命令searchimage时发生了错误: {repr(e)}") return
import re from nonebot import on_command, export, logger from nonebot.typing import T_State from nonebot.adapters.cqhttp.bot import Bot from nonebot.adapters.cqhttp.event import MessageEvent, GroupMessageEvent, PrivateMessageEvent from nonebot.adapters.cqhttp.permission import GROUP, PRIVATE_FRIEND from nonebot.adapters.cqhttp import MessageSegment, Message from omega_miya.utils.Omega_plugin_utils import init_export, init_permission_state from .utils import pic_2_base64, get_saucenao_identify_result, get_ascii2d_identify_result # Custom plugin usage text __plugin_name__ = '识图' __plugin_usage__ = r'''【识图助手】 使用SauceNAO/ascii2d识别各类图片、插画 群组/私聊可用 **Permission** Friend Private Command & Lv.50 or AuthNode **AuthNode** basic **Usage** /识图''' # 声明本插件可配置的权限节点 __plugin_auth_node__ = [ 'basic' ] # Init plugin export init_export(export(), __plugin_name__, __plugin_usage__, __plugin_auth_node__) # 注册事件响应器 search_image = on_command( '识图', aliases={'搜图'}, # 使用run_preprocessor拦截权限管理, 在default_state初始化所需权限 state=init_permission_state( name='search_image', command=True, level=50, auth_node='basic'), permission=GROUP | PRIVATE_FRIEND, priority=20, block=True) # 修改默认参数处理 @search_image.args_parser async def parse(bot: Bot, event: MessageEvent, state: T_State): args = str(event.get_message()).strip().split() if not args: await search_image.reject('你似乎没有发送有效的消息呢QAQ, 请重新发送:') state[state["_current_key"]] = args[0] if state[state["_current_key"]] == '取消': await search_image.finish('操作已取消') @search_image.handle() async def handle_first_receive(bot: Bot, event: MessageEvent, state: T_State): if event.reply: img_url = str(event.reply.message).strip() if re.match(r'^(\[CQ:image,file=[abcdef\d]{32}\.image,url=.+?])$', img_url): state['image_url'] = img_url args = str(event.get_plaintext()).strip().lower().split() if args: await search_image.finish('该命令不支持参数QAQ') @search_image.got('image_url', prompt='请发送你想要识别的图片:') async def handle_draw(bot: Bot, event: MessageEvent, state: T_State): if isinstance(event, GroupMessageEvent): group_id = event.group_id else: group_id = 'Private event' image_url = state['image_url'] if not re.match(r'^(\[CQ:image,file=[abcdef\d]{32}\.image,url=.+?])$', image_url): await search_image.reject('你发送的似乎不是图片呢, 请重新发送, 取消命令请发送【取消】:') # 提取图片url image_url = re.sub(r'^(\[CQ:image,file=[abcdef\d]{32}\.image,url=)', '', image_url) image_url = re.sub(r'(])$', '', image_url) try: has_error = False await search_image.send('获取识别结果中, 请稍后~') identify_result = [] identify_saucenao_result = await get_saucenao_identify_result(url=image_url) if identify_saucenao_result.success(): identify_result.extend(identify_saucenao_result.result) else: has_error = True # saucenao 没有结果时再使用 ascii2d 进行搜索 if not identify_result: identify_ascii2d_result = await get_ascii2d_identify_result(url=image_url) # 合并搜索结果 if identify_ascii2d_result.success(): identify_result.extend(identify_ascii2d_result.result) else: has_error = True if identify_result: for item in identify_result: try: if type(item['ext_urls']) == list: ext_urls = '' for urls in item['ext_urls']: ext_urls += f'{urls}\n' ext_urls = ext_urls.strip() else: ext_urls = item['ext_urls'] ext_urls = ext_urls.strip() img_b64 = await pic_2_base64(item['thumbnail']) if not img_b64.success(): msg = f"识别结果: {item['index_name']}\n\n相似度: {item['similarity']}\n资源链接: {ext_urls}" await search_image.send(msg) else: img_seg = MessageSegment.image(img_b64.result) msg = f"识别结果: {item['index_name']}\n\n相似度: {item['similarity']}\n资源链接: {ext_urls}\n{img_seg}" await search_image.send(Message(msg)) except Exception as e: logger.warning(f'处理和发送识别结果时发生了错误: {repr(e)}') continue logger.info(f"{group_id} / {event.user_id} 使用searchimage成功搜索了一张图片") return elif not identify_result and has_error: await search_image.send('识图过程中获取信息失败QAQ, 请重试一下吧') logger.info(f"{group_id} / {event.user_id} 使用了searchimage, 但在识图过程中获取信息失败") return else: await search_image.send('没有找到相似度足够高的图片QAQ') logger.info(f"{group_id} / {event.user_id} 使用了searchimage, 但没有找到相似的图片") return except Exception as e: await search_image.send('识图失败, 发生了意外的错误QAQ, 请稍后重试') logger.error(f"{group_id} / {event.user_id} 使用命令searchimage时发生了错误: {repr(e)}") return
# document_grid.py # # MIT License # # Copyright (c) 2020-2021 Andrey Maksimov <meamka@ya.ru> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os from datetime import datetime from gettext import gettext as _ from typing import Optional from urllib.parse import urlparse, unquote_plus import cairo from gi.repository import Gtk, GObject, Gdk from gi.repository.GdkPixbuf import Pixbuf, Colorspace from norka.define import TARGET_ENTRY_TEXT, TARGET_ENTRY_REORDER, RESOURCE_PREFIX from norka.models.document import Document from norka.models.folder import Folder from norka.services.logger import Logger from norka.services.settings import Settings from norka.services.storage import Storage from norka.utils import find_child from norka.widgets.folder_create_dialog import FolderCreateDialog class DocumentGrid(Gtk.Grid): __gtype_name__ = 'DocumentGrid' __gsignals__ = { 'path-changed': (GObject.SIGNAL_RUN_FIRST, None, (str, str)), 'document-create': (GObject.SIGNAL_RUN_FIRST, None, (int,)), 'document-import': (GObject.SIGNAL_RUN_FIRST, None, (str,)), 'rename-folder': (GObject.SIGNAL_RUN_FIRST, None, (str,)), } def __init__(self, settings: Settings, storage: Storage): super().__init__() self.last_selected_path = None self.settings = settings self.storage = storage self.settings.connect("changed", self.on_settings_changed) self.model = Gtk.ListStore(Pixbuf, str, str, int, str) self.show_archived = False self.selected_path = None # self.selected_document = None # Store current virtual files path. self.current_path = '/' self.view = Gtk.IconView() self.view.set_model(self.model) self.view.set_pixbuf_column(0) self.view.set_text_column(1) self.view.set_tooltip_column(4) self.view.set_item_width(80) self.view.set_activate_on_single_click(True) self.view.set_selection_mode(Gtk.SelectionMode.SINGLE) self.view.connect('show', self.reload_items) self.view.connect('button-press-event', self.on_button_pressed) # Enable drag-drop import_dnd_target = Gtk.TargetEntry.new('text/plain', Gtk.TargetFlags.OTHER_APP, TARGET_ENTRY_TEXT) reorder_dnd_target = Gtk.TargetEntry.new('reorder', Gtk.TargetFlags.SAME_APP, TARGET_ENTRY_REORDER) self.view.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK, [import_dnd_target, reorder_dnd_target], Gdk.DragAction.MOVE) self.view.enable_model_drag_dest([import_dnd_target, reorder_dnd_target], Gdk.DragAction.COPY | Gdk.DragAction.COPY) self.view.connect("drag-begin", self.on_drag_begin) self.view.connect("drag-motion", self.on_drag_motion) self.view.connect("drag-leave", self.on_drag_leave) self.view.connect("drag-end", self.on_drag_end) # self.view.connect("drag-data-get", self.on_drag_data_get) self.view.connect('drag-data-received', self.on_drag_data_received) scrolled = Gtk.ScrolledWindow() scrolled.set_hexpand(True) scrolled.set_vexpand(True) scrolled.add(self.view) self.add(scrolled) @property def current_folder_path(self): current_folder_path = self.current_path or '/' if current_folder_path != '/' and current_folder_path.endswith('/'): current_folder_path = current_folder_path[:-1] return current_folder_path @property def is_folder_selected(self) -> bool: if self.selected_path is None: return False model_iter = self.model.get_iter(self.selected_path) doc_id = self.model.get_value(model_iter, 3) return doc_id == -1 @property def selected_document_id(self) -> Optional[int]: """Returns Id of the selected document or `None` """ if self.is_folder_selected: return None model_iter = self.model.get_iter(self.selected_path) return self.model.get_value(model_iter, 3) @property def selected_document(self) -> Optional[Document]: """Returns selected :model:`Document` or `None` """ Logger.debug('DocumentGrid.selected_document') if self.is_folder_selected: return None if self.selected_path is None: return None model_iter = self.model.get_iter(self.selected_path) doc_id = self.model.get_value(model_iter, 3) return self.storage.get(doc_id) @property def selected_folder(self) -> Optional[Folder]: """Returns selected :model:`Folder` or `None` if :model:`Document` selected. """ if not self.is_folder_selected: return None model_iter = self.model.get_iter(self.selected_path) return Folder( title=self.model.get_value(model_iter, 1), path=self.model.get_value(model_iter, 2) ) def on_settings_changed(self, settings, key): if key == "sort-desc": self.reload_items(self) def reload_items(self, sender: Gtk.Widget = None, path: str = None) -> None: order_desc = self.settings.get_boolean('sort-desc') self.model.clear() _old_path = self.current_path self.current_path = path or self.current_folder_path # For non-root path add virtual "upper" folder. if self.current_folder_path != '/': # /folder 1/folder 2 -> /folder 1 folder_path = self.current_folder_path[:self.current_folder_path[:-1].rfind('/')] or '/' folder_open_icon = Pixbuf.new_from_resource(RESOURCE_PREFIX + '/icons/folder-open.svg') self.create_folder_model(title='..', path=folder_path, icon=folder_open_icon, tooltip=_('Go to the upper folder')) # Emit "path-changed" signal. self.emit('path-changed', _old_path, self.current_path) # Load folders first Logger.info(f"reload_items: {self.current_folder_path}") for folder in self.storage.get_folders(path=self.current_folder_path): self.create_folder_model(title=folder.title, path=folder.path) # Then load documents, not before foldes. for document in self.storage.all(path=self.current_folder_path, with_archived=self.show_archived, desc=order_desc): # icon = Gtk.IconTheme.get_default().load_icon('text-x-generic', 64, 0) opacity = 0.2 if document.archived else 1 # generate icon. It needs to stay in cache icon = self.gen_preview(document.content[:200], opacity=opacity) # Generate tooltip tooltip = f"{document.title}" if document.created: created = datetime.strptime(document.created, "%Y-%m-%d %H:%M:%S.%f") tooltip += f"\n<span weight='600' size='smaller' alpha='75%'>" \ + _('Created') + f": {created.strftime("%x")}</span>" if document.modified: modified = datetime.strptime(document.modified, "%Y-%m-%d %H:%M:%S.%f") tooltip += f"\n<span weight='600' size='smaller' alpha='75%'>" \ + _('Modified') + f": {modified.strftime("%x")}</span>" self.model.append([icon, document.title, document.content, document.document_id, tooltip]) if self.selected_path: self.view.select_path(self.selected_path) def create_folder_model(self, title: str, path: str, tooltip: str = None, icon: Pixbuf = None): icon = icon or Pixbuf.new_from_resource(RESOURCE_PREFIX + '/icons/folder.svg') self.model.append([icon, title, path, -1, tooltip or title]) @staticmethod def gen_preview(text, size=9, opacity=1) -> Pixbuf: pix = Pixbuf.new(Colorspace.RGB, True, 8, 60, 80) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, pix.get_width(), pix.get_height()) context = cairo.Context(surface) # Gdk.cairo_set_source_pixbuf(context, pix, 0, 0) # context.paint() # paint the pixbuf # context.select_font_face('sans-serif') context.set_font_size(size) # Document background grad = cairo.LinearGradient(0, 0, 0, pix.get_height()) grad.add_color_stop_rgb(0, 0.95, 0.95, 0.95) grad.add_color_stop_rgb(pix.get_height(), 0.93, 0.93, 0.93) context.set_source(grad) context.paint_with_alpha(opacity) # Document Outline grad = cairo.LinearGradient(0, 0, 0, pix.get_height()) grad.add_color_stop_rgba(0, 1, 1, 1, opacity) grad.add_color_stop_rgba(pix.get_height(), 0.94, 0.94, 0.94, opacity) context.rectangle(1, 1, pix.get_width() - 2, pix.get_height() - 2) context.set_source(grad) context.stroke() # Border context.rectangle(0, 0, pix.get_width(), pix.get_height()) context.set_source_rgba(0.9, 0.9, 0.9, opacity) context.stroke() # add the text for num, line in enumerate(text.split('\n'), 1): context.set_source_rgba(0.2, 0.2, 0.24, opacity) # Fix to remove \r if it exists if line.startswith('\r'): line = line[1:] if num == 1: context.select_font_face('sans-serif', cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) else: context.select_font_face('monospace', cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) context.move_to(4, 4 + size * num) context.show_text(line) # get the resulting pixbuf surface = context.get_target() return Gdk.pixbuf_get_from_surface(surface, 0, 0, surface.get_width(), surface.get_height()) def on_button_pressed(self, widget: Gtk.Widget, event: Gdk.EventButton): """Handle mouse button press event and display context menu if needed. """ self.selected_path = self.view.get_path_at_pos(event.x, event.y) if not self.selected_path: # self.selected_document = None self.view.unselect_all() return True if event.button == Gdk.BUTTON_SECONDARY: self.view.select_path(self.selected_path) origin_item = self.selected_folder if self.is_folder_selected else self.selected_document if isinstance(origin_item, Folder) and origin_item.title == "..": print('System @UP folder. Action declined.') return # self.selected_document = self.storage.get(self.model.get_value( # self.model.get_iter(self.selected_path), 3 # )) found, rect = self.view.get_cell_rect(self.selected_path) builder = Gtk.Builder() builder.add_from_resource(f"{RESOURCE_PREFIX}/ui/documents_grid_context_menu.ui") # Switch between folder's and document's menus if self.is_folder_selected: menu_popover: Gtk.PopoverMenu = builder.get_object('folder-popover-menu') else: menu_popover: Gtk.PopoverMenu = builder.get_object('document-popover-menu') find_child(menu_popover, "archive").set_visible(not self.selected_document.archived) find_child(menu_popover, "unarchive").set_visible(self.selected_document.archived) menu_popover.set_relative_to(self.view) menu_popover.set_pointing_to(rect) menu_popover.popup() return True self.view.unselect_all() def on_drag_begin(self, widget: Gtk.Widget, context: Gdk.DragContext) -> None: self.last_selected_path = self.selected_path def on_drag_motion(self, widget: Gtk.Widget, context: Gdk.DragContext, x: int, y: int, time: int) -> bool: # Change cursor icon based on drop target. # if the user move mouse over the folder - it becomes MOVE action model_path = self.view.get_path_at_pos(x, y) if not model_path: return False model_iter = self.model.get_iter(model_path) item_id = self.model.get_value(model_iter, 3) # Select hover cell, make it interactive for the user self.view.select_path(model_path) # Folder could have an ID, so this condition going to change if item_id == -1: Gdk.drag_status(context, Gdk.DragAction.MOVE, time) # TODO: Change folder icon on hover # self.model.set_value(model_iter, 0, Pixbuf.new_from_resource(RESOURCE_PREFIX + '/icons/folder-open.svg')) else: Gdk.drag_status(context, Gdk.DragAction.COPY, time) return True def on_drag_leave(self, widget: Gtk.Widget, context: Gdk.DragContext, time: int) -> None: # print('on_drag_leave') pass def on_drag_end(self, widget: Gtk.Widget, context: Gdk.DragContext) -> None: # print('on_drag_end') if self.last_selected_path: self.view.select_path(self.last_selected_path) self.last_selected_path = None # Move handler to window class def on_drag_data_received(self, widget: Gtk.Widget, drag_context: Gdk.DragContext, x: int, y: int, data: Gtk.SelectionData, info: int, time: int) -> None: print(f'Drag info: {info}') # Handle normal dnd from other apps with files as a target if info == TARGET_ENTRY_TEXT: uris = data.get_text().split('\n') print(data.get_text()) for uri in uris: # Skip empty items if not uri: continue p = urlparse(unquote_plus(uri)) filename = os.path.abspath(os.path.join(p.netloc, p.path)) self.emit('document-import', filename) # Handle reordering and moving inside Norka's virtual filesystem elif info == TARGET_ENTRY_REORDER: origin_item = self.selected_folder if self.is_folder_selected else self.selected_document dest_path = self.view.get_path_at_pos(x, y) if not dest_path: print("No dest path") return dest_iter = self.model.get_iter(dest_path) dest_item_id = self.model.get_value(dest_iter, 3) if dest_item_id == -1: dest_item = Folder( title=self.model.get_value(dest_iter, 1), path=self.model.get_value(dest_iter, 2) ) else: dest_item = self.storage.get(dest_item_id) # Don't move item to itself :) if origin_item.absolute_path == dest_item.absolute_path: print("Don't move item to itself") return # Create folders when doc dropped onto doc # After creation rename dialog should appear if isinstance(dest_item, Document): folder_id = self.create_folder(f'{origin_item.title} + {dest_item.title}', self.current_folder_path) if folder_id: folder = self.storage.get_folder(folder_id) self.storage.move(origin_item.document_id, folder.absolute_path) self.storage.move(dest_item.document_id, folder.absolute_path) self.reload_items() return # For folders, we have to move folder and its content to destination if isinstance(origin_item, Folder): print(f'Folder "{origin_item.title}": "{origin_item.path}" -> "{dest_item.absolute_path}"') self.storage.move_folder(origin_item, dest_item.absolute_path) self.reload_items() # For regular documents it is easy to move - just update the `path`. else: if self.storage.update(origin_item.document_id, {'path': dest_item.absolute_path}): print(f'Moved {origin_item.title} to {dest_item.absolute_path}') self.reload_items() Gtk.drag_finish(drag_context, True, drag_context.get_selected_action() == Gdk.DragAction.MOVE, time) def create_folder(self, title: str, path: str) -> Optional[int]: dialog = FolderCreateDialog(title) result = dialog.run() folder_path = dialog.folder_title dialog.destroy() if result == Gtk.ResponseType.ACCEPT: print(f'Folder "{folder_path}" created') return self.storage.add_folder(folder_path, path) def on_folder_rename_activated(self, sender: Gtk.Widget, title: str) -> None: sender.destroy() folder = self.document_grid.selected_folder if folder and self.storage.rename_folder(folder, title): self.document_grid.reload_items() def filter_model_by_value(self, model, path, iter): print(f'filter_model_by_value: {model}; {path}; {iter};')
# document_grid.py # # MIT License # # Copyright (c) 2020-2021 Andrey Maksimov <meamka@ya.ru> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os from datetime import datetime from gettext import gettext as _ from typing import Optional from urllib.parse import urlparse, unquote_plus import cairo from gi.repository import Gtk, GObject, Gdk from gi.repository.GdkPixbuf import Pixbuf, Colorspace from norka.define import TARGET_ENTRY_TEXT, TARGET_ENTRY_REORDER, RESOURCE_PREFIX from norka.models.document import Document from norka.models.folder import Folder from norka.services.logger import Logger from norka.services.settings import Settings from norka.services.storage import Storage from norka.utils import find_child from norka.widgets.folder_create_dialog import FolderCreateDialog class DocumentGrid(Gtk.Grid): __gtype_name__ = 'DocumentGrid' __gsignals__ = { 'path-changed': (GObject.SIGNAL_RUN_FIRST, None, (str, str)), 'document-create': (GObject.SIGNAL_RUN_FIRST, None, (int,)), 'document-import': (GObject.SIGNAL_RUN_FIRST, None, (str,)), 'rename-folder': (GObject.SIGNAL_RUN_FIRST, None, (str,)), } def __init__(self, settings: Settings, storage: Storage): super().__init__() self.last_selected_path = None self.settings = settings self.storage = storage self.settings.connect("changed", self.on_settings_changed) self.model = Gtk.ListStore(Pixbuf, str, str, int, str) self.show_archived = False self.selected_path = None # self.selected_document = None # Store current virtual files path. self.current_path = '/' self.view = Gtk.IconView() self.view.set_model(self.model) self.view.set_pixbuf_column(0) self.view.set_text_column(1) self.view.set_tooltip_column(4) self.view.set_item_width(80) self.view.set_activate_on_single_click(True) self.view.set_selection_mode(Gtk.SelectionMode.SINGLE) self.view.connect('show', self.reload_items) self.view.connect('button-press-event', self.on_button_pressed) # Enable drag-drop import_dnd_target = Gtk.TargetEntry.new('text/plain', Gtk.TargetFlags.OTHER_APP, TARGET_ENTRY_TEXT) reorder_dnd_target = Gtk.TargetEntry.new('reorder', Gtk.TargetFlags.SAME_APP, TARGET_ENTRY_REORDER) self.view.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK, [import_dnd_target, reorder_dnd_target], Gdk.DragAction.MOVE) self.view.enable_model_drag_dest([import_dnd_target, reorder_dnd_target], Gdk.DragAction.COPY | Gdk.DragAction.COPY) self.view.connect("drag-begin", self.on_drag_begin) self.view.connect("drag-motion", self.on_drag_motion) self.view.connect("drag-leave", self.on_drag_leave) self.view.connect("drag-end", self.on_drag_end) # self.view.connect("drag-data-get", self.on_drag_data_get) self.view.connect('drag-data-received', self.on_drag_data_received) scrolled = Gtk.ScrolledWindow() scrolled.set_hexpand(True) scrolled.set_vexpand(True) scrolled.add(self.view) self.add(scrolled) @property def current_folder_path(self): current_folder_path = self.current_path or '/' if current_folder_path != '/' and current_folder_path.endswith('/'): current_folder_path = current_folder_path[:-1] return current_folder_path @property def is_folder_selected(self) -> bool: if self.selected_path is None: return False model_iter = self.model.get_iter(self.selected_path) doc_id = self.model.get_value(model_iter, 3) return doc_id == -1 @property def selected_document_id(self) -> Optional[int]: """Returns Id of the selected document or `None` """ if self.is_folder_selected: return None model_iter = self.model.get_iter(self.selected_path) return self.model.get_value(model_iter, 3) @property def selected_document(self) -> Optional[Document]: """Returns selected :model:`Document` or `None` """ Logger.debug('DocumentGrid.selected_document') if self.is_folder_selected: return None if self.selected_path is None: return None model_iter = self.model.get_iter(self.selected_path) doc_id = self.model.get_value(model_iter, 3) return self.storage.get(doc_id) @property def selected_folder(self) -> Optional[Folder]: """Returns selected :model:`Folder` or `None` if :model:`Document` selected. """ if not self.is_folder_selected: return None model_iter = self.model.get_iter(self.selected_path) return Folder( title=self.model.get_value(model_iter, 1), path=self.model.get_value(model_iter, 2) ) def on_settings_changed(self, settings, key): if key == "sort-desc": self.reload_items(self) def reload_items(self, sender: Gtk.Widget = None, path: str = None) -> None: order_desc = self.settings.get_boolean('sort-desc') self.model.clear() _old_path = self.current_path self.current_path = path or self.current_folder_path # For non-root path add virtual "upper" folder. if self.current_folder_path != '/': # /folder 1/folder 2 -> /folder 1 folder_path = self.current_folder_path[:self.current_folder_path[:-1].rfind('/')] or '/' folder_open_icon = Pixbuf.new_from_resource(RESOURCE_PREFIX + '/icons/folder-open.svg') self.create_folder_model(title='..', path=folder_path, icon=folder_open_icon, tooltip=_('Go to the upper folder')) # Emit "path-changed" signal. self.emit('path-changed', _old_path, self.current_path) # Load folders first Logger.info(f"reload_items: {self.current_folder_path}") for folder in self.storage.get_folders(path=self.current_folder_path): self.create_folder_model(title=folder.title, path=folder.path) # Then load documents, not before foldes. for document in self.storage.all(path=self.current_folder_path, with_archived=self.show_archived, desc=order_desc): # icon = Gtk.IconTheme.get_default().load_icon('text-x-generic', 64, 0) opacity = 0.2 if document.archived else 1 # generate icon. It needs to stay in cache icon = self.gen_preview(document.content[:200], opacity=opacity) # Generate tooltip tooltip = f"{document.title}" if document.created: created = datetime.strptime(document.created, "%Y-%m-%d %H:%M:%S.%f") tooltip += f"\n<span weight='600' size='smaller' alpha='75%'>" \ + _('Created') + f": {created.strftime('%x')}</span>" if document.modified: modified = datetime.strptime(document.modified, "%Y-%m-%d %H:%M:%S.%f") tooltip += f"\n<span weight='600' size='smaller' alpha='75%'>" \ + _('Modified') + f": {modified.strftime('%x')}</span>" self.model.append([icon, document.title, document.content, document.document_id, tooltip]) if self.selected_path: self.view.select_path(self.selected_path) def create_folder_model(self, title: str, path: str, tooltip: str = None, icon: Pixbuf = None): icon = icon or Pixbuf.new_from_resource(RESOURCE_PREFIX + '/icons/folder.svg') self.model.append([icon, title, path, -1, tooltip or title]) @staticmethod def gen_preview(text, size=9, opacity=1) -> Pixbuf: pix = Pixbuf.new(Colorspace.RGB, True, 8, 60, 80) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, pix.get_width(), pix.get_height()) context = cairo.Context(surface) # Gdk.cairo_set_source_pixbuf(context, pix, 0, 0) # context.paint() # paint the pixbuf # context.select_font_face('sans-serif') context.set_font_size(size) # Document background grad = cairo.LinearGradient(0, 0, 0, pix.get_height()) grad.add_color_stop_rgb(0, 0.95, 0.95, 0.95) grad.add_color_stop_rgb(pix.get_height(), 0.93, 0.93, 0.93) context.set_source(grad) context.paint_with_alpha(opacity) # Document Outline grad = cairo.LinearGradient(0, 0, 0, pix.get_height()) grad.add_color_stop_rgba(0, 1, 1, 1, opacity) grad.add_color_stop_rgba(pix.get_height(), 0.94, 0.94, 0.94, opacity) context.rectangle(1, 1, pix.get_width() - 2, pix.get_height() - 2) context.set_source(grad) context.stroke() # Border context.rectangle(0, 0, pix.get_width(), pix.get_height()) context.set_source_rgba(0.9, 0.9, 0.9, opacity) context.stroke() # add the text for num, line in enumerate(text.split('\n'), 1): context.set_source_rgba(0.2, 0.2, 0.24, opacity) # Fix to remove \r if it exists if line.startswith('\r'): line = line[1:] if num == 1: context.select_font_face('sans-serif', cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) else: context.select_font_face('monospace', cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) context.move_to(4, 4 + size * num) context.show_text(line) # get the resulting pixbuf surface = context.get_target() return Gdk.pixbuf_get_from_surface(surface, 0, 0, surface.get_width(), surface.get_height()) def on_button_pressed(self, widget: Gtk.Widget, event: Gdk.EventButton): """Handle mouse button press event and display context menu if needed. """ self.selected_path = self.view.get_path_at_pos(event.x, event.y) if not self.selected_path: # self.selected_document = None self.view.unselect_all() return True if event.button == Gdk.BUTTON_SECONDARY: self.view.select_path(self.selected_path) origin_item = self.selected_folder if self.is_folder_selected else self.selected_document if isinstance(origin_item, Folder) and origin_item.title == "..": print('System @UP folder. Action declined.') return # self.selected_document = self.storage.get(self.model.get_value( # self.model.get_iter(self.selected_path), 3 # )) found, rect = self.view.get_cell_rect(self.selected_path) builder = Gtk.Builder() builder.add_from_resource(f"{RESOURCE_PREFIX}/ui/documents_grid_context_menu.ui") # Switch between folder's and document's menus if self.is_folder_selected: menu_popover: Gtk.PopoverMenu = builder.get_object('folder-popover-menu') else: menu_popover: Gtk.PopoverMenu = builder.get_object('document-popover-menu') find_child(menu_popover, "archive").set_visible(not self.selected_document.archived) find_child(menu_popover, "unarchive").set_visible(self.selected_document.archived) menu_popover.set_relative_to(self.view) menu_popover.set_pointing_to(rect) menu_popover.popup() return True self.view.unselect_all() def on_drag_begin(self, widget: Gtk.Widget, context: Gdk.DragContext) -> None: self.last_selected_path = self.selected_path def on_drag_motion(self, widget: Gtk.Widget, context: Gdk.DragContext, x: int, y: int, time: int) -> bool: # Change cursor icon based on drop target. # if the user move mouse over the folder - it becomes MOVE action model_path = self.view.get_path_at_pos(x, y) if not model_path: return False model_iter = self.model.get_iter(model_path) item_id = self.model.get_value(model_iter, 3) # Select hover cell, make it interactive for the user self.view.select_path(model_path) # Folder could have an ID, so this condition going to change if item_id == -1: Gdk.drag_status(context, Gdk.DragAction.MOVE, time) # TODO: Change folder icon on hover # self.model.set_value(model_iter, 0, Pixbuf.new_from_resource(RESOURCE_PREFIX + '/icons/folder-open.svg')) else: Gdk.drag_status(context, Gdk.DragAction.COPY, time) return True def on_drag_leave(self, widget: Gtk.Widget, context: Gdk.DragContext, time: int) -> None: # print('on_drag_leave') pass def on_drag_end(self, widget: Gtk.Widget, context: Gdk.DragContext) -> None: # print('on_drag_end') if self.last_selected_path: self.view.select_path(self.last_selected_path) self.last_selected_path = None # Move handler to window class def on_drag_data_received(self, widget: Gtk.Widget, drag_context: Gdk.DragContext, x: int, y: int, data: Gtk.SelectionData, info: int, time: int) -> None: print(f'Drag info: {info}') # Handle normal dnd from other apps with files as a target if info == TARGET_ENTRY_TEXT: uris = data.get_text().split('\n') print(data.get_text()) for uri in uris: # Skip empty items if not uri: continue p = urlparse(unquote_plus(uri)) filename = os.path.abspath(os.path.join(p.netloc, p.path)) self.emit('document-import', filename) # Handle reordering and moving inside Norka's virtual filesystem elif info == TARGET_ENTRY_REORDER: origin_item = self.selected_folder if self.is_folder_selected else self.selected_document dest_path = self.view.get_path_at_pos(x, y) if not dest_path: print("No dest path") return dest_iter = self.model.get_iter(dest_path) dest_item_id = self.model.get_value(dest_iter, 3) if dest_item_id == -1: dest_item = Folder( title=self.model.get_value(dest_iter, 1), path=self.model.get_value(dest_iter, 2) ) else: dest_item = self.storage.get(dest_item_id) # Don't move item to itself :) if origin_item.absolute_path == dest_item.absolute_path: print("Don't move item to itself") return # Create folders when doc dropped onto doc # After creation rename dialog should appear if isinstance(dest_item, Document): folder_id = self.create_folder(f'{origin_item.title} + {dest_item.title}', self.current_folder_path) if folder_id: folder = self.storage.get_folder(folder_id) self.storage.move(origin_item.document_id, folder.absolute_path) self.storage.move(dest_item.document_id, folder.absolute_path) self.reload_items() return # For folders, we have to move folder and its content to destination if isinstance(origin_item, Folder): print(f'Folder "{origin_item.title}": "{origin_item.path}" -> "{dest_item.absolute_path}"') self.storage.move_folder(origin_item, dest_item.absolute_path) self.reload_items() # For regular documents it is easy to move - just update the `path`. else: if self.storage.update(origin_item.document_id, {'path': dest_item.absolute_path}): print(f'Moved {origin_item.title} to {dest_item.absolute_path}') self.reload_items() Gtk.drag_finish(drag_context, True, drag_context.get_selected_action() == Gdk.DragAction.MOVE, time) def create_folder(self, title: str, path: str) -> Optional[int]: dialog = FolderCreateDialog(title) result = dialog.run() folder_path = dialog.folder_title dialog.destroy() if result == Gtk.ResponseType.ACCEPT: print(f'Folder "{folder_path}" created') return self.storage.add_folder(folder_path, path) def on_folder_rename_activated(self, sender: Gtk.Widget, title: str) -> None: sender.destroy() folder = self.document_grid.selected_folder if folder and self.storage.rename_folder(folder, title): self.document_grid.reload_items() def filter_model_by_value(self, model, path, iter): print(f'filter_model_by_value: {model}; {path}; {iter};')
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2021/9/12 # @Author : MashiroF # @File : DailyCash.py # @Software: PyCharm ''' cron: 30 5,12 * * * DailyCash.py new Env('欢太每日现金'); ''' import os import re import sys import time import random import logging # 日志模块 logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logFormat = logging.Formatter("%(message)s") # 日志输出流 stream = logging.StreamHandler() stream.setFormatter(logFormat) logger.addHandler(stream) # 第三方库 try: import requests except ModuleNotFoundError: logger.info("缺少requests依赖!程序将尝试安装依赖!") os.system("pip3 install requests -i https://pypi.tuna.tsinghua.edu.cn/simple") os.execl(sys.executable, 'python3', __file__, *sys.argv) # 检测配置文件并下载(云函数可能不适用) def checkFile(urlList): exitFlag = False for url in urlList: fileName = url.split('/')[-1] fileUrl = f'https://ghproxy.com/{url}' try: if not os.path.exists(fileName): exitFlag = True logger.info(f"`{fileName}`不存在,尝试进行下载...") content = requests.get(url=fileUrl).content.decode('utf-8') with open(file=fileName, mode='w', encoding='utf-8') as fc: fc.write(content) except: logger.info(f'请手动下载配置文件`{fileName[:-3]}`到 {os.path.dirname(os.path.abspath(__file__))}') logger.info(f'下载地址:{fileUrl}\n') if os.path.exists('/ql/config/auth.json'): # 判断环境,青龙面板则提示 logger.info(f"CK配置 -> 脚本管理 -> 搜索`HT_config`关键字 -> 编辑\n") if exitFlag ==True: # 发生下载行为,应退出程序,编辑配置文件 time.sleep(3) sys.exit(0) # 检测必备文件 fileUrlList = [ 'https://raw.githubusercontent.com/Mashiro2000/HeyTapTask/main/sendNotify.py', 'https://raw.githubusercontent.com/Mashiro2000/HeyTapTask/main/HT_config.py' ] checkFile(fileUrlList) # 配置文件 try: from HT_config import notifyBlackList,accounts,text logger.info(text) lists = accounts except: logger.info('更新配置文件或检测CK') lists = [] # 配信文件 try: from sendNotify import send except: logger.info('推送文件有误') finally: allMess = '' # 配信内容格式化 def notify(content=None): global allMess allMess = allMess + content + '\n' logger.info(content) # 日志录入时间 notify(f"任务:欢太每日现金\n时间:{time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())}") class DailyCash: def __init__(self,dic): self.dic = dic self.sess = requests.session() # 登录验证 def login(self): url = 'https://store.oppo.com/cn/oapi/users/web/member/check' headers = { 'Host': 'store.oppo.com', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Content-Type': 'application/x-www-form-urlencoded', 'Connection': 'keep-alive', 'Accept-Language': 'zh-cn', 'Accept-Encoding': 'gzip, deflate, br', } response = self.sess.get(url=url,headers=headers).json() if response['code'] == 200: notify(f"{self.dic["user"]}\t登录成功") return True else: notify(f"{self.dic["user"]}\t登录失败") return False # 浏览商品 def viewGoods(self, count,flag,dic=None): headers = { 'clientPackage': 'com.oppo.store', 'Host': 'msec.opposhop.cn', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Content-Type': 'application/x-www-form-urlencoded', 'Connection': 'keep-alive', 'User-Agent': 'okhttp/3.12.12.200sp1', 'Accept-Encoding': 'gzip' } result = self.getGoodMess(count=count) # 秒杀列表存在商品url if result['meta']['code'] == 200: for each in result['detail']: url = f"https://msec.opposhop.cn/goods/v1/info/sku?skuId={each["skuid"]}" self.sess.get(url=url,headers=headers) notify(f"正在浏览商品id:{each["skuid"]}...") time.sleep(random.randint(7,10)) if flag == 1: # 来源天天领现金 self.getCash(dic=dic) # 分享商品 def shareGoods(self, flag,count,dic=None): url = 'https://msec.opposhop.cn/users/vi/creditsTask/pushTask' headers = { 'clientPackage': 'com.oppo.store', 'Host': 'msec.opposhop.cn', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Content-Type': 'application/x-www-form-urlencoded', 'Connection': 'keep-alive', 'User-Agent': 'okhttp/3.12.12.200sp1', 'Accept-Encoding': 'gzip', } params = { 'marking': 'daily_sharegoods' } for i in range(count + random.randint(1,3)): self.sess.get(url=url,headers=headers,params=params) notify(f"正在执行第{i+1}次微信分享...") time.sleep(random.randint(7,10)) if flag == 1: #来源天天赚钱 self.getCash(dic=dic) # 秒杀详情页获取商品数据 def getGoodMess(self,count=10): taskUrl = f'https://msec.opposhop.cn/goods/v1/SeckillRound/goods/{random.randint(100,250)}' # 随机商品 headers = { 'clientPackage': 'com.oppo.store', 'Host': 'msec.opposhop.cn', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Content-Type': 'application/x-www-form-urlencoded', 'Connection': 'keep-alive', 'User-Agent': 'okhttp/3.12.12.200sp1', 'Accept-Encoding': 'gzip', } params = { 'pageSize':count + random.randint(1,3) } response = self.sess.get(url=taskUrl,headers=headers,params=params).json() if response['meta']['code'] == 200: return response else: notify(response) def getCash(self,dic): url = 'https://store.oppo.com/cn/oapi/omp-web/web/dailyCash/drawReward' headers = { 'Host': 'store.oppo.com', 'Connection': 'keep-alive', 'Origin': 'https://store.oppo.com', 'source_type': '501', 'clientPackage': 'com.oppo.store', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json, text/plain, */*', 'Referer': 'https://store.oppo.com/cn/app/cashRedEnvelope?activityId=1&us=shouye&um=xuanfu&uc=xianjinhongbao', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,en-US;q=0.9' } data = { 'activityId':1, 'channel':3, 'channelRewardId':dic['id'] } response = self.sess.post(url=url,headers=headers,data=data).json() if response['code'] == 200: notify(f"[{dic["taskName"]}]\t{response["data"]["amount"]}") elif response['code'] == 1000001: notify(f"[{dic["taskName"]}]\t{response["errorMessage"]}") # 天天领取现金 def getDailyCashTask(self): url = 'https://store.oppo.com/cn/oapi/omp-web/web/dailyCash/queryActivityReward' headers = { 'Host': 'store.oppo.com', 'Connection': 'keep-alive', 'source_type': '501', 'clientPackage': 'com.oppo.store', 'Accept': 'application/json, text/plain, */*', 'Referer': 'https://store.oppo.com/cn/app/cashRedEnvelope?activityId=1&us=shouye&um=xuanfu&uc=xianjinhongbao', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,en-US;q=0.9' } params = { 'activityId':1 } response = self.sess.get(url=url,headers=headers,params=params).json() if response['code'] == 200: self.taskRewardList = response['data']['taskRewardList'] self.timingRewardList = response['data']['timingRewardList'] return True elif response['code'] == 1000001: notify(response['errorMessage']) return False # 天天领现金浏览模板 def viewCashTask(self,dic): url = 'https://store.oppo.com/cn/oapi/credits/web/dailyCash/reportDailyTask' param = { 'taskType':dic['taskType'], 'taskId':f"dailyCash{dic["id"]}" } headers = { 'Host': 'store.oppo.com', 'Connection': 'keep-alive', 'source_type': '501', 'clientPackage': 'com.oppo.store', 'Cache-Control': 'no-cache', 'Accept': 'application/json, text/plain, */*', 'Referer': 'https://store.oppo.com/cn/app/cashRedEnvelope?activityId=1&us=shouye&um=xuanfu&uc=xianjinhongbao', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,en-US;q=0.9' } response = self.sess.get(url=url,headers=headers,params=param).json() if response['code'] == 200: notify(f"正在执行{dic["taskName"]}...") time.sleep(random.randint(5,7)) self.getCash(dic=dic) else: notify(f"{dic["taskName"]}执行失败") def runTaskRewardList(self): for each in self.taskRewardList: if each['taskName'] == '浏览商品': if each['taskStatus'] == 0: self.viewGoods(count=6,flag=1,dic=each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each["taskName"]}\t已领取") elif each['taskName'] == '浏览秒杀专区': if each['taskStatus'] == 0: self.viewCashTask(each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each["taskName"]}\t已领取") elif each['taskName'] == '分享商品': if each['taskStatus'] == 0: self.shareGoods(count=2,flag=1,dic=each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each["taskName"]}\t已领取") elif each['taskName'] == '观看直播': if each['taskStatus'] == 0: self.viewCashTask(each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each["taskName"]}\t已领取") elif each['taskName'] == '浏览签到页': if each['taskStatus'] == 0: self.viewCashTask(each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each["taskName"]}\t已领取") if each['taskName'] == '浏览领券中心': if each['taskStatus'] == 0: self.viewCashTask(each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each["taskName"]}\t已领取") elif each['taskName'] == '浏览realme商品': if each['taskStatus'] == 0: self.viewCashTask(each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each["taskName"]}\t已领取") elif each['taskName'] == '浏览指定商品': if each['taskStatus'] == 0: self.viewCashTask(each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each["taskName"]}\t已领取") elif each['taskName'] == '浏览一加商品': if each['taskStatus'] == 0: self.viewCashTask(each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each["taskName"]}\t已领取") elif each['taskName'] == '浏览OPPO商品': if each['taskStatus'] == 0: self.viewCashTask(each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each["taskName"]}\t已领取") # 执行欢太商城实例对象 def start(self): self.sess.headers.update({ "User-Agent":self.dic['UA'] }) self.sess.cookies.update({ "Cookie": self.dic['CK'] }) if self.login() == True: if self.getDailyCashTask() == True: # 获取天天领现金数据,判断CK是否正确(登录可能成功,但无法跑任务) self.runTaskRewardList() # 运行天天领现金 notify('*' * 40 + '\n') # 检测CK是否存在必备参数 def checkHT(dic): CK = dic['CK'] if len(re.findall(r'source_type=.*?;',CK)) == 0: notify(f"{dic["user"]}\tCK格式有误:可能缺少`source_type`字段") return False if len(re.findall(r'TOKENSID=.*?;',CK)) == 0: notify(f"{dic["user"]}\tCK格式有误:可能缺少`TOKENSID`字段") return False if len(re.findall(r'app_param=.*?[;]?',CK)) == 0: notify(f"{dic["user"]}\tCK格式有误:可能缺少`app_param`字段") return False return True # # 格式化设备信息Json # # 由于青龙的特殊性,把CK中的 app_param 转换未非正常格式,故需要此函数 # def transform(string): # dic2 = {} # dic1 = eval(string) # for i in dic1['app_param'][1:-1].split(','): # dic2[i.split(':')[0]] = i.split(':')[-1] # if dic1['CK'][-1] != ';': # dic1['CK'] = dic1['CK'] + ';' # dic1['CK'] = dic1['CK'] + f"app_param={json.dumps(dic2,ensure_ascii=False)}" # dic1['CK'] = checkHT(dic1['CK']) # return dic1 # # 读取青龙CK # def getEnv(key): # lists2 = [] # notify("尝试导入青龙面板CK...") # variable = os.environ.get(key) # if variable == None: # notify("青龙面板环境变量 TH_COOKIE 不存在!") # else: # for each in variable.split('&'): # result = transform(each) # if result: # lists2.append(result) # return lists2 # 兼容云函数 def main(event, context): global lists for each in lists: if all(each.values()): if checkHT(each): dailyCash = DailyCash(each) for count in range(3): try: time.sleep(random.randint(2,5)) # 随机延时 dailyCash.start() break except requests.exceptions.ConnectionError: notify(f"{dailyCash.dic["user"]}\t请求失败,随机延迟后再次访问") time.sleep(random.randint(2,5)) continue else: notify(f"账号: {dailyCash.dic["user"]}\n状态: 取消登录\n原因: 多次登录失败") break if not os.path.basename(__file__).split('_')[-1][:-3] in notifyBlackList: send('欢太每日现金',allMess) if __name__ == '__main__': main(None,None)
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2021/9/12 # @Author : MashiroF # @File : DailyCash.py # @Software: PyCharm ''' cron: 30 5,12 * * * DailyCash.py new Env('欢太每日现金'); ''' import os import re import sys import time import random import logging # 日志模块 logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logFormat = logging.Formatter("%(message)s") # 日志输出流 stream = logging.StreamHandler() stream.setFormatter(logFormat) logger.addHandler(stream) # 第三方库 try: import requests except ModuleNotFoundError: logger.info("缺少requests依赖!程序将尝试安装依赖!") os.system("pip3 install requests -i https://pypi.tuna.tsinghua.edu.cn/simple") os.execl(sys.executable, 'python3', __file__, *sys.argv) # 检测配置文件并下载(云函数可能不适用) def checkFile(urlList): exitFlag = False for url in urlList: fileName = url.split('/')[-1] fileUrl = f'https://ghproxy.com/{url}' try: if not os.path.exists(fileName): exitFlag = True logger.info(f"`{fileName}`不存在,尝试进行下载...") content = requests.get(url=fileUrl).content.decode('utf-8') with open(file=fileName, mode='w', encoding='utf-8') as fc: fc.write(content) except: logger.info(f'请手动下载配置文件`{fileName[:-3]}`到 {os.path.dirname(os.path.abspath(__file__))}') logger.info(f'下载地址:{fileUrl}\n') if os.path.exists('/ql/config/auth.json'): # 判断环境,青龙面板则提示 logger.info(f"CK配置 -> 脚本管理 -> 搜索`HT_config`关键字 -> 编辑\n") if exitFlag ==True: # 发生下载行为,应退出程序,编辑配置文件 time.sleep(3) sys.exit(0) # 检测必备文件 fileUrlList = [ 'https://raw.githubusercontent.com/Mashiro2000/HeyTapTask/main/sendNotify.py', 'https://raw.githubusercontent.com/Mashiro2000/HeyTapTask/main/HT_config.py' ] checkFile(fileUrlList) # 配置文件 try: from HT_config import notifyBlackList,accounts,text logger.info(text) lists = accounts except: logger.info('更新配置文件或检测CK') lists = [] # 配信文件 try: from sendNotify import send except: logger.info('推送文件有误') finally: allMess = '' # 配信内容格式化 def notify(content=None): global allMess allMess = allMess + content + '\n' logger.info(content) # 日志录入时间 notify(f"任务:欢太每日现金\n时间:{time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())}") class DailyCash: def __init__(self,dic): self.dic = dic self.sess = requests.session() # 登录验证 def login(self): url = 'https://store.oppo.com/cn/oapi/users/web/member/check' headers = { 'Host': 'store.oppo.com', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Content-Type': 'application/x-www-form-urlencoded', 'Connection': 'keep-alive', 'Accept-Language': 'zh-cn', 'Accept-Encoding': 'gzip, deflate, br', } response = self.sess.get(url=url,headers=headers).json() if response['code'] == 200: notify(f"{self.dic['user']}\t登录成功") return True else: notify(f"{self.dic['user']}\t登录失败") return False # 浏览商品 def viewGoods(self, count,flag,dic=None): headers = { 'clientPackage': 'com.oppo.store', 'Host': 'msec.opposhop.cn', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Content-Type': 'application/x-www-form-urlencoded', 'Connection': 'keep-alive', 'User-Agent': 'okhttp/3.12.12.200sp1', 'Accept-Encoding': 'gzip' } result = self.getGoodMess(count=count) # 秒杀列表存在商品url if result['meta']['code'] == 200: for each in result['detail']: url = f"https://msec.opposhop.cn/goods/v1/info/sku?skuId={each['skuid']}" self.sess.get(url=url,headers=headers) notify(f"正在浏览商品id:{each['skuid']}...") time.sleep(random.randint(7,10)) if flag == 1: # 来源天天领现金 self.getCash(dic=dic) # 分享商品 def shareGoods(self, flag,count,dic=None): url = 'https://msec.opposhop.cn/users/vi/creditsTask/pushTask' headers = { 'clientPackage': 'com.oppo.store', 'Host': 'msec.opposhop.cn', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Content-Type': 'application/x-www-form-urlencoded', 'Connection': 'keep-alive', 'User-Agent': 'okhttp/3.12.12.200sp1', 'Accept-Encoding': 'gzip', } params = { 'marking': 'daily_sharegoods' } for i in range(count + random.randint(1,3)): self.sess.get(url=url,headers=headers,params=params) notify(f"正在执行第{i+1}次微信分享...") time.sleep(random.randint(7,10)) if flag == 1: #来源天天赚钱 self.getCash(dic=dic) # 秒杀详情页获取商品数据 def getGoodMess(self,count=10): taskUrl = f'https://msec.opposhop.cn/goods/v1/SeckillRound/goods/{random.randint(100,250)}' # 随机商品 headers = { 'clientPackage': 'com.oppo.store', 'Host': 'msec.opposhop.cn', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Content-Type': 'application/x-www-form-urlencoded', 'Connection': 'keep-alive', 'User-Agent': 'okhttp/3.12.12.200sp1', 'Accept-Encoding': 'gzip', } params = { 'pageSize':count + random.randint(1,3) } response = self.sess.get(url=taskUrl,headers=headers,params=params).json() if response['meta']['code'] == 200: return response else: notify(response) def getCash(self,dic): url = 'https://store.oppo.com/cn/oapi/omp-web/web/dailyCash/drawReward' headers = { 'Host': 'store.oppo.com', 'Connection': 'keep-alive', 'Origin': 'https://store.oppo.com', 'source_type': '501', 'clientPackage': 'com.oppo.store', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json, text/plain, */*', 'Referer': 'https://store.oppo.com/cn/app/cashRedEnvelope?activityId=1&us=shouye&um=xuanfu&uc=xianjinhongbao', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,en-US;q=0.9' } data = { 'activityId':1, 'channel':3, 'channelRewardId':dic['id'] } response = self.sess.post(url=url,headers=headers,data=data).json() if response['code'] == 200: notify(f"[{dic['taskName']}]\t{response['data']['amount']}") elif response['code'] == 1000001: notify(f"[{dic['taskName']}]\t{response['errorMessage']}") # 天天领取现金 def getDailyCashTask(self): url = 'https://store.oppo.com/cn/oapi/omp-web/web/dailyCash/queryActivityReward' headers = { 'Host': 'store.oppo.com', 'Connection': 'keep-alive', 'source_type': '501', 'clientPackage': 'com.oppo.store', 'Accept': 'application/json, text/plain, */*', 'Referer': 'https://store.oppo.com/cn/app/cashRedEnvelope?activityId=1&us=shouye&um=xuanfu&uc=xianjinhongbao', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,en-US;q=0.9' } params = { 'activityId':1 } response = self.sess.get(url=url,headers=headers,params=params).json() if response['code'] == 200: self.taskRewardList = response['data']['taskRewardList'] self.timingRewardList = response['data']['timingRewardList'] return True elif response['code'] == 1000001: notify(response['errorMessage']) return False # 天天领现金浏览模板 def viewCashTask(self,dic): url = 'https://store.oppo.com/cn/oapi/credits/web/dailyCash/reportDailyTask' param = { 'taskType':dic['taskType'], 'taskId':f"dailyCash{dic['id']}" } headers = { 'Host': 'store.oppo.com', 'Connection': 'keep-alive', 'source_type': '501', 'clientPackage': 'com.oppo.store', 'Cache-Control': 'no-cache', 'Accept': 'application/json, text/plain, */*', 'Referer': 'https://store.oppo.com/cn/app/cashRedEnvelope?activityId=1&us=shouye&um=xuanfu&uc=xianjinhongbao', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,en-US;q=0.9' } response = self.sess.get(url=url,headers=headers,params=param).json() if response['code'] == 200: notify(f"正在执行{dic['taskName']}...") time.sleep(random.randint(5,7)) self.getCash(dic=dic) else: notify(f"{dic['taskName']}执行失败") def runTaskRewardList(self): for each in self.taskRewardList: if each['taskName'] == '浏览商品': if each['taskStatus'] == 0: self.viewGoods(count=6,flag=1,dic=each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each['taskName']}\t已领取") elif each['taskName'] == '浏览秒杀专区': if each['taskStatus'] == 0: self.viewCashTask(each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each['taskName']}\t已领取") elif each['taskName'] == '分享商品': if each['taskStatus'] == 0: self.shareGoods(count=2,flag=1,dic=each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each['taskName']}\t已领取") elif each['taskName'] == '观看直播': if each['taskStatus'] == 0: self.viewCashTask(each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each['taskName']}\t已领取") elif each['taskName'] == '浏览签到页': if each['taskStatus'] == 0: self.viewCashTask(each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each['taskName']}\t已领取") if each['taskName'] == '浏览领券中心': if each['taskStatus'] == 0: self.viewCashTask(each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each['taskName']}\t已领取") elif each['taskName'] == '浏览realme商品': if each['taskStatus'] == 0: self.viewCashTask(each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each['taskName']}\t已领取") elif each['taskName'] == '浏览指定商品': if each['taskStatus'] == 0: self.viewCashTask(each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each['taskName']}\t已领取") elif each['taskName'] == '浏览一加商品': if each['taskStatus'] == 0: self.viewCashTask(each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each['taskName']}\t已领取") elif each['taskName'] == '浏览OPPO商品': if each['taskStatus'] == 0: self.viewCashTask(each) elif each['taskStatus'] == 1: self.getCash(dic=each) elif each['taskStatus'] == 2: notify(f"{each['taskName']}\t已领取") # 执行欢太商城实例对象 def start(self): self.sess.headers.update({ "User-Agent":self.dic['UA'] }) self.sess.cookies.update({ "Cookie": self.dic['CK'] }) if self.login() == True: if self.getDailyCashTask() == True: # 获取天天领现金数据,判断CK是否正确(登录可能成功,但无法跑任务) self.runTaskRewardList() # 运行天天领现金 notify('*' * 40 + '\n') # 检测CK是否存在必备参数 def checkHT(dic): CK = dic['CK'] if len(re.findall(r'source_type=.*?;',CK)) == 0: notify(f"{dic['user']}\tCK格式有误:可能缺少`source_type`字段") return False if len(re.findall(r'TOKENSID=.*?;',CK)) == 0: notify(f"{dic['user']}\tCK格式有误:可能缺少`TOKENSID`字段") return False if len(re.findall(r'app_param=.*?[;]?',CK)) == 0: notify(f"{dic['user']}\tCK格式有误:可能缺少`app_param`字段") return False return True # # 格式化设备信息Json # # 由于青龙的特殊性,把CK中的 app_param 转换未非正常格式,故需要此函数 # def transform(string): # dic2 = {} # dic1 = eval(string) # for i in dic1['app_param'][1:-1].split(','): # dic2[i.split(':')[0]] = i.split(':')[-1] # if dic1['CK'][-1] != ';': # dic1['CK'] = dic1['CK'] + ';' # dic1['CK'] = dic1['CK'] + f"app_param={json.dumps(dic2,ensure_ascii=False)}" # dic1['CK'] = checkHT(dic1['CK']) # return dic1 # # 读取青龙CK # def getEnv(key): # lists2 = [] # notify("尝试导入青龙面板CK...") # variable = os.environ.get(key) # if variable == None: # notify("青龙面板环境变量 TH_COOKIE 不存在!") # else: # for each in variable.split('&'): # result = transform(each) # if result: # lists2.append(result) # return lists2 # 兼容云函数 def main(event, context): global lists for each in lists: if all(each.values()): if checkHT(each): dailyCash = DailyCash(each) for count in range(3): try: time.sleep(random.randint(2,5)) # 随机延时 dailyCash.start() break except requests.exceptions.ConnectionError: notify(f"{dailyCash.dic['user']}\t请求失败,随机延迟后再次访问") time.sleep(random.randint(2,5)) continue else: notify(f"账号: {dailyCash.dic['user']}\n状态: 取消登录\n原因: 多次登录失败") break if not os.path.basename(__file__).split('_')[-1][:-3] in notifyBlackList: send('欢太每日现金',allMess) if __name__ == '__main__': main(None,None)
# SPDX-License-Identifier: Apache-2.0 # Copyright © 2021 Intel Corporation """Helpers for strict type checking.""" import typing as T from .. import compilers from ..build import EnvironmentVariables, CustomTarget, BuildTarget, CustomTargetIndex, ExtractedObjects, GeneratedList from ..coredata import UserFeatureOption from ..interpreterbase import TYPE_var from ..interpreterbase.decorators import KwargInfo, ContainerTypeInfo from ..mesonlib import File, FileMode, MachineChoice, listify, has_path_sep, OptionKey from ..programs import ExternalProgram # Helper definition for type checks that are `Optional[T]` NoneType: T.Type[None] = type(None) def in_set_validator(choices: T.Set[str]) -> T.Callable[[str], T.Optional[str]]: """Check that the choice given was one of the given set.""" def inner(check: str) -> T.Optional[str]: if check not in choices: return f"must be one of {", ".join(sorted(choices))}, not {check}" return None return inner def _language_validator(l: T.List[str]) -> T.Optional[str]: """Validate language keyword argument. Particularly for functions like `add_compiler()`, and `add_*_args()` """ diff = {a.lower() for a in l}.difference(compilers.all_languages) if diff: return f'unknown languages: {', '.join(diff)}' return None def _install_mode_validator(mode: T.List[T.Union[str, bool, int]]) -> T.Optional[str]: """Validate the `install_mode` keyword argument. This is a rather odd thing, it's a scalar, or an array of 3 values in the form: [(str | False), (str | int | False) = False, (str | int | False) = False] where the second and third components are not required and default to False. """ if not mode: return None if True in mode: return 'components can only be permission strings, numbers, or False' if len(mode) > 3: return 'may have at most 3 elements' perms = mode[0] if not isinstance(perms, (str, bool)): return 'first component must be a permissions string or False' if isinstance(perms, str): if not len(perms) == 9: return ('permissions string must be exactly 9 characters in the form rwxr-xr-x,' f' got {len(perms)}') for i in [0, 3, 6]: if perms[i] not in {'-', 'r'}: return f'permissions character {i+1} must be "-" or "r", not {perms[i]}' for i in [1, 4, 7]: if perms[i] not in {'-', 'w'}: return f'permissions character {i+1} must be "-" or "w", not {perms[i]}' for i in [2, 5]: if perms[i] not in {'-', 'x', 's', 'S'}: return f'permissions character {i+1} must be "-", "s", "S", or "x", not {perms[i]}' if perms[8] not in {'-', 'x', 't', 'T'}: return f'permission character 9 must be "-", "t", "T", or "x", not {perms[8]}' if len(mode) >= 2 and not isinstance(mode[1], (int, str, bool)): return 'second componenent can only be a string, number, or False' if len(mode) >= 3 and not isinstance(mode[2], (int, str, bool)): return 'third componenent can only be a string, number, or False' return None def _install_mode_convertor(mode: T.Optional[T.List[T.Union[str, bool, int]]]) -> FileMode: """Convert the DSL form of the `install_mode` keyword argument to `FileMode` This is not required, and if not required returns None TODO: It's not clear to me why this needs to be None and not just return an empty FileMode. """ # this has already been validated by the validator return FileMode(*(m if isinstance(m, str) else None for m in mode)) def _lower_strlist(input: T.List[str]) -> T.List[str]: """Lower a list of strings. mypy (but not pyright) gets confused about using a lambda as the convertor function """ return [i.lower() for i in input] NATIVE_KW = KwargInfo( 'native', bool, default=False, convertor=lambda n: MachineChoice.BUILD if n else MachineChoice.HOST) LANGUAGE_KW = KwargInfo( 'language', ContainerTypeInfo(list, str, allow_empty=False), listify=True, required=True, validator=_language_validator, convertor=_lower_strlist) INSTALL_MODE_KW: KwargInfo[T.List[T.Union[str, bool, int]]] = KwargInfo( 'install_mode', ContainerTypeInfo(list, (str, bool, int)), listify=True, default=[], validator=_install_mode_validator, convertor=_install_mode_convertor, ) REQUIRED_KW: KwargInfo[T.Union[bool, UserFeatureOption]] = KwargInfo( 'required', (bool, UserFeatureOption), default=True, # TODO: extract_required_kwarg could be converted to a convertor ) def _env_validator(value: T.Union[EnvironmentVariables, T.List['TYPE_var'], T.Dict[str, 'TYPE_var'], str, None]) -> T.Optional[str]: def _splitter(v: str) -> T.Optional[str]: split = v.split('=', 1) if len(split) == 1: return f'"{v}" is not two string values separated by an "="' return None if isinstance(value, str): v = _splitter(value) if v is not None: return v elif isinstance(value, list): for i in listify(value): if not isinstance(i, str): return f"All array elements must be a string, not {i!r}" v = _splitter(i) if v is not None: return v elif isinstance(value, dict): # We don't need to spilt here, just do the type checking for k, dv in value.items(): if not isinstance(dv, str): return f"Dictionary element {k} must be a string not {dv!r}" # We know that otherwise we have an EnvironmentVariables object or None, and # we're okay at this point return None def split_equal_string(input: str) -> T.Tuple[str, str]: """Split a string in the form `x=y` This assumes that the string has already been validated to split properly. """ a, b = input.split('=', 1) return (a, b) def _env_convertor(value: T.Union[EnvironmentVariables, T.List[str], T.List[T.List[str]], T.Dict[str, str], str, None]) -> EnvironmentVariables: if isinstance(value, str): return EnvironmentVariables(dict([split_equal_string(value)])) elif isinstance(value, list): return EnvironmentVariables(dict(split_equal_string(v) for v in listify(value))) elif isinstance(value, dict): return EnvironmentVariables(value) elif value is None: return EnvironmentVariables() return value ENV_KW: KwargInfo[T.Union[EnvironmentVariables, T.List, T.Dict, str, None]] = KwargInfo( 'env', (EnvironmentVariables, list, dict, str, NoneType), validator=_env_validator, convertor=_env_convertor, ) DEPFILE_KW: KwargInfo[T.Optional[str]] = KwargInfo( 'depfile', (str, type(None)), validator=lambda x: 'Depfile must be a plain filename with a subdirectory' if has_path_sep(x) else None ) DEPENDS_KW: KwargInfo[T.List[T.Union[BuildTarget, CustomTarget]]] = KwargInfo( 'depends', ContainerTypeInfo(list, (BuildTarget, CustomTarget)), listify=True, default=[], ) DEPEND_FILES_KW: KwargInfo[T.List[T.Union[str, File]]] = KwargInfo( 'depend_files', ContainerTypeInfo(list, (File, str)), listify=True, default=[], ) COMMAND_KW: KwargInfo[T.List[T.Union[str, BuildTarget, CustomTarget, CustomTargetIndex, ExternalProgram, File]]] = KwargInfo( 'command', # TODO: should accept CustomTargetIndex as well? ContainerTypeInfo(list, (str, BuildTarget, CustomTarget, CustomTargetIndex, ExternalProgram, File), allow_empty=False), required=True, listify=True, default=[], ) def _override_options_convertor(raw: T.List[str]) -> T.Dict[OptionKey, str]: output: T.Dict[OptionKey, str] = {} for each in raw: k, v = split_equal_string(each) output[OptionKey.from_string(k)] = v return output OVERRIDE_OPTIONS_KW: KwargInfo[T.List[str]] = KwargInfo( 'override_options', ContainerTypeInfo(list, str), listify=True, default=[], # Reusing the env validator is a littl overkill, but nicer than duplicating the code validator=_env_validator, convertor=_override_options_convertor, ) def _output_validator(outputs: T.List[str]) -> T.Optional[str]: for i in outputs: if i == '': return 'Output must not be empty.' elif i.strip() == '': return 'Output must not consist only of whitespace.' elif has_path_sep(i): return f'Output {i!r} must not contain a path segment.' return None CT_OUTPUT_KW: KwargInfo[T.List[str]] = KwargInfo( 'output', ContainerTypeInfo(list, str, allow_empty=False), listify=True, required=True, default=[], validator=_output_validator, ) CT_INPUT_KW: KwargInfo[T.List[T.Union[str, File, ExternalProgram, BuildTarget, CustomTarget, CustomTargetIndex, ExtractedObjects, GeneratedList]]] = KwargInfo( 'input', ContainerTypeInfo(list, (str, File, ExternalProgram, BuildTarget, CustomTarget, CustomTargetIndex, ExtractedObjects, GeneratedList)), listify=True, default=[], ) CT_INSTALL_TAG_KW: KwargInfo[T.List[T.Union[str, bool]]] = KwargInfo( 'install_tag', ContainerTypeInfo(list, (str, bool)), listify=True, default=[], since='0.60.0', ) INSTALL_KW = KwargInfo('install', bool, default=False) CT_INSTALL_DIR_KW: KwargInfo[T.List[T.Union[str, bool]]] = KwargInfo( 'install_dir', ContainerTypeInfo(list, (str, bool)), listify=True, default=[], ) CT_BUILD_BY_DEFAULT: KwargInfo[T.Optional[bool]] = KwargInfo('build_by_default', (bool, type(None)), since='0.40.0')
# SPDX-License-Identifier: Apache-2.0 # Copyright © 2021 Intel Corporation """Helpers for strict type checking.""" import typing as T from .. import compilers from ..build import EnvironmentVariables, CustomTarget, BuildTarget, CustomTargetIndex, ExtractedObjects, GeneratedList from ..coredata import UserFeatureOption from ..interpreterbase import TYPE_var from ..interpreterbase.decorators import KwargInfo, ContainerTypeInfo from ..mesonlib import File, FileMode, MachineChoice, listify, has_path_sep, OptionKey from ..programs import ExternalProgram # Helper definition for type checks that are `Optional[T]` NoneType: T.Type[None] = type(None) def in_set_validator(choices: T.Set[str]) -> T.Callable[[str], T.Optional[str]]: """Check that the choice given was one of the given set.""" def inner(check: str) -> T.Optional[str]: if check not in choices: return f"must be one of {', '.join(sorted(choices))}, not {check}" return None return inner def _language_validator(l: T.List[str]) -> T.Optional[str]: """Validate language keyword argument. Particularly for functions like `add_compiler()`, and `add_*_args()` """ diff = {a.lower() for a in l}.difference(compilers.all_languages) if diff: return f'unknown languages: {", ".join(diff)}' return None def _install_mode_validator(mode: T.List[T.Union[str, bool, int]]) -> T.Optional[str]: """Validate the `install_mode` keyword argument. This is a rather odd thing, it's a scalar, or an array of 3 values in the form: [(str | False), (str | int | False) = False, (str | int | False) = False] where the second and third components are not required and default to False. """ if not mode: return None if True in mode: return 'components can only be permission strings, numbers, or False' if len(mode) > 3: return 'may have at most 3 elements' perms = mode[0] if not isinstance(perms, (str, bool)): return 'first component must be a permissions string or False' if isinstance(perms, str): if not len(perms) == 9: return ('permissions string must be exactly 9 characters in the form rwxr-xr-x,' f' got {len(perms)}') for i in [0, 3, 6]: if perms[i] not in {'-', 'r'}: return f'permissions character {i+1} must be "-" or "r", not {perms[i]}' for i in [1, 4, 7]: if perms[i] not in {'-', 'w'}: return f'permissions character {i+1} must be "-" or "w", not {perms[i]}' for i in [2, 5]: if perms[i] not in {'-', 'x', 's', 'S'}: return f'permissions character {i+1} must be "-", "s", "S", or "x", not {perms[i]}' if perms[8] not in {'-', 'x', 't', 'T'}: return f'permission character 9 must be "-", "t", "T", or "x", not {perms[8]}' if len(mode) >= 2 and not isinstance(mode[1], (int, str, bool)): return 'second componenent can only be a string, number, or False' if len(mode) >= 3 and not isinstance(mode[2], (int, str, bool)): return 'third componenent can only be a string, number, or False' return None def _install_mode_convertor(mode: T.Optional[T.List[T.Union[str, bool, int]]]) -> FileMode: """Convert the DSL form of the `install_mode` keyword argument to `FileMode` This is not required, and if not required returns None TODO: It's not clear to me why this needs to be None and not just return an empty FileMode. """ # this has already been validated by the validator return FileMode(*(m if isinstance(m, str) else None for m in mode)) def _lower_strlist(input: T.List[str]) -> T.List[str]: """Lower a list of strings. mypy (but not pyright) gets confused about using a lambda as the convertor function """ return [i.lower() for i in input] NATIVE_KW = KwargInfo( 'native', bool, default=False, convertor=lambda n: MachineChoice.BUILD if n else MachineChoice.HOST) LANGUAGE_KW = KwargInfo( 'language', ContainerTypeInfo(list, str, allow_empty=False), listify=True, required=True, validator=_language_validator, convertor=_lower_strlist) INSTALL_MODE_KW: KwargInfo[T.List[T.Union[str, bool, int]]] = KwargInfo( 'install_mode', ContainerTypeInfo(list, (str, bool, int)), listify=True, default=[], validator=_install_mode_validator, convertor=_install_mode_convertor, ) REQUIRED_KW: KwargInfo[T.Union[bool, UserFeatureOption]] = KwargInfo( 'required', (bool, UserFeatureOption), default=True, # TODO: extract_required_kwarg could be converted to a convertor ) def _env_validator(value: T.Union[EnvironmentVariables, T.List['TYPE_var'], T.Dict[str, 'TYPE_var'], str, None]) -> T.Optional[str]: def _splitter(v: str) -> T.Optional[str]: split = v.split('=', 1) if len(split) == 1: return f'"{v}" is not two string values separated by an "="' return None if isinstance(value, str): v = _splitter(value) if v is not None: return v elif isinstance(value, list): for i in listify(value): if not isinstance(i, str): return f"All array elements must be a string, not {i!r}" v = _splitter(i) if v is not None: return v elif isinstance(value, dict): # We don't need to spilt here, just do the type checking for k, dv in value.items(): if not isinstance(dv, str): return f"Dictionary element {k} must be a string not {dv!r}" # We know that otherwise we have an EnvironmentVariables object or None, and # we're okay at this point return None def split_equal_string(input: str) -> T.Tuple[str, str]: """Split a string in the form `x=y` This assumes that the string has already been validated to split properly. """ a, b = input.split('=', 1) return (a, b) def _env_convertor(value: T.Union[EnvironmentVariables, T.List[str], T.List[T.List[str]], T.Dict[str, str], str, None]) -> EnvironmentVariables: if isinstance(value, str): return EnvironmentVariables(dict([split_equal_string(value)])) elif isinstance(value, list): return EnvironmentVariables(dict(split_equal_string(v) for v in listify(value))) elif isinstance(value, dict): return EnvironmentVariables(value) elif value is None: return EnvironmentVariables() return value ENV_KW: KwargInfo[T.Union[EnvironmentVariables, T.List, T.Dict, str, None]] = KwargInfo( 'env', (EnvironmentVariables, list, dict, str, NoneType), validator=_env_validator, convertor=_env_convertor, ) DEPFILE_KW: KwargInfo[T.Optional[str]] = KwargInfo( 'depfile', (str, type(None)), validator=lambda x: 'Depfile must be a plain filename with a subdirectory' if has_path_sep(x) else None ) DEPENDS_KW: KwargInfo[T.List[T.Union[BuildTarget, CustomTarget]]] = KwargInfo( 'depends', ContainerTypeInfo(list, (BuildTarget, CustomTarget)), listify=True, default=[], ) DEPEND_FILES_KW: KwargInfo[T.List[T.Union[str, File]]] = KwargInfo( 'depend_files', ContainerTypeInfo(list, (File, str)), listify=True, default=[], ) COMMAND_KW: KwargInfo[T.List[T.Union[str, BuildTarget, CustomTarget, CustomTargetIndex, ExternalProgram, File]]] = KwargInfo( 'command', # TODO: should accept CustomTargetIndex as well? ContainerTypeInfo(list, (str, BuildTarget, CustomTarget, CustomTargetIndex, ExternalProgram, File), allow_empty=False), required=True, listify=True, default=[], ) def _override_options_convertor(raw: T.List[str]) -> T.Dict[OptionKey, str]: output: T.Dict[OptionKey, str] = {} for each in raw: k, v = split_equal_string(each) output[OptionKey.from_string(k)] = v return output OVERRIDE_OPTIONS_KW: KwargInfo[T.List[str]] = KwargInfo( 'override_options', ContainerTypeInfo(list, str), listify=True, default=[], # Reusing the env validator is a littl overkill, but nicer than duplicating the code validator=_env_validator, convertor=_override_options_convertor, ) def _output_validator(outputs: T.List[str]) -> T.Optional[str]: for i in outputs: if i == '': return 'Output must not be empty.' elif i.strip() == '': return 'Output must not consist only of whitespace.' elif has_path_sep(i): return f'Output {i!r} must not contain a path segment.' return None CT_OUTPUT_KW: KwargInfo[T.List[str]] = KwargInfo( 'output', ContainerTypeInfo(list, str, allow_empty=False), listify=True, required=True, default=[], validator=_output_validator, ) CT_INPUT_KW: KwargInfo[T.List[T.Union[str, File, ExternalProgram, BuildTarget, CustomTarget, CustomTargetIndex, ExtractedObjects, GeneratedList]]] = KwargInfo( 'input', ContainerTypeInfo(list, (str, File, ExternalProgram, BuildTarget, CustomTarget, CustomTargetIndex, ExtractedObjects, GeneratedList)), listify=True, default=[], ) CT_INSTALL_TAG_KW: KwargInfo[T.List[T.Union[str, bool]]] = KwargInfo( 'install_tag', ContainerTypeInfo(list, (str, bool)), listify=True, default=[], since='0.60.0', ) INSTALL_KW = KwargInfo('install', bool, default=False) CT_INSTALL_DIR_KW: KwargInfo[T.List[T.Union[str, bool]]] = KwargInfo( 'install_dir', ContainerTypeInfo(list, (str, bool)), listify=True, default=[], ) CT_BUILD_BY_DEFAULT: KwargInfo[T.Optional[bool]] = KwargInfo('build_by_default', (bool, type(None)), since='0.40.0')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import platform import sympy import mpmath import numpy from mathics.version import __version__ version_info = { "mathics": __version__, "sympy": sympy.__version__, "mpmath": mpmath.__version__, "numpy": numpy.__version__, "python": platform.python_implementation() + " " + sys.version.split("\n")[0], } try: import cython except ImportError: pass else: version_info["cython"] = cython.__version__ version_string = """Mathics {mathics} on {python} using SymPy {sympy}, mpmath {mpmath}, numpy {numpy}""".format( **version_info ) if "cython" in version_info: version_string += f", cython {version_info["cython"]}" license_string = """\ Copyright (C) 2011-2021 The Mathics Team. This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. See the documentation for the full license."""
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import platform import sympy import mpmath import numpy from mathics.version import __version__ version_info = { "mathics": __version__, "sympy": sympy.__version__, "mpmath": mpmath.__version__, "numpy": numpy.__version__, "python": platform.python_implementation() + " " + sys.version.split("\n")[0], } try: import cython except ImportError: pass else: version_info["cython"] = cython.__version__ version_string = """Mathics {mathics} on {python} using SymPy {sympy}, mpmath {mpmath}, numpy {numpy}""".format( **version_info ) if "cython" in version_info: version_string += f", cython {version_info['cython']}" license_string = """\ Copyright (C) 2011-2021 The Mathics Team. This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. See the documentation for the full license."""
from pprint import pprint from ttp import ttp import json import time from netmiko import ConnectHandler ssh = { 'device_type': 'alcatel_sros', 'ip': '135.243.92.119', 'username': 'admin', 'password': 'admin', 'port': '22' } print ('Connection successful') net_connect = ConnectHandler(**ssh) output = net_connect.send_command('show port detail') #print (output) parser = ttp(data=data_to_parse, template=ttp_template) parser.parse() results = parser.result(format='json')[0] #converting str to json. result = json.loads(results) #print(result[0][1]['Port_Number']) #print(len(result[0])) i = 0 while i < len(result[0]): # print(result[0][i]['Port_Number']) if "Port_Number" in result[0][i] and "Utilization_Input" in result[0][i] and "Utilization_Output" in result[0][i]: print(f"{result[0][i]["Port_Number"]} --> Utilization Input degeri : {result[0][i]["Utilization_Input"]} Utilization Output degeri: {result[0][i]["Utilization_Output"]}") i = i + 1
from pprint import pprint from ttp import ttp import json import time from netmiko import ConnectHandler ssh = { 'device_type': 'alcatel_sros', 'ip': '135.243.92.119', 'username': 'admin', 'password': 'admin', 'port': '22' } print ('Connection successful') net_connect = ConnectHandler(**ssh) output = net_connect.send_command('show port detail') #print (output) parser = ttp(data=data_to_parse, template=ttp_template) parser.parse() results = parser.result(format='json')[0] #converting str to json. result = json.loads(results) #print(result[0][1]['Port_Number']) #print(len(result[0])) i = 0 while i < len(result[0]): # print(result[0][i]['Port_Number']) if "Port_Number" in result[0][i] and "Utilization_Input" in result[0][i] and "Utilization_Output" in result[0][i]: print(f"{result[0][i]['Port_Number']} --> Utilization Input degeri : {result[0][i]['Utilization_Input']} Utilization Output degeri: {result[0][i]['Utilization_Output']}") i = i + 1
# Copyright 2021 Google LLC # # 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. """ Userservice manages user account creation, user login, and related tasks """ import atexit from datetime import datetime, timedelta import logging import os from pathlib import Path import sys import re import bcrypt import jwt from flask import Flask, jsonify, request import bleach from sqlalchemy.exc import OperationalError, SQLAlchemyError from db import UserDb from opentelemetry import trace import tracing from tracing import OpenTelemetryConfiguration from flask_management_endpoints import ManagementEndpoints APP_NAME = 'userservice' def create_app(): """Flask application factory to create instances of the Userservice Flask App """ app = Flask('userservice') @app.route('/users', methods=['POST']) def create_user(): """Create a user record. Fails if that username already exists. Generates a unique accountid. request fields: - username - password - password-repeat - firstname - lastname - birthday - timezone - address - state - zip - ssn """ span = trace.get_current_span() try: app.logger.debug('Sanitizing input') req = {k: bleach.clean(v) for k, v in request.form.items()} if 'username' in req: span.set_attribute('username', req['username']) __validate_new_user(req) # Check if user already exists if users_db.get_user(req['username']) is not None: raise NameError(f"user {req["username"]} already exists") # Create password hash with salt app.logger.debug("Creating password hash.") password = req['password'] salt = bcrypt.gensalt() passhash = bcrypt.hashpw(password.encode('utf-8'), salt) accountid = users_db.generate_accountid() # Create user data to be added to the database user_data = { 'accountid': accountid, 'username': req['username'], 'passhash': passhash, 'firstname': req['firstname'], 'lastname': req['lastname'], 'birthday': req['birthday'], 'timezone': req['timezone'], 'address': req['address'], 'state': req['state'], 'zip': req['zip'], 'ssn': req['ssn'], } # Add user_data to database app.logger.debug("Adding user to the database") users_db.add_user(user_data) app.logger.info("Successfully created user") except UserWarning as warn: app.logger.error("Error creating new user: %s", str(warn)) span.add_event(str(warn)) return str(warn), 400 except NameError as err: app.logger.error("Error creating new user: %s", str(err)) span.record_exception(err) return str(err), 409 except SQLAlchemyError as err: app.logger.error("Error creating new user: %s", str(err)) span.record_exception(err) return 'failed to create user', 500 return jsonify({}), 201 def __validate_new_user(req): app.logger.debug('validating create user request: %s', str(req)) # Check if required fields are filled fields = ( 'username', 'password', 'password-repeat', 'firstname', 'lastname', 'birthday', 'timezone', 'address', 'state', 'zip', 'ssn', ) if any(f not in req for f in fields): raise UserWarning('missing required field(s)') if any(not bool(req[f] or req[f].strip()) for f in fields): raise UserWarning('missing value for input field(s)') # Verify username contains only 2-15 alphanumeric or underscore characters if not re.match(r"\A[a-zA-Z0-9_]{2,15}\Z", req['username']): raise UserWarning('username must contain 2-15 alphanumeric characters or underscores') # Check if passwords match if not req['password'] == req['password-repeat']: raise UserWarning('passwords do not match') @app.route('/login', methods=['GET']) def login(): """Login a user and return a JWT token Fails if username doesn't exist or password doesn't match hash token expiry time determined by environment variable request fields: - username - password """ span = trace.get_current_span() app.logger.debug('Sanitizing login input') username = bleach.clean(request.args.get('username')) span.set_attribute('username', username) password = bleach.clean(request.args.get('password')) # Get user data try: app.logger.debug('Getting the user data') user = users_db.get_user(username) if user is None: raise LookupError(f"user {username} does not exist") # Validate the password app.logger.debug('Validating the password') if not bcrypt.checkpw(password.encode('utf-8'), user['passhash']): raise PermissionError('invalid login') full_name = f"{user["firstname"]} {user["lastname"]}" exp_time = datetime.utcnow() + timedelta(seconds=app.config['EXPIRY_SECONDS']) payload = { 'user': username, 'acct': user['accountid'], 'name': full_name, 'iat': datetime.utcnow(), 'exp': exp_time, } app.logger.debug('Creating jwt token.') token = jwt.encode(payload, app.config['PRIVATE_KEY'], algorithm='RS256') app.logger.info('Login Successful') return jsonify({'token': token.decode("utf-8")}), 200 except LookupError as err: app.logger.error('Error logging in: %s', str(err)) span.record_exception(err) return str(err), 404 except PermissionError as err: app.logger.error('Error logging in: %s', str(err)) span.record_exception(err) return str(err), 401 except SQLAlchemyError as err: app.logger.error('Error logging in: %s', str(err)) span.record_exception(err) return 'failed to retrieve user information', 500 @atexit.register def _shutdown(): """Executed when web app is terminated.""" app.logger.info("Stopping userservice.") # Set up logger app.logger.handlers = logging.getLogger('gunicorn.error').handlers app.logger.setLevel(logging.getLogger('gunicorn.error').level) app.logger.info('Starting userservice.') app.config['VERSION'] = os.environ.get('VERSION') app.config['EXPIRY_SECONDS'] = int(os.environ.get('TOKEN_EXPIRY_SECONDS')) private_key_path = os.environ.get('PRIV_KEY_PATH') if private_key_path: app.config['PRIVATE_KEY'] = Path(private_key_path).read_text(encoding='ascii') public_key_path = os.environ.get('PUB_KEY_PATH') if os.environ.get('PUB_KEY_PATH'): app.config['PUBLIC_KEY'] = Path(public_key_path).read_text(encoding='ascii') # Configure database connection try: users_db = UserDb(os.environ.get("ACCOUNTS_DB_URI"), app.logger) except OperationalError: app.logger.critical("users_db database connection failed") sys.exit(1) # Set up tracing and export spans to Open Telemetry if tracing.config: tracing.config.instrument_app(app) # Setup health checks and management endpoints ManagementEndpoints(app) def db_check(): try: engine = users_db.engine result = engine.execute('SELECT 1') return result.first()[0] == 1 except SQLAlchemyError as err: app.logger.error(f'DB health check failed: {err}') return False app.config.update( Z_ENDPOINTS={ 'check_functions': { 'readiness': { 'db': db_check } } } ) return app if __name__ == "__main__": if not tracing.config: tracing.config = OpenTelemetryConfiguration(APP_NAME) tracing.config.setup_exporter() # Create an instance of flask server when called directly USERSERVICE = create_app() USERSERVICE.run(port=os.getenv('FLASK_RUN_PORT', 5001))
# Copyright 2021 Google LLC # # 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. """ Userservice manages user account creation, user login, and related tasks """ import atexit from datetime import datetime, timedelta import logging import os from pathlib import Path import sys import re import bcrypt import jwt from flask import Flask, jsonify, request import bleach from sqlalchemy.exc import OperationalError, SQLAlchemyError from db import UserDb from opentelemetry import trace import tracing from tracing import OpenTelemetryConfiguration from flask_management_endpoints import ManagementEndpoints APP_NAME = 'userservice' def create_app(): """Flask application factory to create instances of the Userservice Flask App """ app = Flask('userservice') @app.route('/users', methods=['POST']) def create_user(): """Create a user record. Fails if that username already exists. Generates a unique accountid. request fields: - username - password - password-repeat - firstname - lastname - birthday - timezone - address - state - zip - ssn """ span = trace.get_current_span() try: app.logger.debug('Sanitizing input') req = {k: bleach.clean(v) for k, v in request.form.items()} if 'username' in req: span.set_attribute('username', req['username']) __validate_new_user(req) # Check if user already exists if users_db.get_user(req['username']) is not None: raise NameError(f"user {req['username']} already exists") # Create password hash with salt app.logger.debug("Creating password hash.") password = req['password'] salt = bcrypt.gensalt() passhash = bcrypt.hashpw(password.encode('utf-8'), salt) accountid = users_db.generate_accountid() # Create user data to be added to the database user_data = { 'accountid': accountid, 'username': req['username'], 'passhash': passhash, 'firstname': req['firstname'], 'lastname': req['lastname'], 'birthday': req['birthday'], 'timezone': req['timezone'], 'address': req['address'], 'state': req['state'], 'zip': req['zip'], 'ssn': req['ssn'], } # Add user_data to database app.logger.debug("Adding user to the database") users_db.add_user(user_data) app.logger.info("Successfully created user") except UserWarning as warn: app.logger.error("Error creating new user: %s", str(warn)) span.add_event(str(warn)) return str(warn), 400 except NameError as err: app.logger.error("Error creating new user: %s", str(err)) span.record_exception(err) return str(err), 409 except SQLAlchemyError as err: app.logger.error("Error creating new user: %s", str(err)) span.record_exception(err) return 'failed to create user', 500 return jsonify({}), 201 def __validate_new_user(req): app.logger.debug('validating create user request: %s', str(req)) # Check if required fields are filled fields = ( 'username', 'password', 'password-repeat', 'firstname', 'lastname', 'birthday', 'timezone', 'address', 'state', 'zip', 'ssn', ) if any(f not in req for f in fields): raise UserWarning('missing required field(s)') if any(not bool(req[f] or req[f].strip()) for f in fields): raise UserWarning('missing value for input field(s)') # Verify username contains only 2-15 alphanumeric or underscore characters if not re.match(r"\A[a-zA-Z0-9_]{2,15}\Z", req['username']): raise UserWarning('username must contain 2-15 alphanumeric characters or underscores') # Check if passwords match if not req['password'] == req['password-repeat']: raise UserWarning('passwords do not match') @app.route('/login', methods=['GET']) def login(): """Login a user and return a JWT token Fails if username doesn't exist or password doesn't match hash token expiry time determined by environment variable request fields: - username - password """ span = trace.get_current_span() app.logger.debug('Sanitizing login input') username = bleach.clean(request.args.get('username')) span.set_attribute('username', username) password = bleach.clean(request.args.get('password')) # Get user data try: app.logger.debug('Getting the user data') user = users_db.get_user(username) if user is None: raise LookupError(f"user {username} does not exist") # Validate the password app.logger.debug('Validating the password') if not bcrypt.checkpw(password.encode('utf-8'), user['passhash']): raise PermissionError('invalid login') full_name = f"{user['firstname']} {user['lastname']}" exp_time = datetime.utcnow() + timedelta(seconds=app.config['EXPIRY_SECONDS']) payload = { 'user': username, 'acct': user['accountid'], 'name': full_name, 'iat': datetime.utcnow(), 'exp': exp_time, } app.logger.debug('Creating jwt token.') token = jwt.encode(payload, app.config['PRIVATE_KEY'], algorithm='RS256') app.logger.info('Login Successful') return jsonify({'token': token.decode("utf-8")}), 200 except LookupError as err: app.logger.error('Error logging in: %s', str(err)) span.record_exception(err) return str(err), 404 except PermissionError as err: app.logger.error('Error logging in: %s', str(err)) span.record_exception(err) return str(err), 401 except SQLAlchemyError as err: app.logger.error('Error logging in: %s', str(err)) span.record_exception(err) return 'failed to retrieve user information', 500 @atexit.register def _shutdown(): """Executed when web app is terminated.""" app.logger.info("Stopping userservice.") # Set up logger app.logger.handlers = logging.getLogger('gunicorn.error').handlers app.logger.setLevel(logging.getLogger('gunicorn.error').level) app.logger.info('Starting userservice.') app.config['VERSION'] = os.environ.get('VERSION') app.config['EXPIRY_SECONDS'] = int(os.environ.get('TOKEN_EXPIRY_SECONDS')) private_key_path = os.environ.get('PRIV_KEY_PATH') if private_key_path: app.config['PRIVATE_KEY'] = Path(private_key_path).read_text(encoding='ascii') public_key_path = os.environ.get('PUB_KEY_PATH') if os.environ.get('PUB_KEY_PATH'): app.config['PUBLIC_KEY'] = Path(public_key_path).read_text(encoding='ascii') # Configure database connection try: users_db = UserDb(os.environ.get("ACCOUNTS_DB_URI"), app.logger) except OperationalError: app.logger.critical("users_db database connection failed") sys.exit(1) # Set up tracing and export spans to Open Telemetry if tracing.config: tracing.config.instrument_app(app) # Setup health checks and management endpoints ManagementEndpoints(app) def db_check(): try: engine = users_db.engine result = engine.execute('SELECT 1') return result.first()[0] == 1 except SQLAlchemyError as err: app.logger.error(f'DB health check failed: {err}') return False app.config.update( Z_ENDPOINTS={ 'check_functions': { 'readiness': { 'db': db_check } } } ) return app if __name__ == "__main__": if not tracing.config: tracing.config = OpenTelemetryConfiguration(APP_NAME) tracing.config.setup_exporter() # Create an instance of flask server when called directly USERSERVICE = create_app() USERSERVICE.run(port=os.getenv('FLASK_RUN_PORT', 5001))
""" Financial Modeling Prep Controller """ __docformat__ = "numpy" import argparse import os from typing import List from prompt_toolkit.completion import NestedCompleter from gamestonk_terminal.fundamental_analysis.financial_modeling_prep import fmp_view from gamestonk_terminal import feature_flags as gtff from gamestonk_terminal.helper_funcs import ( get_flair, ) from gamestonk_terminal.menu import session class FinancialModelingPrepController: """Financial Modeling Prep Controller""" # Command choices CHOICES = [ "cls", "?", "help", "q", "quit", "profile", "quote", "enterprise", "dcf", "income", "balance", "cash", "metrics", "ratios", "growth", ] def __init__(self, ticker: str, start: str, interval: str): """Constructor Parameters ---------- ticker : str Fundamental analysis ticker symbol start : str Stat date of the stock data interval : str Stock data interval """ self.ticker = ticker self.start = start self.interval = interval self.fmp_parser = argparse.ArgumentParser(add_help=False, prog="fmp") self.fmp_parser.add_argument( "cmd", choices=self.CHOICES, ) def print_help(self): """Print help""" print( "https://github.com/GamestonkTerminal/GamestonkTerminal/" "tree/main/gamestonk_terminal/fundamental_analysis/financial_modeling_prep" ) intraday = (f"Intraday {self.interval}", "Daily")[self.interval == "1440min"] if self.start: print( f"\n{intraday} Stock: {self.ticker} (from {self.start.strftime("%Y-%m-%d")})" ) else: print(f"\n{intraday} Stock: {self.ticker}") print("\nFinancial Modeling Prep API") print(" cls clear screen") print(" ?/help show this menu again") print(" q quit this menu, and shows back to main menu") print(" quit quit to abandon program") print("") print(" profile profile of the company") print(" quote quote of the company") print(" enterprise enterprise value of the company over time") print(" dcf discounted cash flow of the company over time") print(" income income statements of the company") print(" balance balance sheet of the company") print(" cash cash flow statement of the company") print(" metrics key metrics of the company") print(" ratios financial ratios of the company") print(" growth financial statement growth of the company") print("") def switch(self, an_input: str): """Process and dispatch input Returns ------- True, False or None False - quit the menu True - quit the program None - continue in the menu """ # Empty command if not an_input: print("") return None (known_args, other_args) = self.fmp_parser.parse_known_args(an_input.split()) # Help menu again if known_args.cmd == "?": self.print_help() return None # Clear screen if known_args.cmd == "cls": os.system("cls||clear") return None return getattr( self, "call_" + known_args.cmd, lambda: "Command not recognized!" )(other_args) def call_help(self, _): """Process Help command""" self.print_help() def call_q(self, _): """Process Q command - quit the menu""" return False def call_quit(self, _): """Process Quit command - quit the program""" return True def call_profile(self, other_args: List[str]): """Process profile command""" fmp_view.profile(other_args, self.ticker) def call_quote(self, other_args: List[str]): """Process quote command""" fmp_view.quote(other_args, self.ticker) def call_enterprise(self, other_args: List[str]): """Process income command""" fmp_view.enterprise(other_args, self.ticker) def call_dcf(self, other_args: List[str]): """Process dcf command""" fmp_view.discounted_cash_flow(other_args, self.ticker) def call_income(self, other_args: List[str]): """Process income command""" fmp_view.income_statement(other_args, self.ticker) def call_balance(self, other_args: List[str]): """Process balance command""" fmp_view.balance_sheet(other_args, self.ticker) def call_cash(self, other_args: List[str]): """Process cash command""" fmp_view.cash_flow(other_args, self.ticker) def call_metrics(self, other_args: List[str]): """Process metrics command""" fmp_view.key_metrics(other_args, self.ticker) def call_ratios(self, other_args: List[str]): """Process cash command""" fmp_view.financial_ratios(other_args, self.ticker) def call_growth(self, other_args: List[str]): """Process cash command""" fmp_view.financial_statement_growth(other_args, self.ticker) def menu(ticker: str, start: str, interval: str): """Financial Modeling Prep menu Parameters ---------- ticker : str Fundamental analysis ticker symbol start : str Start date of the stock data interval : str Stock data interval """ fmp_controller = FinancialModelingPrepController(ticker, start, interval) fmp_controller.call_help(None) while True: # Get input command from user if session and gtff.USE_PROMPT_TOOLKIT: completer = NestedCompleter.from_nested_dict( {c: None for c in fmp_controller.CHOICES} ) an_input = session.prompt( f"{get_flair()} (fa)>(fmp)> ", completer=completer, ) else: an_input = input(f"{get_flair()} (fa)>(fmp)> ") try: process_input = fmp_controller.switch(an_input) if process_input is not None: return process_input except SystemExit: print("The command selected doesn't exist\n") continue
""" Financial Modeling Prep Controller """ __docformat__ = "numpy" import argparse import os from typing import List from prompt_toolkit.completion import NestedCompleter from gamestonk_terminal.fundamental_analysis.financial_modeling_prep import fmp_view from gamestonk_terminal import feature_flags as gtff from gamestonk_terminal.helper_funcs import ( get_flair, ) from gamestonk_terminal.menu import session class FinancialModelingPrepController: """Financial Modeling Prep Controller""" # Command choices CHOICES = [ "cls", "?", "help", "q", "quit", "profile", "quote", "enterprise", "dcf", "income", "balance", "cash", "metrics", "ratios", "growth", ] def __init__(self, ticker: str, start: str, interval: str): """Constructor Parameters ---------- ticker : str Fundamental analysis ticker symbol start : str Stat date of the stock data interval : str Stock data interval """ self.ticker = ticker self.start = start self.interval = interval self.fmp_parser = argparse.ArgumentParser(add_help=False, prog="fmp") self.fmp_parser.add_argument( "cmd", choices=self.CHOICES, ) def print_help(self): """Print help""" print( "https://github.com/GamestonkTerminal/GamestonkTerminal/" "tree/main/gamestonk_terminal/fundamental_analysis/financial_modeling_prep" ) intraday = (f"Intraday {self.interval}", "Daily")[self.interval == "1440min"] if self.start: print( f"\n{intraday} Stock: {self.ticker} (from {self.start.strftime('%Y-%m-%d')})" ) else: print(f"\n{intraday} Stock: {self.ticker}") print("\nFinancial Modeling Prep API") print(" cls clear screen") print(" ?/help show this menu again") print(" q quit this menu, and shows back to main menu") print(" quit quit to abandon program") print("") print(" profile profile of the company") print(" quote quote of the company") print(" enterprise enterprise value of the company over time") print(" dcf discounted cash flow of the company over time") print(" income income statements of the company") print(" balance balance sheet of the company") print(" cash cash flow statement of the company") print(" metrics key metrics of the company") print(" ratios financial ratios of the company") print(" growth financial statement growth of the company") print("") def switch(self, an_input: str): """Process and dispatch input Returns ------- True, False or None False - quit the menu True - quit the program None - continue in the menu """ # Empty command if not an_input: print("") return None (known_args, other_args) = self.fmp_parser.parse_known_args(an_input.split()) # Help menu again if known_args.cmd == "?": self.print_help() return None # Clear screen if known_args.cmd == "cls": os.system("cls||clear") return None return getattr( self, "call_" + known_args.cmd, lambda: "Command not recognized!" )(other_args) def call_help(self, _): """Process Help command""" self.print_help() def call_q(self, _): """Process Q command - quit the menu""" return False def call_quit(self, _): """Process Quit command - quit the program""" return True def call_profile(self, other_args: List[str]): """Process profile command""" fmp_view.profile(other_args, self.ticker) def call_quote(self, other_args: List[str]): """Process quote command""" fmp_view.quote(other_args, self.ticker) def call_enterprise(self, other_args: List[str]): """Process income command""" fmp_view.enterprise(other_args, self.ticker) def call_dcf(self, other_args: List[str]): """Process dcf command""" fmp_view.discounted_cash_flow(other_args, self.ticker) def call_income(self, other_args: List[str]): """Process income command""" fmp_view.income_statement(other_args, self.ticker) def call_balance(self, other_args: List[str]): """Process balance command""" fmp_view.balance_sheet(other_args, self.ticker) def call_cash(self, other_args: List[str]): """Process cash command""" fmp_view.cash_flow(other_args, self.ticker) def call_metrics(self, other_args: List[str]): """Process metrics command""" fmp_view.key_metrics(other_args, self.ticker) def call_ratios(self, other_args: List[str]): """Process cash command""" fmp_view.financial_ratios(other_args, self.ticker) def call_growth(self, other_args: List[str]): """Process cash command""" fmp_view.financial_statement_growth(other_args, self.ticker) def menu(ticker: str, start: str, interval: str): """Financial Modeling Prep menu Parameters ---------- ticker : str Fundamental analysis ticker symbol start : str Start date of the stock data interval : str Stock data interval """ fmp_controller = FinancialModelingPrepController(ticker, start, interval) fmp_controller.call_help(None) while True: # Get input command from user if session and gtff.USE_PROMPT_TOOLKIT: completer = NestedCompleter.from_nested_dict( {c: None for c in fmp_controller.CHOICES} ) an_input = session.prompt( f"{get_flair()} (fa)>(fmp)> ", completer=completer, ) else: an_input = input(f"{get_flair()} (fa)>(fmp)> ") try: process_input = fmp_controller.switch(an_input) if process_input is not None: return process_input except SystemExit: print("The command selected doesn't exist\n") continue
from generallibrary import match, replace, deco_cache from urllib.parse import quote class Path_Strings: """ String operations for Path. """ def __getitem__(self, item): """ Get character from path string. :param generalfile.Path self: """ return self.Path(self.path.__getitem__(item)) @deco_cache() def to_alternative(self): """ Get path using alternative delimiter and alternative root for windows. :param generalfile.Path self: :rtype: generalfile.Path """ return self.Path(replace(string=self.path, **self._alternative_chars)) @deco_cache() def from_alternative(self): """ Get path from an alternative representation with or without leading lock dir. :param generalfile.Path self: :rtype: generalfile.Path """ path = str(self.remove_start(self.get_lock_dir())) return self.Path(replace(string=path, reverse=True, **self._alternative_chars)) def absolute(self): """ Get new Path as absolute. :param generalfile.Path self: :rtype: generalfile.Path """ if self.is_absolute(): return self else: return self.get_working_dir() / self def relative(self, base=None): """ Get new Path as relative, uses working dir if base is None. Returns self if not inside base. :param generalfile.Path self: :param base: Defaults to working dir. """ if self.is_relative() and (base is None or not self.startswith(base)): return self else: if base is None: base = self.get_working_dir() try: return self.Path() if self == base else self.Path(self._path.relative_to(base)) except ValueError: return None @deco_cache() def is_absolute(self): """ Get whether this Path is absolute. :param generalfile.Path self: """ return self._path.is_absolute() @deco_cache() def is_relative(self): """ Get whether this Path is relative. :param generalfile.Path self: """ return not self.is_absolute() @deco_cache() def mirror_path(self): """ Return mirror Path which currently points to same destination based on working dir. Absolute Path returns relative Path and vice versa. :param generalfile.Path self: :rtype: generalfile.Path """ if self.is_absolute(): return self.relative() else: return self.absolute() @deco_cache() def startswith(self, path): """ Get whether this Path starts with given string. :param generalfile.Path self: :param str or Path path:""" path = self.Path(path) return self.path.startswith(str(path)) @deco_cache() def endswith(self, path): """ Get whether this Path ends with given string. :param generalfile.Path self: :param str or Path path:""" path = self.Path(path) return self.path.endswith(str(path)) @deco_cache() def remove_start(self, path): """ Remove a string from the start of this Path if it exists. :param generalfile.Path self: :param str or Path path:""" path = self.Path(path) str_path = str(path) if not self.startswith(str_path): return self else: new_path = self.Path(self.path[len(str_path):]) if str(new_path).startswith(path.path_delimiter): return new_path[1:] else: return new_path @deco_cache() def remove_end(self, path): """ Remove a string from the end of this Path if it exists. :param generalfile.Path self: :param str or Path path:""" path = self.Path(path) str_path = str(path) if not self.endswith(str_path): return self else: new_path = self.Path(self.path[:-len(str_path)]) if str(new_path).endswith(path.path_delimiter): return new_path[:-1] else: return new_path def same_destination(self, path): """ See if two paths point to the same destination. :param generalfile.Path self: :param str or Path path:""" path = self.Path(path) return self.absolute() == path.absolute() @deco_cache() def parts(self): """ Split path using it's delimiter. With an absolute path the first index is an empty string on a posix system. <- Not sure about that anymore, might be / :param generalfile.Path self: """ return self.path.split(self.path_delimiter) @deco_cache() def name(self): """ Get string name of Path which is stem + suffix, or entire path if root. :param generalfile.Path self: """ return self.path if self.is_root() else self._path.name @deco_cache() def with_name(self, name): """ Get a new Path with new name which is stem + suffix. :param name: Name. :param generalfile.Path self: :rtype: generalfile.Path """ return self.Path(self._path.with_name(str(name))) @deco_cache() def stem(self): """ Get stem which is name without last suffix. :param generalfile.Path self: """ return self._path.stem @deco_cache() def with_stem(self, stem): """ Get a new Path with new stem which is name without last suffix. :param stem: New stem. :param generalfile.Path self: :rtype: generalfile.Path """ return self.Path(self.with_name(f"{stem}{self.suffix()}")) @deco_cache() def true_stem(self): """ Get true stem which is name without any suffixes. :param generalfile.Path self: """ return self._path.stem.split(".")[0] @deco_cache() def with_true_stem(self, true_stem): """ Get a new Path with new stem which is name without any suffixes. :param true_stem: New true stem. :param generalfile.Path self: :rtype: generalfile.Path """ return self.Path(self.with_name(f"{true_stem}{"".join(self.suffixes())}")) @deco_cache() def suffix(self): """ Get suffix which is name without stem. Empty string if missing. :param generalfile.Path self: """ return self._path.suffix @deco_cache() def with_suffix(self, suffix, index=-1): """ Get a new Path with a new suffix at any index. Index is automatically clamped if it's outside index range. Set suffix to `None` to remove a suffix. :param generalfile.Path self: :param suffix: New suffix, can be `None`. :param index: Suffix index to alter. :rtype: generalfile.Path """ suffixes = self.suffixes().copy() try: suffixes[index] except IndexError: if index >= len(suffixes): if not suffix: if suffixes: del suffixes[-1] else: suffixes.append(suffix) else: if not suffix: if suffixes: del suffixes[0] else: suffixes.insert(0, suffix) else: if not suffix: del suffixes[index] else: suffixes[index] = suffix return self.with_name(f"{self.true_stem()}{"".join(suffixes)}") @deco_cache() def suffixes(self): """ Get every suffix as a list. :param generalfile.Path self: """ return self._path.suffixes @deco_cache() def with_suffixes(self, *suffixes): """ Get a new Path with a new list of suffixes. :param str suffixes: New suffixes :param generalfile.Path self: :rtype: generalfile.Path """ return self.Path(self.with_name(f"{self.true_stem()}{"".join(suffixes)}")) @deco_cache() def match(self, *patterns): """ Get whether this Path matches any given filter line. :param generalfile.Path self: """ return match(self.path, *map(self._replace_delimiters, patterns)) @deco_cache() def encode(self): """ Return a URL encoded string from this Path. :param generalfile.Path self: """ url = self.path.replace("\\", "/") return quote(url)
from generallibrary import match, replace, deco_cache from urllib.parse import quote class Path_Strings: """ String operations for Path. """ def __getitem__(self, item): """ Get character from path string. :param generalfile.Path self: """ return self.Path(self.path.__getitem__(item)) @deco_cache() def to_alternative(self): """ Get path using alternative delimiter and alternative root for windows. :param generalfile.Path self: :rtype: generalfile.Path """ return self.Path(replace(string=self.path, **self._alternative_chars)) @deco_cache() def from_alternative(self): """ Get path from an alternative representation with or without leading lock dir. :param generalfile.Path self: :rtype: generalfile.Path """ path = str(self.remove_start(self.get_lock_dir())) return self.Path(replace(string=path, reverse=True, **self._alternative_chars)) def absolute(self): """ Get new Path as absolute. :param generalfile.Path self: :rtype: generalfile.Path """ if self.is_absolute(): return self else: return self.get_working_dir() / self def relative(self, base=None): """ Get new Path as relative, uses working dir if base is None. Returns self if not inside base. :param generalfile.Path self: :param base: Defaults to working dir. """ if self.is_relative() and (base is None or not self.startswith(base)): return self else: if base is None: base = self.get_working_dir() try: return self.Path() if self == base else self.Path(self._path.relative_to(base)) except ValueError: return None @deco_cache() def is_absolute(self): """ Get whether this Path is absolute. :param generalfile.Path self: """ return self._path.is_absolute() @deco_cache() def is_relative(self): """ Get whether this Path is relative. :param generalfile.Path self: """ return not self.is_absolute() @deco_cache() def mirror_path(self): """ Return mirror Path which currently points to same destination based on working dir. Absolute Path returns relative Path and vice versa. :param generalfile.Path self: :rtype: generalfile.Path """ if self.is_absolute(): return self.relative() else: return self.absolute() @deco_cache() def startswith(self, path): """ Get whether this Path starts with given string. :param generalfile.Path self: :param str or Path path:""" path = self.Path(path) return self.path.startswith(str(path)) @deco_cache() def endswith(self, path): """ Get whether this Path ends with given string. :param generalfile.Path self: :param str or Path path:""" path = self.Path(path) return self.path.endswith(str(path)) @deco_cache() def remove_start(self, path): """ Remove a string from the start of this Path if it exists. :param generalfile.Path self: :param str or Path path:""" path = self.Path(path) str_path = str(path) if not self.startswith(str_path): return self else: new_path = self.Path(self.path[len(str_path):]) if str(new_path).startswith(path.path_delimiter): return new_path[1:] else: return new_path @deco_cache() def remove_end(self, path): """ Remove a string from the end of this Path if it exists. :param generalfile.Path self: :param str or Path path:""" path = self.Path(path) str_path = str(path) if not self.endswith(str_path): return self else: new_path = self.Path(self.path[:-len(str_path)]) if str(new_path).endswith(path.path_delimiter): return new_path[:-1] else: return new_path def same_destination(self, path): """ See if two paths point to the same destination. :param generalfile.Path self: :param str or Path path:""" path = self.Path(path) return self.absolute() == path.absolute() @deco_cache() def parts(self): """ Split path using it's delimiter. With an absolute path the first index is an empty string on a posix system. <- Not sure about that anymore, might be / :param generalfile.Path self: """ return self.path.split(self.path_delimiter) @deco_cache() def name(self): """ Get string name of Path which is stem + suffix, or entire path if root. :param generalfile.Path self: """ return self.path if self.is_root() else self._path.name @deco_cache() def with_name(self, name): """ Get a new Path with new name which is stem + suffix. :param name: Name. :param generalfile.Path self: :rtype: generalfile.Path """ return self.Path(self._path.with_name(str(name))) @deco_cache() def stem(self): """ Get stem which is name without last suffix. :param generalfile.Path self: """ return self._path.stem @deco_cache() def with_stem(self, stem): """ Get a new Path with new stem which is name without last suffix. :param stem: New stem. :param generalfile.Path self: :rtype: generalfile.Path """ return self.Path(self.with_name(f"{stem}{self.suffix()}")) @deco_cache() def true_stem(self): """ Get true stem which is name without any suffixes. :param generalfile.Path self: """ return self._path.stem.split(".")[0] @deco_cache() def with_true_stem(self, true_stem): """ Get a new Path with new stem which is name without any suffixes. :param true_stem: New true stem. :param generalfile.Path self: :rtype: generalfile.Path """ return self.Path(self.with_name(f"{true_stem}{''.join(self.suffixes())}")) @deco_cache() def suffix(self): """ Get suffix which is name without stem. Empty string if missing. :param generalfile.Path self: """ return self._path.suffix @deco_cache() def with_suffix(self, suffix, index=-1): """ Get a new Path with a new suffix at any index. Index is automatically clamped if it's outside index range. Set suffix to `None` to remove a suffix. :param generalfile.Path self: :param suffix: New suffix, can be `None`. :param index: Suffix index to alter. :rtype: generalfile.Path """ suffixes = self.suffixes().copy() try: suffixes[index] except IndexError: if index >= len(suffixes): if not suffix: if suffixes: del suffixes[-1] else: suffixes.append(suffix) else: if not suffix: if suffixes: del suffixes[0] else: suffixes.insert(0, suffix) else: if not suffix: del suffixes[index] else: suffixes[index] = suffix return self.with_name(f"{self.true_stem()}{''.join(suffixes)}") @deco_cache() def suffixes(self): """ Get every suffix as a list. :param generalfile.Path self: """ return self._path.suffixes @deco_cache() def with_suffixes(self, *suffixes): """ Get a new Path with a new list of suffixes. :param str suffixes: New suffixes :param generalfile.Path self: :rtype: generalfile.Path """ return self.Path(self.with_name(f"{self.true_stem()}{''.join(suffixes)}")) @deco_cache() def match(self, *patterns): """ Get whether this Path matches any given filter line. :param generalfile.Path self: """ return match(self.path, *map(self._replace_delimiters, patterns)) @deco_cache() def encode(self): """ Return a URL encoded string from this Path. :param generalfile.Path self: """ url = self.path.replace("\\", "/") return quote(url)
""" Defines the base class for optimizations as well as a certain amount of useful generic optimization tools. """ import abc import contextlib import copy import inspect import logging import pdb import sys import time import traceback import warnings from collections import OrderedDict, UserList, defaultdict, deque from collections.abc import Iterable from functools import partial, reduce from typing import Dict, List, Optional, Tuple, Union import numpy as np import aesara from aesara.assert_op import Assert, assert_op from aesara.configdefaults import config from aesara.graph import destroyhandler as dh from aesara.graph.basic import ( Apply, Constant, Variable, applys_between, io_toposort, nodes_constructed, ) from aesara.graph.features import Feature, NodeFinder from aesara.graph.fg import FunctionGraph, InconsistencyError from aesara.graph.op import Op from aesara.graph.utils import AssocList from aesara.misc.ordered_set import OrderedSet from aesara.utils import flatten _logger = logging.getLogger("aesara.graph.opt") _optimizer_idx = [0] class LocalMetaOptimizerSkipAssertionError(AssertionError): """This is an AssertionError, but instead of having the LocalMetaOptimizer print the error, it just skip that compilation. """ class GlobalOptimizer(abc.ABC): """A optimizer that can be applied to a `FunctionGraph` in order to transform it. It can represent an optimization or, in general, any kind of transformation one could apply to a `FunctionGraph`. """ @abc.abstractmethod def apply(self, fgraph): """Apply the optimization to a `FunctionGraph`. It may use all the methods defined by the `FunctionGraph`. If the `GlobalOptimizer` needs to use a certain tool, such as an `InstanceFinder`, it can do so in its `add_requirements` method. """ raise NotImplementedError() def optimize(self, fgraph, *args, **kwargs): """ This is meant as a shortcut for the following:: opt.add_requirements(fgraph) opt.apply(fgraph) """ self.add_requirements(fgraph) ret = self.apply(fgraph, *args, **kwargs) return ret def __call__(self, fgraph): """Optimize a `FunctionGraph`. This is the same as ``self.optimize(fgraph)``. """ return self.optimize(fgraph) def add_requirements(self, fgraph): """Add features to `fgraph` that are required to apply the optimization. For example:: fgraph.attach_feature(History()) fgraph.attach_feature(MyFeature()) # etc. """ def print_summary(self, stream=sys.stdout, level=0, depth=-1): name = getattr(self, "name", None) print( f"{" " * level}{self.__class__.__name__} {name} id={id(self)}", file=stream, ) @staticmethod def print_profile(stream, prof, level=0): if prof is not None: raise NotImplementedError( "The function print_profile must be overridden if the" " optimizer return profiling information." ) def __hash__(self): if not hasattr(self, "_optimizer_idx"): self._optimizer_idx = _optimizer_idx[0] _optimizer_idx[0] += 1 return self._optimizer_idx class FromFunctionOptimizer(GlobalOptimizer): """A `GlobalOptimizer` constructed from a given function.""" def __init__(self, fn, requirements=()): self.fn = fn self.requirements = requirements def apply(self, *args, **kwargs): return self.fn(*args, **kwargs) def add_requirements(self, fgraph): for req in self.requirements: req(fgraph) def print_summary(self, stream=sys.stdout, level=0, depth=-1): print(f"{" " * level}{self.apply} id={id(self)}", file=stream) def __call__(self, *args, **kwargs): return self.fn(*args, **kwargs) def __str__(self): return self.__name__ def optimizer(f): """Decorator for `FromFunctionOptimizer`.""" rval = FromFunctionOptimizer(f) rval.__name__ = f.__name__ return rval def inplace_optimizer(f): """Decorator for `FromFunctionOptimizer` that also adds the `DestroyHandler` features.""" dh_handler = dh.DestroyHandler requirements = (lambda fgraph: fgraph.attach_feature(dh_handler()),) rval = FromFunctionOptimizer(f, requirements) rval.__name__ = f.__name__ return rval class SeqOptimizer(GlobalOptimizer, UserList): """A `GlobalOptimizer` that applies a list of optimizers sequentially.""" @staticmethod def warn(exc, self, optimizer): """Default ``failure_callback`` for `SeqOptimizer`.""" _logger.error(f"SeqOptimizer apply {optimizer}") _logger.error("Traceback:") _logger.error(traceback.format_exc()) if config.on_opt_error == "raise": raise exc elif config.on_opt_error == "pdb": pdb.post_mortem(sys.exc_info()[2]) def __init__(self, *opts, failure_callback=None): """ Parameters ---------- *opts : The List of optimizers to be applied to a node failure_callback : callable or None Keyword only argument. A callback used when a failure happen during optimization. """ if len(opts) == 1 and isinstance(opts[0], (list, tuple)): opts = opts[0] super().__init__(opts) self.failure_callback = failure_callback def apply(self, fgraph): """Applies each `GlobalOptimizer` in ``self.data`` to `fgraph`.""" l = [] if fgraph.profile: validate_before = fgraph.profile.validate_time sub_validate_time = [validate_before] callbacks_before = fgraph.execute_callbacks_times.copy() else: sub_validate_time = [] callbacks_before = [] callback_before = fgraph.execute_callbacks_time nb_node_before = len(fgraph.apply_nodes) sub_profs = [] nb_nodes = [] self.pre_profile = ( self, l, -1, -1, nb_node_before, -1, sub_profs, sub_validate_time, nb_nodes, {}, ) try: for optimizer in self.data: try: nb_nodes_before = len(fgraph.apply_nodes) t0 = time.time() sub_prof = optimizer.optimize(fgraph) l.append(float(time.time() - t0)) sub_profs.append(sub_prof) nb_nodes.append((nb_nodes_before, len(fgraph.apply_nodes))) if fgraph.profile: sub_validate_time.append(fgraph.profile.validate_time) except AssertionError: # do not catch Assertion failures raise except Exception as e: if self.failure_callback: self.failure_callback(e, self, optimizer) continue else: raise finally: if fgraph.profile: validate_time = fgraph.profile.validate_time - validate_before callbacks_time = {} for k, v in fgraph.execute_callbacks_times.items(): if k in callbacks_before: t = v - callbacks_before[k] if t > 0: callbacks_time[k] = t else: callbacks_time[k] = v else: validate_time = None callbacks_time = {} callback_time = fgraph.execute_callbacks_time - callback_before self.pre_profile = ( self, l, validate_time, callback_time, nb_node_before, len(fgraph.apply_nodes), sub_profs, sub_validate_time, nb_nodes, callbacks_time, ) return self.pre_profile def __repr__(self): return f"SeqOpt({self.data})" def print_summary(self, stream=sys.stdout, level=0, depth=-1): name = getattr(self, "name", None) print( f"{" " * level}{self.__class__.__name__} {name} id={id(self)}", file=stream ) # This way, -1 will do all depth if depth != 0: depth -= 1 for opt in self.data: opt.print_summary(stream, level=(level + 2), depth=depth) @staticmethod def print_profile(stream, prof, level=0): ( opts, prof, validate_time, callback_time, nb_node_before, nb_node_after, sub_profs, sub_validate_time, nb_nodes, callbacks_time, ) = prof blanc = " " * level print(blanc, "SeqOptimizer", end=" ", file=stream) if hasattr(opts, "name"): print(blanc, opts.name, end=" ", file=stream) elif hasattr(opts, "__name__"): print(blanc, opts.__name__, end=" ", file=stream) print( ( f" time {sum(prof):.3f}s for {int(nb_node_before)}/{int(nb_node_after)} nodes" " before/after optimization" ), file=stream, ) print(blanc, f" {callback_time:.3f}s for callback", file=stream) print(blanc, f" {validate_time:.3f}s for fgraph.validate()", file=stream) if callback_time > 1: print(blanc, " callbacks_time", file=stream) for i in sorted(callbacks_time.items(), key=lambda a: -a[1]): if i[1] > 0: # We want to have the __str__ called, so we can't # just print i. print(blanc, " ", i[0], ",", i[1], file=stream) if level == 0: print( blanc, " time - (name, class, index, nodes before, nodes after) - validate time", file=stream, ) ll = [] for (opt, nb_n) in zip(opts, nb_nodes): if hasattr(opt, "__name__"): name = opt.__name__ else: name = opt.name idx = opts.index(opt) ll.append((name, opt.__class__.__name__, idx) + nb_n) lll = sorted(zip(prof, ll), key=lambda a: a[0]) for (t, opt) in lll[::-1]: i = opt[2] if sub_validate_time: val_time = sub_validate_time[i + 1] - sub_validate_time[i] print( blanc, f" {t:.6f}s - {opt} - {val_time:.3f}s", file=stream, ) else: print(blanc, f" {t:.6f}s - {opt}", file=stream) if sub_profs[i]: opts[i].print_profile(stream, sub_profs[i], level=level + 1) print(file=stream) @staticmethod def merge_profile(prof1, prof2): """Merge two profiles.""" new_t = [] # the time for the optimization new_l = [] # the optimization new_sub_profile = [] # merge common(same object) opt for l in set(prof1[0]).intersection(set(prof2[0])): idx1 = prof1[0].index(l) idx2 = prof2[0].index(l) new_t.append(prof1[1][idx1] + prof2[1][idx2]) new_l.append(l) if hasattr(l, "merge_profile"): assert len(prof1[6][idx1]) == len(prof2[6][idx2]) new_sub_profile.append(l.merge_profile(prof1[6][idx1], prof2[6][idx2])) else: new_sub_profile.append(None) # merge not common opt from io import StringIO for l in set(prof1[0]).symmetric_difference(set(prof2[0])): # The set trick above only work for the same object optimization # It don't work for equivalent optimization. # So we try to merge equivalent optimization here. new_l_names = [o.name for o in new_l] if l.name in new_l_names: idx = new_l_names.index(l.name) io1 = StringIO() io2 = StringIO() l.print_summary(io1) new_l[idx].print_summary(io2) if io1.read() == io2.read(): if l in prof1[0]: p = prof1 else: p = prof2 new_t[idx] += p[1][p[0].index(l)] if hasattr(l, "merge_profile"): assert len(p[6][p[0].index(l)]) == len(new_sub_profile[idx]) new_sub_profile[idx] = l.merge_profile( new_sub_profile[idx], p[6][p[0].index(l)] ) else: new_sub_profile[idx] = None continue if l in prof1[0]: p = prof1 else: p = prof2 new_t.append(p[1][p[0].index(l)]) idx = p[0].index(l) new_l.append(l) new_sub_profile.append(p[6][idx]) new_opt = SeqOptimizer(*new_l) new_nb_nodes = [] for p1, p2 in zip(prof1[8], prof2[8]): new_nb_nodes.append((p1[0] + p2[0], p1[1] + p2[1])) new_nb_nodes.extend(prof1[8][len(new_nb_nodes) :]) new_nb_nodes.extend(prof2[8][len(new_nb_nodes) :]) new_callbacks_times = merge_dict(prof1[9], prof2[9]) # We need to assert based on the name as we merge also based on # the name. assert {l.name for l in prof1[0]}.issubset({l.name for l in new_l}) assert {l.name for l in prof2[0]}.issubset({l.name for l in new_l}) assert len(new_t) == len(new_opt) == len(new_sub_profile) return ( new_opt, new_t, prof1[2] + prof2[2], prof1[3] + prof2[3], -1, -1, new_sub_profile, [], new_nb_nodes, new_callbacks_times, ) class MergeFeature(Feature): """Keeps track of variables in a `FunctionGraph` that cannot be merged together. That way, the `MergeOptimizer` can remember the result of the last merge-pass on the `FunctionGraph`. """ def on_attach(self, fgraph): assert not hasattr(fgraph, "merge_feature") fgraph.merge_feature = self # For constants self.seen_constants = set() # variable -> signature (for constants) self.const_sig = AssocList() # signature -> variable (for constants) self.const_sig_inv = AssocList() # For all Apply nodes # Set of distinct (not mergeable) nodes self.nodes_seen = set() # Ordered set of distinct (not mergeable) nodes without any input self.noinput_nodes = OrderedSet() # Each element of scheduled is a list of list of (out, new_out) pairs. # Each list of pairs represent the substitution needed to replace all # the outputs of a node with the outputs of a replacement candidate. # Each node can have several candidates. For instance, if "node" has # 2 outputs, and there are 3 replacement candidates, we will have: # shelf.scheduled = [ # [[(node.out1, cand1.out1), (node.out2, cand1.out2)], # [(node.out1, cand2.out1), (node.out2, cand2.out2)], # [(node.out1, cand3.out1), (node.out2, cand3.out2)]]] self.scheduled = [] # List of (node, candidate) pairs, where we tried to replace node by # candidate, but it failed. This is used to avoid infinite loops # during the replacement phase. self.blacklist = [] for node in fgraph.toposort(): self.on_import(fgraph, node, "on_attach") def on_change_input(self, fgraph, node, i, r, new_r, reason): # If inputs to node change, it is not guaranteed that it is distinct # from the other nodes in nodes_seen if node in self.nodes_seen: self.nodes_seen.discard(node) self.process_node(fgraph, node) # Since we are in on_change_input, node should have inputs. if not isinstance(node, str): assert node.inputs if isinstance(new_r, Constant): self.process_constant(fgraph, new_r) def on_import(self, fgraph, node, reason): for c in node.inputs: if isinstance(c, Constant): self.process_constant(fgraph, c) self.process_node(fgraph, node) def on_prune(self, fgraph, node, reason): self.nodes_seen.discard(node) if not node.inputs: self.noinput_nodes.discard(node) for c in node.inputs: if isinstance(c, Constant) and (len(fgraph.clients[c]) <= 1): # This was the last node using this constant sig = self.const_sig[c] self.const_sig.discard(c) self.const_sig_inv.discard(sig) self.seen_constants.discard(id(c)) def process_constant(self, fgraph, c): """Check if a constant `c` can be merged, and queue that replacement.""" if id(c) in self.seen_constants: return sig = c.merge_signature() other_c = self.const_sig_inv.get(sig, None) if other_c is not None: # multiple names will clobber each other.. # we adopt convention to keep the last name if c.name: other_c.name = c.name self.scheduled.append([[(c, other_c, "merge")]]) else: # this is a new constant self.const_sig[c] = sig self.const_sig_inv[sig] = c self.seen_constants.add(id(c)) def process_node(self, fgraph, node): """Check if a `node` can be merged, and queue that replacement.""" if node in self.nodes_seen: return node_has_assert = False # These asserts ensure that the fgraph has set the clients field # properly. # The clients should at least contain `node` itself! if node.inputs: # Take the smallest clients list. Some ops like elemwise # have optimization that put constant as the first inputs. # As constant have in general more clients than other type of nodes # using always inputs[0] make us look at more nodes. # Always pick the smallest clints list between inputs 0 # and -1 speed up optimization. a_clients = fgraph.clients[node.inputs[0]] b_clients = fgraph.clients[node.inputs[-1]] if len(a_clients) < len(b_clients): clients = a_clients else: clients = b_clients assert len(clients) > 0 merge_candidates = [c for c, i in clients if c in self.nodes_seen] # Put all clients of Assert inputs (if exist) into merge_candidates # TODO: Deactivated for now as this cause cycle in the graph. # (There is a second deactivation part below.) for i in []: # node.inputs: if i.owner and isinstance(i.owner.op, Assert): node_has_assert = True i_clients = fgraph.clients[i.owner.inputs[0]] assert_clients = [c for (c, _) in i_clients if c in self.nodes_seen] for idx in range(len(assert_clients)): client = assert_clients[idx] if isinstance(i.owner.op, Assert): o_clients = fgraph.clients[client.outputs[0]] for c in o_clients: if c[0] in self.nodes_seen: assert_clients.append(c[0]) merge_candidates.extend(assert_clients) else: # If two nodes have no input, but perform the same operation, # they are not always constant-folded, so we want to merge them. # In that case, the candidates are all the nodes without inputs. merge_candidates = self.noinput_nodes replacement_candidates = [] for candidate in merge_candidates: if candidate is node: continue if len(node.inputs) != len(candidate.inputs): continue cand_has_assert = False # Get input list of the candidate with assert removed cand_inputs_assert_removed = [] # TODO: Deactivated while Assert merging is disabled. (See above and below.) for i in []: # candidate.inputs: if i.owner and isinstance(i.owner.op, Assert): cand_has_assert = True cand_inputs_assert_removed.append(i.owner.inputs[0]) else: cand_inputs_assert_removed.append(i) # TODO: Remove this when Assert merging is re-enabled. (See above.) # Without Assert merging we can still look for identical Asserts, # so we should not treat Asserts separately for now. cand_inputs_assert_removed = candidate.inputs # Get input list of the node with assert removed if node_has_assert: node_inputs_assert_removed = [] for i in node.inputs: if i.owner and isinstance(i.owner.op, Assert): node_inputs_assert_removed.append(i.owner.inputs[0]) else: node_inputs_assert_removed.append(i) else: node_inputs_assert_removed = node.inputs inputs_match = all( node_in is cand_in for node_in, cand_in in zip( node_inputs_assert_removed, cand_inputs_assert_removed ) ) if inputs_match and node.op == candidate.op: if (node, candidate) in self.blacklist: # They were already tried, and there was an error continue # replace node with candidate if not (node_has_assert or cand_has_assert): # Schedule transfer of clients from node to candidate pairs = list( zip( node.outputs, candidate.outputs, ["merge"] * len(node.outputs), ) ) # if the current node has assert input, it should not be # replaced with a candidate node which has no assert input elif node_has_assert and not cand_has_assert: pairs = list( zip( candidate.outputs, node.outputs, ["merge"] * len(node.outputs), ) ) else: new_inputs = self.get_merged_assert_input(node, candidate) new_node = node.op(*new_inputs) pairs = list( zip( node.outputs, new_node.owner.outputs, ["new_node"] * len(node.outputs), ) ) + list( zip( candidate.outputs, new_node.owner.outputs, ["new_node"] * len(node.outputs), ) ) # transfer names for pair in pairs: node_output, cand_output = pair[:2] # clobber old name with new one # it's arbitrary... one of the names has to go if node_output.name: cand_output.name = node_output.name replacement_candidates.append(pairs) if replacement_candidates: self.scheduled.append(replacement_candidates) else: self.nodes_seen.add(node) if not node.inputs: self.noinput_nodes.add(node) def get_merged_assert_input(self, node, candidate): new_inputs = [] for node_i, cand_i in zip(node.inputs, candidate.inputs): # if node_i is assert if node_i.owner and isinstance(node_i.owner.op, Assert): # node_i is assert, cand_i is assert if cand_i.owner and isinstance(cand_i.owner.op, Assert): # Here two assert nodes are merged. # Step 1. Merge conditions of both assert nodes. # Step 2. Make the new assert node node_cond = node_i.owner.inputs[1:] cand_cond = cand_i.owner.inputs[1:] new_cond = list(set(node_cond + cand_cond)) new_inputs.append(assert_op(node_i.owner.inputs[0], *new_cond)) # node_i is assert, cand_i is not assert else: new_inputs.append(node_i) else: # if node_i is not an assert node, append cand_i new_inputs.append(cand_i) return new_inputs class MergeOptimizer(GlobalOptimizer): r"""Merges parts of the graph that are identical and redundant. The basic principle is that if two `Apply`\s have `Op`\s that compare equal, and identical inputs, then they do not both need to be computed. The clients of one are transferred to the other and one of them is removed from the graph. This procedure is carried out in input-to-output order throughout the graph. The first step of merging is constant-merging, so that all clients of an ``int(1)`` for example, are transferred to just one particular instance of ``int(1)``. """ def add_requirements(self, fgraph): if not hasattr(fgraph, "merge_feature"): fgraph.attach_feature(MergeFeature()) def apply(self, fgraph): # Constant and non-constant are now applied in the same phase. # I am not sure why, but it seems to be faster this way. sched = fgraph.merge_feature.scheduled nb_fail = 0 t0 = time.time() if fgraph.profile: validate_before = fgraph.profile.validate_time callback_before = fgraph.execute_callbacks_time callbacks_before = fgraph.execute_callbacks_times.copy() nb_merged = 0 nb_constant = 0 while sched: pairs_list = sched.pop() success = True for pairs_ in pairs_list: # We must check again the equivalence, as the graph # could've changed. If so, doing the replacement can # introduce a node that depends on itself. Doing the # full check of such cycles every time is very time # consuming. I think this double check is faster than # doing the full cycle check. The full cycle check is # skipped by validate() if the graph doesn't contain # destroyers. var, candidate, merge_mode = pairs_[0] if merge_mode == "new_node" and var in fgraph.variables: pass elif var not in fgraph.variables or candidate not in fgraph.variables: continue # Keep len(item) == 2 for item in pairs pairs = [pair[:2] for pair in pairs_] if var.owner and candidate.owner: node = var.owner candidate = candidate.owner # Get input list of the candidate node with assert # nodes removed cand_inputs_assert_removed = [] for i in candidate.inputs: if i.owner and isinstance(i.owner.op, Assert): cand_inputs_assert_removed.append(i.owner.inputs[0]) else: cand_inputs_assert_removed.append(i) # Get input list of the node with assert nodes removed node_inputs_assert_removed = [] for i in node.inputs: if i.owner and isinstance(i.owner.op, Assert): node_inputs_assert_removed.append(i.owner.inputs[0]) else: node_inputs_assert_removed.append(i) if merge_mode == "new_node": inputs_match = True else: inputs_match = all( node_in is cand_in for node_in, cand_in in zip( node_inputs_assert_removed, cand_inputs_assert_removed ) ) # No need to compare the op again, as it don't change. if not inputs_match: continue if hasattr(fgraph, "destroy_handler"): # If both nodes have clients that destroy them, we # can't merge them. clients = ( fgraph.clients[pairs[0][0]] + fgraph.clients[pairs[0][1]] ) if ( sum( [ i in flatten(c.op.destroy_map.values()) for c, i in clients if c != "output" and c.op.destroy_map ] ) > 1 ): continue if len(pairs) == 1 and pairs[0][0].type != pairs[0][1].type: res = pairs[0][0].type.convert_variable(pairs[0][1]) # Since the fgraph.replace only checks the convert_variable # in one way, we change the order in the case that # convert_variable will not be successful. if not res: pairs = [(pairs[0][1], pairs[0][0])] try: # If all Constants, no need to call validate. # Only need to check one of the var of each pairs. # If it is a Constant, the other must also be a Constant as we merge them. if all([isinstance(old, Constant) for old, new in pairs]): fgraph.replace_all(pairs, reason="MergeOptimizer") else: fgraph.replace_all_validate(pairs, reason="MergeOptimizer") except InconsistencyError: success = False nb_fail += 1 fgraph.merge_feature.blacklist.append( (pairs[0][0].owner, pairs[0][1].owner) ) if success: nb_merged += len(pairs) if isinstance(pairs[0][0], Constant): nb_constant += 1 # print pairs, pairs[0][0].type break if fgraph.profile: validate_time = fgraph.profile.validate_time - validate_before callback_time = fgraph.execute_callbacks_time - callback_before callbacks_time = {} for k, v in fgraph.execute_callbacks_times.items(): if k in callbacks_before: t = v - callbacks_before[k] if t > 0: callbacks_time[k] = t else: callbacks_time[k] = v else: validate_time = None callback_time = None callbacks_time = {} # clear blacklist fgraph.merge_feature.blacklist = [] return ( nb_fail, time.time() - t0, validate_time, callback_time, callbacks_time, nb_merged, nb_constant, ) def __str__(self): return self.__class__.__name__ @staticmethod def print_profile(stream, prof, level=0): ( nb_fail, replace_time, validate_time, callback_time, callbacks_time, nb_merged, nb_constant, ) = prof blanc = " " * level print(blanc, "MergeOptimizer", file=stream) print( blanc, f" nb fail={nb_fail:5d} merged={nb_merged:5d} constant={nb_constant:5d}", file=stream, ) print( blanc, f" time replace={replace_time:2.2f} validate={validate_time:2.2f} callback={callback_time:2.2f}", file=stream, ) if callback_time > 1: print(blanc, " callbacks_time", file=stream) for i in sorted(callbacks_time.items(), key=lambda a: a[1]): if i[1] > 0: # We want to have the __str__ called, so we can't # just print i. print(blanc, " ", i[0], ",", i[1], file=stream) @staticmethod def merge_profile(prof1, prof2): def merge_none_number(v1, v2): if v1 is None: return v2 if v2 is None: return v1 return v1 + v2 nb_fail = prof1[0] + prof2[0] replace_time = prof1[1] + prof2[1] validate_time = merge_none_number(prof1[2], prof2[2]) callback_time = merge_none_number(prof1[3], prof2[3]) callbacks_time = merge_dict(prof1[4], prof2[4]) nb_merged = prof1[5] + prof2[5] nb_constant = prof1[6] + prof2[6] return ( nb_fail, replace_time, validate_time, callback_time, callbacks_time, nb_merged, nb_constant, ) def pre_constant_merge(fgraph, variables): """Merge constants in the graphs given by `variables`. .. warning:: This changes the nodes in a graph in-place! Parameters ---------- fgraph A `FunctionGraph` instance in which some of these `variables` may reside. We want to avoid terms in `variables` that are contained in `fgraph`. The reason for that: it will break consistency of `fgraph` and its features (e.g. `ShapeFeature`). variables A list of nodes for which we want to merge constant inputs. Notes ----- It is used to pre-merge nodes generated inside an optimization. It is useful if there are many such replacements to make, so that `DebugMode` will not check each of them. """ seen_var = set() # signature -> variable (for constants) const_sig_inv = {} if isinstance(variables, Variable): variables = [variables] def recursive_merge(var): if var in seen_var: return var if not hasattr(var, "owner"): return var # We don't want to merge constants that are *within* the # `FunctionGraph` if var.owner in fgraph.apply_nodes: return var seen_var.add(var) if isinstance(var, Constant): sig = var.signature() if sig in const_sig_inv: return const_sig_inv[sig] const_sig_inv[sig] = var return var if var.owner: for idx, inp in enumerate(var.owner.inputs): # XXX: This is changing the graph in place! var.owner.inputs[idx] = recursive_merge(inp) return var return [recursive_merge(v) for v in variables] class LocalOptimizer(abc.ABC): """A node-based optimizer.""" def __hash__(self): if not hasattr(self, "_optimizer_idx"): self._optimizer_idx = _optimizer_idx[0] _optimizer_idx[0] += 1 return self._optimizer_idx def tracks(self): """Return the list of `Op` classes to which this optimization applies. Returns ``None`` when the optimization applies to all nodes. """ return None @abc.abstractmethod def transform( self, fgraph: FunctionGraph, node: Apply, *args, **kwargs ) -> Union[bool, List[Variable], Dict[Variable, Variable]]: r"""Transform a subgraph whose output is `node`. Subclasses should implement this function so that it returns one of the following: - ``False`` to indicate that no optimization can be applied to this `node`; - A list of `Variable`\s to use in place of the `node`'s current outputs. - A ``dict`` mapping old `Variable`\s to `Variable`\s. Parameters ---------- fgraph : A `FunctionGraph` containing `node`. node : An `Apply` node to be transformed. """ raise NotImplementedError() def add_requirements(self, fgraph): r"""Add required `Feature`\s to `fgraph`.""" def print_summary(self, stream=sys.stdout, level=0, depth=-1): print(f"{" " * level}{self.__class__.__name__} id={id(self)}", file=stream) class LocalMetaOptimizer(LocalOptimizer): r""" Base class for meta-optimizers that try a set of `LocalOptimizer`\s to replace a node and choose the one that executes the fastest. If the error ``LocalMetaOptimizerSkipAssertionError`` is raised during compilation, we will skip that function compilation and not print the error. """ def __init__(self): self.verbose = config.metaopt__verbose self.track_dict = defaultdict(lambda: []) self.tag_dict = defaultdict(lambda: []) self._tracks = [] self.optimizers = [] def register(self, optimizer, tag_list): self.optimizers.append(optimizer) for c in optimizer.tracks(): self.track_dict[c].append(optimizer) self._tracks.append(c) for tag in tag_list: self.tag_dict[tag].append(optimizer) def tracks(self): return self._tracks def transform(self, fgraph, node, *args, **kwargs): # safety check: depending on registration, tracks may have been ignored if self._tracks is not None: if not isinstance(node.op, tuple(self._tracks)): return # first, we need to provide dummy values for all inputs # to the node that are not shared variables anyway givens = {} missing = set() for input in node.inputs: if isinstance(input, aesara.compile.SharedVariable): pass elif hasattr(input.tag, "test_value"): givens[input] = aesara.shared( input.type.filter(input.tag.test_value), input.name, broadcastable=input.broadcastable, borrow=True, ) else: missing.add(input) if missing: givens.update(self.provide_inputs(node, missing)) missing.difference_update(givens.keys()) # ensure we have data for all input variables that need it if missing: if self.verbose > 0: print( f"{self.__class__.__name__} cannot meta-optimize {node}, " f"{len(missing)} of {int(node.nin)} input shapes unknown" ) return # now we can apply the different optimizations in turn, # compile the resulting subgraphs and time their execution if self.verbose > 1: print( f"{self.__class__.__name__} meta-optimizing {node} ({len(self.get_opts(node))} choices):" ) timings = [] for opt in self.get_opts(node): outputs = opt.transform(fgraph, node, *args, **kwargs) if outputs: try: fn = aesara.function( [], outputs, givens=givens, on_unused_input="ignore" ) fn.trust_input = True timing = min(self.time_call(fn) for _ in range(2)) except LocalMetaOptimizerSkipAssertionError: continue except Exception as e: if self.verbose > 0: print(f"* {opt}: exception", e) continue else: if self.verbose > 1: print(f"* {opt}: {timing:.5g} sec") timings.append((timing, outputs, opt)) else: if self.verbose > 0: print(f"* {opt}: not applicable") # finally, we choose the fastest one if timings: timings.sort() if self.verbose > 1: print(f"= {timings[0][2]}") return timings[0][1] return def provide_inputs(self, node, inputs): """Return a dictionary mapping some `inputs` to `SharedVariable` instances of with dummy values. The `node` argument can be inspected to infer required input shapes. """ raise NotImplementedError() def get_opts(self, node): """Return the optimizations that apply to `node`. This uses ``self.track_dict[type(node.op)]`` by default. """ return self.track_dict[type(node.op)] def time_call(self, fn): start = time.time() fn() return time.time() - start class FromFunctionLocalOptimizer(LocalOptimizer): """A `LocalOptimizer` constructed from a function.""" def __init__(self, fn, tracks=None, requirements=()): self.fn = fn self._tracks = tracks self.requirements = requirements def transform(self, *args, **kwargs): return self.fn(*args, **kwargs) def add_requirements(self, fgraph): for req in self.requirements: req(fgraph) def tracks(self): return self._tracks def __str__(self): return getattr(self, "__name__", "<FromFunctionLocalOptimizer instance>") def print_summary(self, stream=sys.stdout, level=0, depth=-1): print(f"{" " * level}{self.transform} id={id(self)}", file=stream) def local_optimizer( tracks: Optional[List[Union[Op, type]]], inplace: bool = False, requirements: Optional[Tuple[type, ...]] = (), ): r"""A decorator used to construct `FromFunctionLocalOptimizer` instances. Parameters ---------- tracks : The `Op` types or instances to which this optimization applies. inplace : A boolean indicating whether or not the optimization works in-place. If ``True``, a `DestroyHandler` `Feature` is added automatically added to the `FunctionGraph`\s applied to this optimization. requirements : `Feature` types required by this optimization. """ if requirements is None: requirements = () def decorator(f): if tracks is not None: if len(tracks) == 0: raise ValueError( "Use None instead of an empty list to apply to all nodes.", f.__module__, f.__name__, ) for t in tracks: if not (isinstance(t, Op) or issubclass(t, Op)): raise ValueError( "Tracks are op classes or instances", f.__module__, f.__name__ ) req = requirements if inplace: dh_handler = dh.DestroyHandler req = tuple(requirements) + ( lambda fgraph: fgraph.attach_feature(dh_handler()), ) rval = FromFunctionLocalOptimizer(f, tracks, req) rval.__name__ = f.__name__ return rval return decorator class LocalOptGroup(LocalOptimizer): r"""An optimizer that applies a list of `LocalOptimizer`\s to a node. Parameters ---------- optimizers : A list of optimizers to be applied to nodes. apply_all_opts : bool (Default False) If ``False``, it will return after the new node after the first optimizer applied. Otherwise, it will start again with the new node until no new optimization apply. profile : Whether or not to profile the optimizations. Attributes ---------- reentrant : bool Some global optimizer like `NavigatorOptimizer` can use this value to determine if it ignore new nodes during a pass on the nodes. Sometimes, ``ignore_newtrees`` is not reentrant. retains_inputs : bool States whether or not the inputs of a transformed node are transferred to the outputs. """ def __init__(self, *optimizers, apply_all_opts=False, profile=False): if len(optimizers) == 1 and isinstance(optimizers[0], list): # This happen when created by LocalGroupDB. optimizers = tuple(optimizers[0]) self.opts = optimizers assert isinstance(self.opts, tuple) self.reentrant = any(getattr(opt, "reentrant", True) for opt in optimizers) self.retains_inputs = all( getattr(opt, "retains_inputs", False) for opt in optimizers ) self.apply_all_opts = apply_all_opts self.profile = profile self.track_map = defaultdict(lambda: []) if self.profile: self.time_opts = {} self.process_count = {} self.applied_true = {} self.node_created = {} for o in self.opts: if self.profile: self.time_opts.setdefault(o, 0) self.process_count.setdefault(o, 0) self.applied_true.setdefault(o, 0) self.node_created.setdefault(o, 0) tracks = o.tracks() if tracks is None: self.track_map[None].append(o) else: for c in tracks: self.track_map[c].append(o) def __str__(self): return getattr( self, "__name__", f"LocalOptGroup({",".join([str(o) for o in self.opts])})", ) def tracks(self): t = [] for l in self.opts: aet = l.tracks() if aet: t.extend(aet) return t def transform(self, fgraph, node): if len(self.opts) == 0: return repl = None while True: opts = ( self.track_map[type(node.op)] + self.track_map[node.op] + self.track_map[None] ) new_repl = None for opt in opts: opt_start = time.time() new_repl = opt.transform(fgraph, node) opt_finish = time.time() if self.profile: self.time_opts[opt] += opt_start - opt_finish self.process_count[opt] += 1 if not new_repl: continue if isinstance(new_repl, (tuple, list)): new_vars = new_repl else: # It must be a dict new_vars = list(new_repl.values()) if self.profile: self.node_created[opt] += len( list(applys_between(fgraph.variables, new_vars)) ) self.applied_true[opt] += 1 break # break from the for loop over optimization. if not new_repl: # No optimization applied in the last iteration return repl # only 1 iteration if not self.apply_all_opts: return new_repl if not new_vars[0].owner: # We are at the start of the graph. return new_repl if len(new_repl) > 1: s = {v.owner for v in new_repl} assert len(s) == 1 repl = new_repl node = new_vars[0].owner @staticmethod def print_profile(stream, prof, level=0): (time_opts, process_count, applied_true, node_created, profile) = prof if not profile: return blanc = " " * int(level) print(blanc, "LocalOptGroup", file=stream) print(blanc, "---------------------", file=stream) count_opt = [] not_used = [] not_used_time = 0 for o, count in process_count.items(): if count > 0: count_opt.append( (time_opts[o], applied_true[o], count, o, node_created[o]) ) else: not_used.append((time_opts[o], o)) not_used_time += time_opts[o] if count_opt: print( blanc, " time taken - times applied - times tried - name - node_created:", file=stream, ) count_opt.sort() for (t, a_t, count, o, n_c) in count_opt[::-1]: print( blanc, f" {t:.3f}s - {int(a_t)} - {int(count)} - {o} - {int(n_c)}", file=stream, ) print( blanc, f" {not_used_time:.3f}s - in {len(not_used)} optimization that were not used (display those with runtime greater than 0)", file=stream, ) not_used.sort(key=lambda nu: (nu[0], str(nu[1]))) for (t, o) in not_used[::-1]: if t > 0: # Skip opt that have 0 times, they probably wasn't even tried. print(blanc + " ", f" {t:.3f}s - {o}", file=stream) else: print(blanc, " The optimizer wasn't successful ", file=stream) print(file=stream) def merge_profile(prof1, prof2): raise NotImplementedError def print_summary(self, stream=sys.stdout, level=0, depth=-1): print(f"{" " * level}{self.__class__.__name__} id={id(self)}", file=stream) if depth != 0: depth -= 1 for lopt in self.opts: lopt.print_summary(stream, level=(level + 2), depth=depth) def add_requirements(self, fgraph): for opt in self.opts: opt.add_requirements(fgraph) class GraphToGPULocalOptGroup(LocalOptGroup): """This is the equivalent of `LocalOptGroup` for `GraphToGPU`. The main different is the function signature of the local optimizer that use the `GraphToGPU` signature and not the normal `LocalOptimizer` signature. ``apply_all_opts=True`` is not supported """ def __init__(self, *optimizers, **kwargs): super().__init__(*optimizers, **kwargs) assert self.apply_all_opts is False def transform(self, fgraph, op, context_name, inputs, outputs): if len(self.opts) == 0: return opts = self.track_map[type(op)] + self.track_map[op] + self.track_map[None] for opt in opts: opt_start = time.time() new_repl = opt.transform(fgraph, op, context_name, inputs, outputs) opt_finish = time.time() if self.profile: self.time_opts[opt] += opt_start - opt_finish self.process_count[opt] += 1 if not new_repl: continue if self.profile: self.node_created[opt] += len( list(applys_between(fgraph.variables, new_repl)) ) self.applied_true[opt] += 1 return new_repl class OpSub(LocalOptimizer): """ Replaces the application of a certain `Op` by the application of another `Op` that takes the same inputs as what it is replacing. Parameters ---------- op1, op2 ``op1.make_node`` and ``op2.make_node`` must take the same number of inputs and have the same number of outputs. Examples -------- OpSub(add, sub) ==> add(div(x, y), add(y, x)) -> sub(div(x, y), sub(y, x)) """ # an OpSub does not apply to the nodes it produces reentrant = False # all the inputs of the original node are transferred to the outputs retains_inputs = True def __init__(self, op1, op2, transfer_tags=True): self.op1 = op1 self.op2 = op2 self.transfer_tags = transfer_tags def op_key(self): return self.op1 def tracks(self): return [self.op1] def transform(self, fgraph, node): if node.op != self.op1: return False repl = self.op2.make_node(*node.inputs) if self.transfer_tags: repl.tag = copy.copy(node.tag) for output, new_output in zip(node.outputs, repl.outputs): new_output.tag = copy.copy(output.tag) return repl.outputs def __str__(self): return f"{self.op1} -> {self.op2}" class OpRemove(LocalOptimizer): """ Removes all applications of an `Op` by transferring each of its outputs to the corresponding input. """ reentrant = False # no nodes are added at all def __init__(self, op): self.op = op def op_key(self): return self.op def tracks(self): return [self.op] def transform(self, fgraph, node): if node.op != self.op: return False return node.inputs def __str__(self): return f"{self.op}(x) -> x" def print_summary(self, stream=sys.stdout, level=0, depth=-1): print( f"{" " * level}{self.__class__.__name__}(self.op) id={id(self)}", file=stream, ) class PatternSub(LocalOptimizer): """ @todo update Replaces all occurrences of the input pattern by the output pattern: input_pattern ::= (op, <sub_pattern1>, <sub_pattern2>, ...) input_pattern ::= dict(pattern = <input_pattern>, constraint = <constraint>) sub_pattern ::= input_pattern sub_pattern ::= string sub_pattern ::= a Constant instance sub_pattern ::= int sub_pattern ::= float constraint ::= lambda fgraph, expr: additional matching condition output_pattern ::= (op, <output_pattern1>, <output_pattern2>, ...) output_pattern ::= string output_pattern ::= int output_pattern ::= float Each string in the input pattern is a variable that will be set to whatever expression is found in its place. If the same string is used more than once, the same expression must be found in those places. If a string used in the input pattern is used in the output pattern, the matching expression will be inserted in its place. The input pattern cannot just be a string but the output pattern can. If you put a constant variable in the input pattern, there will be a match iff a constant variable with the same value and the same type is found in its place. You can add a constraint to the match by using the ``dict(...)`` form described above with a ``'constraint'`` key. The constraint must be a function that takes the fgraph and the current Variable that we are trying to match and returns True or False according to an arbitrary criterion. The constructor creates a `PatternSub` that replaces occurrences of `in_pattern` by occurrences of `out_pattern`. Parameters ---------- in_pattern : The input pattern that we want to replace. out_pattern : The replacement pattern. allow_multiple_clients : bool If False, the pattern matching will fail if one of the subpatterns has more than one client. skip_identities_fn : TODO name : Allows to override this optimizer name. pdb : bool If True, we invoke pdb when the first node in the pattern matches. tracks : optional The values that :meth:`self.tracks` will return. Useful to speed up optimization sometimes. get_nodes : optional If you provide `tracks`, you must provide this parameter. It must be a function that takes the tracked node and returns a list of nodes on which we will try this optimizer. Notes ----- `tracks` and `get_nodes` can be used to make this optimizer track a less frequent `Op`, so this will make this optimizer tried less frequently. Examples -------- PatternSub((add, 'x', 'y'), (add, 'y', 'x')) PatternSub((multiply, 'x', 'x'), (square, 'x')) PatternSub((subtract, (add, 'x', 'y'), 'y'), 'x') PatternSub((power, 'x', Constant(double, 2.0)), (square, 'x')) PatternSub((boggle, {'pattern': 'x', 'constraint': lambda expr: expr.type == scrabble}), (scrabble, 'x')) """ def __init__( self, in_pattern, out_pattern, allow_multiple_clients=False, skip_identities_fn=None, name=None, pdb=False, tracks=(), get_nodes=None, values_eq_approx=None, ): self.in_pattern = in_pattern self.out_pattern = out_pattern self.values_eq_approx = values_eq_approx if isinstance(in_pattern, (list, tuple)): self.op = self.in_pattern[0] elif isinstance(in_pattern, dict): self.op = self.in_pattern["pattern"][0] else: raise TypeError( "The pattern to search for must start with a specific Op instance." ) self.__doc__ = ( self.__class__.__doc__ + "\n\nThis instance does: " + str(self) + "\n" ) self.allow_multiple_clients = allow_multiple_clients self.skip_identities_fn = skip_identities_fn if name: self.__name__ = name self.pdb = pdb self._tracks = tracks self.get_nodes = get_nodes if tracks != (): assert get_nodes def op_key(self): return self.op def tracks(self): if self._tracks != (): return self._tracks return [self.op] def transform(self, fgraph, node, get_nodes=True): """Check if the graph from node corresponds to ``in_pattern``. If it does, it constructs ``out_pattern`` and performs the replacement. """ from aesara.graph import unify if get_nodes and self.get_nodes is not None: for real_node in self.get_nodes(fgraph, node): if real_node == "output": continue ret = self.transform(fgraph, real_node, get_nodes=False) if ret is not False and ret is not None: return dict(zip(real_node.outputs, ret)) if node.op != self.op: return False # TODO: if we remove pdb, do this speed things up? def match(pattern, expr, u, allow_multiple_clients=False, pdb=False): # TODO move outside match def retry_with_equiv(): if not self.skip_identities_fn: return False expr_equiv = self.skip_identities_fn(expr) if expr_equiv is None: return False # TODO: Not sure how to handle multiple_clients flag return match( pattern, expr_equiv, u, allow_multiple_clients=allow_multiple_clients, ) if isinstance(pattern, (list, tuple)): if expr.owner is None: return False if not (expr.owner.op == pattern[0]) or ( not allow_multiple_clients and len(fgraph.clients[expr]) > 1 ): return retry_with_equiv() if len(pattern) - 1 != len(expr.owner.inputs): return retry_with_equiv() for p, v in zip(pattern[1:], expr.owner.inputs): u = match(p, v, u, self.allow_multiple_clients) if not u: return False elif isinstance(pattern, dict): try: real_pattern = pattern["pattern"] except KeyError: raise KeyError( f"Malformed pattern: {pattern} (expected key 'pattern')" ) constraint = pattern.get("constraint", lambda expr: True) if constraint(expr): return match( real_pattern, expr, u, pattern.get("allow_multiple_clients", allow_multiple_clients), ) else: return retry_with_equiv() elif isinstance(pattern, str): v = unify.Var(pattern) if u[v] is not v and u[v] is not expr: return retry_with_equiv() else: u = u.merge(expr, v) elif isinstance(pattern, (int, float)) and isinstance(expr, Constant): if np.all(aesara.tensor.constant(pattern).value == expr.value): return u else: return retry_with_equiv() elif ( isinstance(pattern, Constant) and isinstance(expr, Constant) and pattern.equals(expr) ): return u else: return retry_with_equiv() if pdb: import pdb pdb.set_trace() return u u = match(self.in_pattern, node.out, unify.Unification(), True, self.pdb) if not u: return False def build(pattern, u): if isinstance(pattern, (list, tuple)): args = [build(p, u) for p in pattern[1:]] return pattern[0](*args) elif isinstance(pattern, str): return u[unify.Var(pattern)] elif isinstance(pattern, (int, float)): return pattern else: return pattern.clone() ret = build(self.out_pattern, u) if isinstance(ret, (int, float)): # TODO: Should we convert these to constants explicitly? return [ret] if self.values_eq_approx: ret.tag.values_eq_approx = self.values_eq_approx if ret.owner: if [out.type for out in ret.owner.outputs] != [ out.type for out in node.outputs ]: return False else: # ret is just an input variable assert len(node.outputs) == 1 if ret.type != node.outputs[0].type: return False return [ret] def __str__(self): if getattr(self, "__name__", None): return self.__name__ def pattern_to_str(pattern): if isinstance(pattern, (list, tuple)): return "{}({})".format( str(pattern[0]), ", ".join([pattern_to_str(p) for p in pattern[1:]]), ) elif isinstance(pattern, dict): return "{} subject to {}".format( pattern_to_str(pattern["pattern"]), str(pattern.get("constraint", "no conditions")), ) else: return str(pattern) return "{} -> {}".format( pattern_to_str(self.in_pattern), pattern_to_str(self.out_pattern), ) def __repr__(self): return str(self) def print_summary(self, stream=sys.stdout, level=0, depth=-1): name = getattr(self, "__name__", getattr(self, "name", None)) print( f"{" " * level}{self.__class__.__name__} {name}({self.in_pattern}, {self.out_pattern}) id={id(self)}", file=stream, ) class Updater(Feature): def __init__(self, importer, pruner, chin, name=None): self.importer = importer self.pruner = pruner self.chin = chin self.name = name def __str__(self): return "Updater{%s}" % str(self.name) def on_import(self, fgraph, node, reason): if self.importer: self.importer(node) def on_prune(self, fgraph, node, reason): if self.pruner: self.pruner(node) def on_change_input(self, fgraph, node, i, r, new_r, reason): if self.chin: self.chin(node, i, r, new_r, reason) def on_detach(self, fgraph): # To allow pickling this object self.importer = None self.pruner = None self.chin = None class NavigatorOptimizer(GlobalOptimizer): r"""An optimizer that applies a `LocalOptimizer` with considerations for the new nodes it creates. This optimizer also allows the `LocalOptimizer` to use a special ``"remove"`` value in the ``dict``\s returned by :meth:`LocalOptimizer`. `Variable`\s mapped to this value are removed from the `FunctionGraph`. Parameters ---------- local_opt : A `LocalOptimizer` to apply over a `FunctionGraph` (or ``None``). ignore_newtrees : - ``True``: new subgraphs returned by an optimization are not a candidate for optimization. - ``False``: new subgraphs returned by an optimization is a candidate for optimization. - ``'auto'``: let the `local_opt` set this parameter via its :attr:`reentrant` attribute. failure_callback A function with the signature ``(exception, navigator, [(old, new), (old,new),...])`` that is called when there's an exception. If the exception is raised in ``local_opt.transform``, the ``new`` variables will be ``None``. If the exception is raised during validation (e.g. the new types don't match) then the new variables will be the ones created by ``self.transform``. If this parameter is ``None``, then exceptions are not caught here and are raised normally. """ @staticmethod def warn(exc, nav, repl_pairs, local_opt, node): """A failure callback that prints a traceback.""" if config.on_opt_error != "ignore": _logger.error(f"Optimization failure due to: {local_opt}") _logger.error(f"node: {node}") _logger.error("TRACEBACK:") _logger.error(traceback.format_exc()) if config.on_opt_error == "pdb": pdb.post_mortem(sys.exc_info()[2]) elif isinstance(exc, AssertionError) or config.on_opt_error == "raise": # We always crash on AssertionError because something may be # seriously wrong if such an exception is raised. raise exc @staticmethod def warn_inplace(exc, nav, repl_pairs, local_opt, node): r"""A failure callback that ignores ``InconsistencyError``\s and prints a traceback. If the error occurred during replacement, ``repl_pairs`` is set; otherwise, its value is ``None``. """ if isinstance(exc, InconsistencyError): return return NavigatorOptimizer.warn(exc, nav, repl_pairs, local_opt, node) @staticmethod def warn_ignore(exc, nav, repl_pairs, local_opt, node): """A failure callback that ignores all errors.""" def __init__(self, local_opt, ignore_newtrees="auto", failure_callback=None): self.local_opt = local_opt if ignore_newtrees == "auto": self.ignore_newtrees = not getattr(local_opt, "reentrant", True) else: self.ignore_newtrees = ignore_newtrees self.failure_callback = failure_callback def attach_updater(self, fgraph, importer, pruner, chin=None, name=None): r"""Install `FunctionGraph` listeners to help the navigator deal with the ``ignore_trees``-related functionality. Parameters ---------- importer : Function that will be called whenever optimizations add stuff to the graph. pruner : Function to be called when optimizations remove stuff from the graph. chin : "on change input" called whenever a node's inputs change. name : name of the ``Updater`` to attach. Returns ------- The `FunctionGraph` plugin that handles the three tasks. Keep this around so that `Feature`\s can be detached later. """ if self.ignore_newtrees: importer = None if importer is None and pruner is None: return None u = Updater(importer, pruner, chin, name=name) fgraph.attach_feature(u) return u def detach_updater(self, fgraph, u): """Undo the work of ``attach_updater``. Parameters ---------- fgraph The `FunctionGraph`. u A return-value of ``attach_updater``. Returns ------- None """ if u is not None: fgraph.remove_feature(u) def process_node(self, fgraph, node, lopt=None): r"""Apply `lopt` to `node`. The :meth:`lopt.transform` method will return either ``False`` or a list of `Variable`\s that are intended to replace :attr:`node.outputs`. If the `fgraph` accepts the replacement, then the optimization is successful, and this function returns ``True``. If there are no replacement candidates or the `fgraph` rejects the replacements, this function returns ``False``. Parameters ---------- fgraph : A `FunctionGraph`. node : An `Apply` instance in `fgraph` lopt : A `LocalOptimizer` instance that may have a better idea for how to compute node's outputs. Returns ------- bool ``True`` iff the `node`'s outputs were replaced in the `fgraph`. """ lopt = lopt or self.local_opt try: replacements = lopt.transform(fgraph, node) except Exception as e: if self.failure_callback is not None: self.failure_callback( e, self, [(x, None) for x in node.outputs], lopt, node ) return False else: raise if replacements is False or replacements is None: return False old_vars = node.outputs remove = [] if isinstance(replacements, dict): if "remove" in replacements: remove = replacements.pop("remove") old_vars = list(replacements.keys()) replacements = list(replacements.values()) elif not isinstance(replacements, (tuple, list)): raise TypeError( f"Optimizer {lopt} gave wrong type of replacement. " f"Expected list or tuple. Got {replacements}" ) if len(old_vars) != len(replacements): raise ValueError(f"Optimizer {lopt} gave wrong number of replacements") # None in the replacement mean that this variable isn't used # and we want to remove it for r, rnew in zip(old_vars, replacements): if rnew is None and len(fgraph.clients[r]) > 0: raise ValueError( "A local optimizer tried to remove a Variable that is used" ) # If an output would be replaced by itself, no need to perform # the replacement repl_pairs = [ (r, rnew) for r, rnew in zip(old_vars, replacements) if rnew is not r and rnew is not None ] if len(repl_pairs) == 0: return False try: fgraph.replace_all_validate_remove(repl_pairs, reason=lopt, remove=remove) return True except Exception as e: # This means the replacements were rejected by the fgraph. # # This is not supposed to happen. The default failure_callback # will print a traceback as a warning. if self.failure_callback is not None: self.failure_callback(e, self, repl_pairs, lopt, node) return False else: raise def add_requirements(self, fgraph): super().add_requirements(fgraph) # Added by default # fgraph.attach_feature(ReplaceValidate()) if self.local_opt: self.local_opt.add_requirements(fgraph) def print_summary(self, stream=sys.stdout, level=0, depth=-1): print(f"{" " * level}{self.__class__.__name__} id={id(self)}", file=stream) if depth != 0: self.local_opt.print_summary(stream, level=(level + 2), depth=(depth - 1)) class TopoOptimizer(NavigatorOptimizer): """An optimizer that applies a single `LocalOptimizer` to each node in topological order (or reverse).""" def __init__( self, local_opt, order="in_to_out", ignore_newtrees=False, failure_callback=None ): if order not in ["out_to_in", "in_to_out"]: raise ValueError("order must be 'out_to_in' or 'in_to_out'") self.order = order super().__init__(local_opt, ignore_newtrees, failure_callback) def apply(self, fgraph, start_from=None): if start_from is None: start_from = fgraph.outputs callback_before = fgraph.execute_callbacks_time nb_nodes_start = len(fgraph.apply_nodes) t0 = time.time() q = deque(io_toposort(fgraph.inputs, start_from)) io_t = time.time() - t0 def importer(node): if node is not current_node: q.append(node) u = self.attach_updater( fgraph, importer, None, name=getattr(self, "name", None) ) nb = 0 try: t0 = time.time() while q: if self.order == "out_to_in": node = q.pop() else: node = q.popleft() if node not in fgraph.apply_nodes: continue current_node = node nb += self.process_node(fgraph, node) loop_t = time.time() - t0 finally: self.detach_updater(fgraph, u) callback_time = fgraph.execute_callbacks_time - callback_before nb_nodes_end = len(fgraph.apply_nodes) return ( self, nb, nb_nodes_start, nb_nodes_end, io_t, loop_t, callback_time, self.local_opt, ) @staticmethod def print_profile(stream, prof, level=0): blanc = " " * level if prof is None: # Happen as merge_profile() isn't implemented print(blanc, "TopoOptimizer merge_profile not implemented", file=stream) return ( opt, nb, nb_nodes_start, nb_nodes_end, io_t, loop_t, callback_time, lopt, ) = prof print( blanc, "TopoOptimizer ", getattr(opt, "name", getattr(opt, "__name__", "")), file=stream, ) print( blanc, " nb_node (start, end, changed)", (nb_nodes_start, nb_nodes_end, nb), file=stream, ) print(blanc, " init io_toposort", io_t, file=stream) print(blanc, " loop time", loop_t, file=stream) print(blanc, " callback_time", callback_time, file=stream) if isinstance(lopt, LocalOptGroup): if lopt.profile: lopt.print_profile( stream, ( lopt.time_opts, lopt.process_count, lopt.applied_true, lopt.node_created, lopt.profile, ), level=level + 1, ) def __str__(self): return getattr(self, "__name__", "<TopoOptimizer instance>") def topogroup_optimizer(order, *local_opts, name=None, **kwargs): """Apply `local_opts` from the input/output nodes to the output/input nodes of a graph. This uses a combination of `LocalOptGroup` and `TopoOptimizer`. """ if len(local_opts) > 1: # Don't wrap it uselessly if their is only 1 optimization. local_opts = LocalOptGroup(*local_opts) else: (local_opts,) = local_opts if not name: name = local_opts.__name__ ret = TopoOptimizer( local_opts, order="in_to_out", failure_callback=TopoOptimizer.warn_inplace, **kwargs, ) if name: ret.__name__ = name return ret in2out = partial(topogroup_optimizer, "in_to_out") out2in = partial(topogroup_optimizer, "out_to_in") class OpKeyOptimizer(NavigatorOptimizer): r"""An optimizer that applies a `LocalOptimizer` to specific `Op`\s. The `Op`\s are provided by a :meth:`LocalOptimizer.op_key` method (either as a list of `Op`\s or a single `Op`), and discovered within a `FunctionGraph` using the `NodeFinder` `Feature`. This is similar to the ``tracks`` feature used by other optimizers. """ def __init__(self, local_opt, ignore_newtrees=False, failure_callback=None): if not hasattr(local_opt, "op_key"): raise TypeError(f"{local_opt} must have an `op_key` method.") super().__init__(local_opt, ignore_newtrees, failure_callback) def apply(self, fgraph): op = self.local_opt.op_key() if isinstance(op, (list, tuple)): q = reduce(list.__iadd__, map(fgraph.get_nodes, op)) else: q = list(fgraph.get_nodes(op)) def importer(node): if node is not current_node: if node.op == op: q.append(node) u = self.attach_updater( fgraph, importer, None, name=getattr(self, "name", None) ) try: while q: node = q.pop() if node not in fgraph.apply_nodes: continue current_node = node self.process_node(fgraph, node) finally: self.detach_updater(fgraph, u) def add_requirements(self, fgraph): super().add_requirements(fgraph) fgraph.attach_feature(NodeFinder()) class ChangeTracker(Feature): def __init__(self): self.changed = False self.nb_imported = 0 def on_import(self, fgraph, node, reason): self.nb_imported += 1 self.changed = True def on_change_input(self, fgraph, node, i, r, new_r, reason): self.changed = True def reset(self): self.changed = False def on_attach(self, fgraph): fgraph.change_tracker = self def on_detach(self, fgraph): del fgraph.change_tracker def merge_dict(d1, d2): r"""Merge two ``dict``\s by adding their values.""" d = d1.copy() for k, v in d2.items(): if k in d: d[k] += v else: d[k] = v return d class EquilibriumOptimizer(NavigatorOptimizer): """An optimizer that applies an optimization until a fixed-point/equilibrium is reached. Parameters ---------- optimizers : list or set Local or global optimizations to apply until equilibrium. The global optimizer will be run at the start of each iteration before the local optimizer. max_use_ratio : int or float Each optimizer can be applied at most ``(size of graph * this number)`` times. ignore_newtrees : See :attr:`EquilibriumDB.ignore_newtrees`. final_optimizers : Global optimizers that will be run after each iteration. cleanup_optimizers : Global optimizers that apply a list of pre determined optimization. They must not traverse the graph as they are called very frequently. The MergeOptimizer is one example of optimization that respect this. They are applied after all global optimizers, then when one local optimizer is applied, then after all final optimizers. """ def __init__( self, optimizers, failure_callback=None, ignore_newtrees=True, tracks_on_change_inputs=False, max_use_ratio=None, final_optimizers=None, cleanup_optimizers=None, ): super().__init__( None, ignore_newtrees=ignore_newtrees, failure_callback=failure_callback ) self.local_optimizers_map = OrderedDict() self.local_optimizers_all = [] self.global_optimizers = [] self.final_optimizers = [] self.cleanup_optimizers = [] self.tracks_on_change_inputs = tracks_on_change_inputs for opt in optimizers: if isinstance(opt, LocalOptimizer): if opt.tracks() is None: self.local_optimizers_all.append(opt) else: for c in opt.tracks(): self.local_optimizers_map.setdefault(c, []).append(opt) else: self.global_optimizers.append(opt) if final_optimizers: self.final_optimizers = final_optimizers if cleanup_optimizers: self.cleanup_optimizers = cleanup_optimizers self.max_use_ratio = max_use_ratio assert self.max_use_ratio is not None, "max_use_ratio has to be a number" def get_local_optimizers(self): for opt in self.local_optimizers_all: yield opt # if repeat is not a problem we can drop the set s = set() for lopt in self.local_optimizers_map.values(): for opt in lopt: if opt not in s: yield opt s.add(opt) def add_requirements(self, fgraph): super().add_requirements(fgraph) for opt in self.get_local_optimizers(): opt.add_requirements(fgraph) for opt in self.global_optimizers: opt.add_requirements(fgraph) for opt in self.final_optimizers: opt.add_requirements(fgraph) for opt in self.cleanup_optimizers: opt.add_requirements(fgraph) def apply(self, fgraph, start_from=None): change_tracker = ChangeTracker() fgraph.attach_feature(change_tracker) if start_from is None: start_from = fgraph.outputs else: for node in start_from: assert node in fgraph.outputs changed = True max_use_abort = False opt_name = None global_process_count = {} start_nb_nodes = len(fgraph.apply_nodes) max_nb_nodes = len(fgraph.apply_nodes) max_use = max_nb_nodes * self.max_use_ratio loop_timing = [] loop_process_count = [] global_opt_timing = [] time_opts = {} io_toposort_timing = [] nb_nodes = [] node_created = {} global_sub_profs = [] final_sub_profs = [] cleanup_sub_profs = [] for opt in ( self.global_optimizers + list(self.get_local_optimizers()) + self.final_optimizers + self.cleanup_optimizers ): global_process_count.setdefault(opt, 0) time_opts.setdefault(opt, 0) node_created.setdefault(opt, 0) def apply_cleanup(profs_dict): changed = False for copt in self.cleanup_optimizers: change_tracker.reset() nb = change_tracker.nb_imported t_opt = time.time() sub_prof = copt.apply(fgraph) time_opts[copt] += time.time() - t_opt profs_dict[copt].append(sub_prof) if change_tracker.changed: process_count.setdefault(copt, 0) process_count[copt] += 1 global_process_count[copt] += 1 changed = True node_created[copt] += change_tracker.nb_imported - nb return changed while changed and not max_use_abort: process_count = {} t0 = time.time() changed = False iter_cleanup_sub_profs = {} for copt in self.cleanup_optimizers: iter_cleanup_sub_profs[copt] = [] # apply global optimizers sub_profs = [] for gopt in self.global_optimizers: change_tracker.reset() nb = change_tracker.nb_imported t_opt = time.time() sub_prof = gopt.apply(fgraph) time_opts[gopt] += time.time() - t_opt sub_profs.append(sub_prof) if change_tracker.changed: process_count.setdefault(gopt, 0) process_count[gopt] += 1 global_process_count[gopt] += 1 changed = True node_created[gopt] += change_tracker.nb_imported - nb if global_process_count[gopt] > max_use: max_use_abort = True opt_name = getattr(gopt, "name", None) or getattr( gopt, "__name__", "" ) global_sub_profs.append(sub_profs) global_opt_timing.append(float(time.time() - t0)) # apply clean up as global opt can have done changes that # request that changed |= apply_cleanup(iter_cleanup_sub_profs) # apply local optimizer topo_t0 = time.time() q = deque(io_toposort(fgraph.inputs, start_from)) io_toposort_timing.append(time.time() - topo_t0) nb_nodes.append(len(q)) max_nb_nodes = max(max_nb_nodes, len(q)) max_use = max_nb_nodes * self.max_use_ratio def importer(node): if node is not current_node: q.append(node) chin = None if self.tracks_on_change_inputs: def chin(node, i, r, new_r, reason): if node is not current_node and not isinstance(node, str): q.append(node) u = self.attach_updater( fgraph, importer, None, chin=chin, name=getattr(self, "name", None) ) try: while q: node = q.pop() if node not in fgraph.apply_nodes: continue current_node = node for lopt in ( self.local_optimizers_all + self.local_optimizers_map.get(type(node.op), []) + self.local_optimizers_map.get(node.op, []) ): nb = change_tracker.nb_imported t_opt = time.time() lopt_change = self.process_node(fgraph, node, lopt) time_opts[lopt] += time.time() - t_opt if not lopt_change: continue process_count.setdefault(lopt, 0) process_count[lopt] += 1 global_process_count[lopt] += 1 changed = True node_created[lopt] += change_tracker.nb_imported - nb changed |= apply_cleanup(iter_cleanup_sub_profs) if global_process_count[lopt] > max_use: max_use_abort = True opt_name = getattr(lopt, "name", None) or getattr( lopt, "__name__", "" ) if node not in fgraph.apply_nodes: # go to next node break finally: self.detach_updater(fgraph, u) # Apply final optimizers sub_profs = [] t_before_final_opt = time.time() for gopt in self.final_optimizers: change_tracker.reset() nb = change_tracker.nb_imported t_opt = time.time() sub_prof = gopt.apply(fgraph) time_opts[gopt] += time.time() - t_opt sub_profs.append(sub_prof) if change_tracker.changed: process_count.setdefault(gopt, 0) process_count[gopt] += 1 global_process_count[gopt] += 1 changed = True node_created[gopt] += change_tracker.nb_imported - nb if global_process_count[gopt] > max_use: max_use_abort = True opt_name = getattr(gopt, "name", None) or getattr( gopt, "__name__", "" ) final_sub_profs.append(sub_profs) global_opt_timing[-1] += time.time() - t_before_final_opt # apply clean up as final opt can have done changes that # request that changed |= apply_cleanup(iter_cleanup_sub_profs) # merge clean up profiles during that iteration. c_sub_profs = [] for copt, sub_profs in iter_cleanup_sub_profs.items(): sub_prof = sub_profs[0] for s_p in sub_profs[1:]: sub_prof = copt.merge_profile(sub_prof, s_p) c_sub_profs.append(sub_prof) cleanup_sub_profs.append(c_sub_profs) loop_process_count.append(process_count) loop_timing.append(float(time.time() - t0)) end_nb_nodes = len(fgraph.apply_nodes) if max_use_abort: msg = ( f"EquilibriumOptimizer max'ed out by '{opt_name}'" + ". You can safely raise the current threshold of " + "{config.optdb__max_use_ratio:f} with the aesara flag 'optdb__max_use_ratio'." ) if config.on_opt_error == "raise": raise AssertionError(msg) else: _logger.error(msg) fgraph.remove_feature(change_tracker) assert len(loop_process_count) == len(loop_timing) assert len(loop_process_count) == len(global_opt_timing) assert len(loop_process_count) == len(nb_nodes) assert len(loop_process_count) == len(io_toposort_timing) assert len(loop_process_count) == len(global_sub_profs) assert len(loop_process_count) == len(final_sub_profs) assert len(loop_process_count) == len(cleanup_sub_profs) return ( self, loop_timing, loop_process_count, (start_nb_nodes, end_nb_nodes, max_nb_nodes), global_opt_timing, nb_nodes, time_opts, io_toposort_timing, node_created, global_sub_profs, final_sub_profs, cleanup_sub_profs, ) def print_summary(self, stream=sys.stdout, level=0, depth=-1): name = getattr(self, "name", None) print( f"{" " * level}{self.__class__.__name__} {name} id={id(self)}", file=stream ) if depth != 0: for lopt in self.get_local_optimizers(): lopt.print_summary(stream, level=(level + 2), depth=(depth - 1)) @staticmethod def print_profile(stream, prof, level=0): ( opt, loop_timing, loop_process_count, (start_nb_nodes, end_nb_nodes, max_nb_nodes), global_opt_timing, nb_nodes, time_opts, io_toposort_timing, node_created, global_sub_profs, final_sub_profs, cleanup_sub_profs, ) = prof blanc = " " * level print(blanc, "EquilibriumOptimizer", end=" ", file=stream) print(blanc, getattr(opt, "name", getattr(opt, "__name__", "")), file=stream) print( blanc, f" time {sum(loop_timing):.3f}s for {len(loop_timing)} passes", file=stream, ) print( blanc, f" nb nodes (start, end, max) {int(start_nb_nodes)} {int(end_nb_nodes)} {int(max_nb_nodes)}", file=stream, ) print(blanc, f" time io_toposort {sum(io_toposort_timing):.3f}s", file=stream) s = sum([time_opts[o] for o in opt.get_local_optimizers()]) print(blanc, f" time in local optimizers {s:.3f}s", file=stream) s = sum([time_opts[o] for o in opt.global_optimizers]) print(blanc, f" time in global optimizers {s:.3f}s", file=stream) s = sum([time_opts[o] for o in opt.final_optimizers]) print(blanc, f" time in final optimizers {s:.3f}s", file=stream) s = sum([time_opts[o] for o in opt.cleanup_optimizers]) print(blanc, f" time in cleanup optimizers {s:.3f}s", file=stream) for i in range(len(loop_timing)): lopt = "" if loop_process_count[i]: d = list( reversed(sorted(loop_process_count[i].items(), key=lambda a: a[1])) ) lopt = " ".join([str((str(k), v)) for k, v in d[:5]]) if len(d) > 5: lopt += " ..." print( blanc, ( f" {int(i):2d} - {loop_timing[i]:.3f}s {int(sum(loop_process_count[i].values()))} ({global_opt_timing[i]:.3f}s in global opts, " f"{io_toposort_timing[i]:.3f}s io_toposort) - {int(nb_nodes[i])} nodes - {lopt}" ), file=stream, ) count_opt = [] not_used = [] not_used_time = 0 process_count = {} for o in ( opt.global_optimizers + list(opt.get_local_optimizers()) + list(opt.final_optimizers) + list(opt.cleanup_optimizers) ): process_count.setdefault(o, 0) for count in loop_process_count: for o, v in count.items(): process_count[o] += v for o, count in process_count.items(): if count > 0: count_opt.append((time_opts[o], count, node_created[o], o)) else: not_used.append((time_opts[o], o)) not_used_time += time_opts[o] if count_opt: print( blanc, " times - times applied - nb node created - name:", file=stream ) count_opt.sort() for (t, count, n_created, o) in count_opt[::-1]: print( blanc, f" {t:.3f}s - {int(count)} - {int(n_created)} - {o}", file=stream, ) print( blanc, f" {not_used_time:.3f}s - in {len(not_used)} optimization that were not used (display only those with a runtime > 0)", file=stream, ) not_used.sort(key=lambda nu: (nu[0], str(nu[1]))) for (t, o) in not_used[::-1]: if t > 0: # Skip opt that have 0 times, they probably wasn't even tried. print(blanc + " ", f" {t:.3f}s - {o}", file=stream) print(file=stream) gf_opts = [ o for o in ( opt.global_optimizers + list(opt.final_optimizers) + list(opt.cleanup_optimizers) ) if o.print_profile.__code__ is not GlobalOptimizer.print_profile.__code__ ] if not gf_opts: return print(blanc, "Global, final and clean up optimizers", file=stream) for i in range(len(loop_timing)): print(blanc, f"Iter {int(i)}", file=stream) for o, prof in zip(opt.global_optimizers, global_sub_profs[i]): try: o.print_profile(stream, prof, level + 2) except NotImplementedError: print(blanc, "merge not implemented for ", o) for o, prof in zip(opt.final_optimizers, final_sub_profs[i]): try: o.print_profile(stream, prof, level + 2) except NotImplementedError: print(blanc, "merge not implemented for ", o) for o, prof in zip(opt.cleanup_optimizers, cleanup_sub_profs[i]): try: o.print_profile(stream, prof, level + 2) except NotImplementedError: print(blanc, "merge not implemented for ", o) @staticmethod def merge_profile(prof1, prof2): # (opt, loop_timing, loop_process_count, max_nb_nodes, # global_opt_timing, nb_nodes, time_opts, io_toposort_timing) = prof1 local_optimizers = OrderedSet(prof1[0].get_local_optimizers()).union( prof2[0].get_local_optimizers() ) global_optimizers = OrderedSet(prof1[0].global_optimizers).union( prof2[0].global_optimizers ) final_optimizers = list( OrderedSet(prof1[0].final_optimizers).union(prof2[0].final_optimizers) ) cleanup_optimizers = list( OrderedSet(prof1[0].cleanup_optimizers).union(prof2[0].cleanup_optimizers) ) new_opt = EquilibriumOptimizer( local_optimizers.union(global_optimizers), max_use_ratio=1, final_optimizers=final_optimizers, cleanup_optimizers=cleanup_optimizers, ) def add_append_list(l1, l2): l = copy.copy(l1) for idx, nb in enumerate(l2): if idx < len(l): l[idx] += nb else: l.append(nb) return l loop_timing = add_append_list(prof1[1], prof2[1]) loop_process_count = list(prof1[2]) global_sub_profs = [] final_sub_profs = [] cleanup_sub_profs = [] for i in range(min(len(loop_process_count), len(prof2[2]))): process_count = loop_process_count[i] for process, count in prof2[2][i].items(): if process in process_count: process_count[process] += count else: process_count[process] = count def merge(opts, attr, idx): tmp = [] for opt in opts: o1 = getattr(prof1[0], attr) o2 = getattr(prof2[0], attr) if opt in o1 and opt in o2: p1 = prof1[idx][i][o1.index(opt)] p2 = prof2[idx][i][o2.index(opt)] m = None if hasattr(opt, "merge_profile"): m = opt.merge_profile(p1, p2) elif opt in o1: m = prof1[idx][i][o1.index(opt)] else: m = prof2[idx][i][o2.index(opt)] tmp.append(m) return tmp global_sub_profs.append(merge(global_optimizers, "global_optimizers", 9)) final_sub_profs.append(merge(final_optimizers, "final_optimizers", 10)) cleanup_sub_profs.append( merge(cleanup_optimizers, "cleanup_optimizers", 11) ) # Add the iteration done by only one of the profile. loop_process_count.extend(prof1[2][len(loop_process_count) :]) global_sub_profs.extend(prof1[9][len(global_sub_profs) :]) final_sub_profs.extend(prof1[10][len(final_sub_profs) :]) cleanup_sub_profs.extend(prof1[11][len(cleanup_sub_profs) :]) global_sub_profs.extend(prof2[9][len(loop_process_count) :]) final_sub_profs.extend(prof2[10][len(loop_process_count) :]) cleanup_sub_profs.extend(prof2[11][len(loop_process_count) :]) max_nb_nodes = max(prof1[3], prof2[3]) global_opt_timing = add_append_list(prof1[4], prof2[4]) nb_nodes = add_append_list(prof1[5], prof2[5]) time_opts = merge_dict(prof1[6], prof2[6]) io_toposort_timing = add_append_list(prof1[7], prof2[7]) assert ( len(loop_timing) == len(global_opt_timing) == len(global_sub_profs) == len(io_toposort_timing) == len(nb_nodes) ) assert len(loop_timing) == max(len(prof1[1]), len(prof2[1])) node_created = merge_dict(prof1[8], prof2[8]) return ( new_opt, loop_timing, loop_process_count, max_nb_nodes, global_opt_timing, nb_nodes, time_opts, io_toposort_timing, node_created, global_sub_profs, final_sub_profs, cleanup_sub_profs, ) def _check_chain(r, chain): """ WRITEME """ chain = list(reversed(chain)) while chain: elem = chain.pop() if elem is None: if r.owner is not None: return False elif r.owner is None: return False elif isinstance(elem, Op): if not r.owner.op == elem: return False else: try: if issubclass(elem, Op) and not isinstance(r.owner.op, elem): return False except TypeError: return False if chain: r = r.owner.inputs[chain.pop()] # print 'check_chain', _check_chain.n_calls # _check_chain.n_calls += 1 # The return value will be used as a Boolean, but some Variables cannot # be used as Booleans (the results of comparisons, for instance) return r is not None def check_chain(r, *chain): """ WRITEME """ if isinstance(r, Apply): r = r.outputs[0] return _check_chain(r, reduce(list.__iadd__, ([x, 0] for x in chain))) def pre_greedy_local_optimizer(fgraph, optimizations, out): """Apply local optimizations to a graph. This function traverses the computation graph in the graph before the variable `out` but that are not in the `fgraph`. It applies `optimizations` to each variable on the traversed graph. .. warning:: This changes the nodes in a graph in-place. Its main use is to apply locally constant folding when generating the graph of the indices of a subtensor. Changes should not be applied to nodes that are in an `fgraph`, so we use `fgraph` to prevent that. Notes ----- This doesn't do an equilibrium optimization, so, if there is an optimization--like `local_upcast_elemwise_constant_inputs`--in the list that adds additional nodes to the inputs of the node, it might be necessary to call this function multiple times. Parameters ---------- fgraph : FunctionGraph The graph used to avoid/filter nodes. optimizations : list of LocalOptimizer The list of local optimizations to apply out : Variable A `Variable` specifying the graph to optimize. """ def local_recursive_function(list_opt, out, optimized_vars, depth): if not getattr(out, "owner", None): return [out], optimized_vars node = out.owner if node in fgraph.apply_nodes: return node.outputs, optimized_vars # Walk up the graph via the node's inputs for idx, inp in enumerate(node.inputs): if inp in optimized_vars: nw_in = optimized_vars[inp] else: if inp.owner: outs, optimized_vars = local_recursive_function( list_opt, inp, optimized_vars, depth + 1 ) for k, v in zip(inp.owner.outputs, outs): optimized_vars[k] = v nw_in = outs[inp.owner.outputs.index(inp)] else: nw_in = inp optimized_vars[inp] = inp # XXX: An in-place change node.inputs[idx] = nw_in # Apply the optimizations results = node.outputs for opt in list_opt: ret = opt.transform(fgraph, node) if ret is not False and ret is not None: assert len(ret) == len(node.outputs), opt for k, v in zip(node.outputs, ret): optimized_vars[k] = v results = ret if ret[0].owner: node = out.owner else: break return results, optimized_vars if out.owner: out_index = out.owner.outputs.index(out) else: out_index = 0 final_outs, optimized_nodes = local_recursive_function(optimizations, out, {}, 0) return final_outs[out_index] def copy_stack_trace(from_var, to_var): r"""Copy the stack traces from `from_var` to `to_var`. Parameters ---------- from_var : `Variable` or list `Variable`\s to copy stack traces from. to_var : `Variable` or list `Variable`\s to copy stack traces to. Notes ----- The stacktrace is assumed to be of the form of a list of lists of tuples. Each tuple contains the filename, line number, function name and so on. Each list of tuples contains the truples belonging to a particular `Variable`. """ # Store stack traces from from_var tr = [] if isinstance(from_var, Iterable) and not isinstance(from_var, Variable): # If from_var is a list, store concatenated stack traces for v in from_var: tr += getattr(v.tag, "trace", []) else: # If from_var is not a list, it must be a single tensor variable, # so just store that particular stack trace tr = getattr(from_var.tag, "trace", []) if tr and isinstance(tr[0], tuple): # There was one single stack trace, we encapsulate it in a list tr = [tr] # Copy over stack traces to to_var if isinstance(to_var, Iterable) and not isinstance(to_var, Variable): # Copy over stack traces from from_var to each variable in # to_var, including the stack_trace of the to_var before for v in to_var: v.tag.trace = getattr(v.tag, "trace", []) + tr else: # Copy over stack traces from from_var to each variable to # to_var, including the stack_trace of the to_var before to_var.tag.trace = getattr(to_var.tag, "trace", []) + tr return to_var @contextlib.contextmanager def inherit_stack_trace(from_var): """ A context manager that copies the stack trace from one or more variable nodes to all variable nodes constructed in the body. ``new_nodes`` is the list of all the newly created variable nodes inside an optimization that is managed by ``graph.nodes_constructed``. Parameters ---------- from_var : `Variable` node or a list of `Variable` nodes to copy stack traces from. """ with nodes_constructed() as new_nodes: yield copy_stack_trace(from_var, new_nodes) def check_stack_trace(f_or_fgraph, ops_to_check="last", bug_print="raise"): r"""Checks if the outputs of specific `Op`\s have a stack trace. Parameters ---------- f_or_fgraph : Function or FunctionGraph The compiled function or the function graph to be analysed. ops_to_check This value can be of four different types: - classes or instances inheriting from `Op` - tuple/list of classes or instances inheriting from `Op` - string - function returning a boolean and taking as input an instance of `Op` - if `ops_to_check` is a string, it should be either ``'last'`` or ``'all'``. ``'last'`` will check only the last `Op` of the graph while ``'all'`` will check all the `Op`\s of the graph. - if `ops_to_check` is an `Op` or a tuple/list of `Op`\s, the function will check that all the outputs of their occurrences in the graph have a stack trace. - if `ops_to_check` is a function, it should take as input a `Op` and return a boolean indicating if the input `Op` should be checked or not. bug_print This value is a string belonging to ``{'raise', 'warn', 'ignore'}``. You can specify the behaviour of the function when the specified `ops_to_check` are not in the graph of `f_or_fgraph`: it can either raise an exception, write a warning or simply ignore it. Returns ------- boolean ``True`` if the outputs of the specified ops have a stack, ``False`` otherwise. """ if isinstance(f_or_fgraph, aesara.compile.function.types.Function): fgraph = f_or_fgraph.maker.fgraph elif isinstance(f_or_fgraph, aesara.graph.fg.FunctionGraph): fgraph = f_or_fgraph else: raise ValueError("The type of f_or_fgraph is not supported") if isinstance(ops_to_check, Op) or ( inspect.isclass(ops_to_check) and issubclass(ops_to_check, Op) ): ops_to_check = (ops_to_check,) # if ops_to_check is a string if isinstance(ops_to_check, str): if ops_to_check == "last": apply_nodes_to_check = [ fgraph.outputs[i].owner for i in range(len(fgraph.outputs)) ] elif ops_to_check == "all": apply_nodes_to_check = fgraph.apply_nodes else: raise ValueError("The string ops_to_check is not recognised") # if ops_to_check is a list/tuple of ops elif isinstance(ops_to_check, (tuple, list)): # Separate classes from instances in ops_to_check op_instances = [] op_classes = [] for obj in ops_to_check: if isinstance(obj, Op): op_instances.append(obj) else: op_classes.append(obj) op_classes = tuple(op_classes) apply_nodes_to_check = [ node for node in fgraph.apply_nodes if node.op in ops_to_check ] + [ node for node in fgraph.apply_nodes if isinstance(node.op, op_classes) or ( hasattr(node.op, "scalar_op") and isinstance(node.op.scalar_op, op_classes) ) ] # if ops_to_check is a function elif callable(ops_to_check): apply_nodes_to_check = [ node for node in fgraph.apply_nodes if ops_to_check(node) ] else: raise ValueError("ops_to_check does not have the right type") if not apply_nodes_to_check: msg = ( "Provided op instances/classes are not in the graph or the " "graph is empty" ) if bug_print == "warn": warnings.warn(msg) elif bug_print == "raise": raise Exception(msg) elif bug_print == "ignore": pass else: raise ValueError("The string bug_print is not recognised") for node in apply_nodes_to_check: for output in node.outputs: if not hasattr(output.tag, "trace") or not output.tag.trace: return False return True class CheckStackTraceFeature(Feature): def on_import(self, fgraph, node, reason): # In optdb we only register the CheckStackTraceOptimization when # config.check_stack_trace is not off but we also double check here. if config.check_stack_trace != "off" and not check_stack_trace(fgraph, "all"): if config.check_stack_trace == "raise": raise AssertionError( "Empty stack trace! The optimization that inserted this variable is " + str(reason) ) elif config.check_stack_trace in ["log", "warn"]: apply_nodes_to_check = fgraph.apply_nodes for node in apply_nodes_to_check: for output in node.outputs: if not hasattr(output.tag, "trace") or not output.tag.trace: output.tag.trace = [ [ ( "", 0, "Empty stack trace! The optimization that" + "inserted this variable is " + str(reason), "", ) ] ] if config.check_stack_trace == "warn": warnings.warn( "Empty stack trace! The optimization that inserted this variable is" + str(reason) ) class CheckStackTraceOptimization(GlobalOptimizer): """Optimizer that serves to add `CheckStackTraceOptimization` as a feature.""" def add_requirements(self, fgraph): if not hasattr(fgraph, "CheckStackTraceFeature"): fgraph.attach_feature(CheckStackTraceFeature()) def apply(self, fgraph): pass
""" Defines the base class for optimizations as well as a certain amount of useful generic optimization tools. """ import abc import contextlib import copy import inspect import logging import pdb import sys import time import traceback import warnings from collections import OrderedDict, UserList, defaultdict, deque from collections.abc import Iterable from functools import partial, reduce from typing import Dict, List, Optional, Tuple, Union import numpy as np import aesara from aesara.assert_op import Assert, assert_op from aesara.configdefaults import config from aesara.graph import destroyhandler as dh from aesara.graph.basic import ( Apply, Constant, Variable, applys_between, io_toposort, nodes_constructed, ) from aesara.graph.features import Feature, NodeFinder from aesara.graph.fg import FunctionGraph, InconsistencyError from aesara.graph.op import Op from aesara.graph.utils import AssocList from aesara.misc.ordered_set import OrderedSet from aesara.utils import flatten _logger = logging.getLogger("aesara.graph.opt") _optimizer_idx = [0] class LocalMetaOptimizerSkipAssertionError(AssertionError): """This is an AssertionError, but instead of having the LocalMetaOptimizer print the error, it just skip that compilation. """ class GlobalOptimizer(abc.ABC): """A optimizer that can be applied to a `FunctionGraph` in order to transform it. It can represent an optimization or, in general, any kind of transformation one could apply to a `FunctionGraph`. """ @abc.abstractmethod def apply(self, fgraph): """Apply the optimization to a `FunctionGraph`. It may use all the methods defined by the `FunctionGraph`. If the `GlobalOptimizer` needs to use a certain tool, such as an `InstanceFinder`, it can do so in its `add_requirements` method. """ raise NotImplementedError() def optimize(self, fgraph, *args, **kwargs): """ This is meant as a shortcut for the following:: opt.add_requirements(fgraph) opt.apply(fgraph) """ self.add_requirements(fgraph) ret = self.apply(fgraph, *args, **kwargs) return ret def __call__(self, fgraph): """Optimize a `FunctionGraph`. This is the same as ``self.optimize(fgraph)``. """ return self.optimize(fgraph) def add_requirements(self, fgraph): """Add features to `fgraph` that are required to apply the optimization. For example:: fgraph.attach_feature(History()) fgraph.attach_feature(MyFeature()) # etc. """ def print_summary(self, stream=sys.stdout, level=0, depth=-1): name = getattr(self, "name", None) print( f"{' ' * level}{self.__class__.__name__} {name} id={id(self)}", file=stream, ) @staticmethod def print_profile(stream, prof, level=0): if prof is not None: raise NotImplementedError( "The function print_profile must be overridden if the" " optimizer return profiling information." ) def __hash__(self): if not hasattr(self, "_optimizer_idx"): self._optimizer_idx = _optimizer_idx[0] _optimizer_idx[0] += 1 return self._optimizer_idx class FromFunctionOptimizer(GlobalOptimizer): """A `GlobalOptimizer` constructed from a given function.""" def __init__(self, fn, requirements=()): self.fn = fn self.requirements = requirements def apply(self, *args, **kwargs): return self.fn(*args, **kwargs) def add_requirements(self, fgraph): for req in self.requirements: req(fgraph) def print_summary(self, stream=sys.stdout, level=0, depth=-1): print(f"{' ' * level}{self.apply} id={id(self)}", file=stream) def __call__(self, *args, **kwargs): return self.fn(*args, **kwargs) def __str__(self): return self.__name__ def optimizer(f): """Decorator for `FromFunctionOptimizer`.""" rval = FromFunctionOptimizer(f) rval.__name__ = f.__name__ return rval def inplace_optimizer(f): """Decorator for `FromFunctionOptimizer` that also adds the `DestroyHandler` features.""" dh_handler = dh.DestroyHandler requirements = (lambda fgraph: fgraph.attach_feature(dh_handler()),) rval = FromFunctionOptimizer(f, requirements) rval.__name__ = f.__name__ return rval class SeqOptimizer(GlobalOptimizer, UserList): """A `GlobalOptimizer` that applies a list of optimizers sequentially.""" @staticmethod def warn(exc, self, optimizer): """Default ``failure_callback`` for `SeqOptimizer`.""" _logger.error(f"SeqOptimizer apply {optimizer}") _logger.error("Traceback:") _logger.error(traceback.format_exc()) if config.on_opt_error == "raise": raise exc elif config.on_opt_error == "pdb": pdb.post_mortem(sys.exc_info()[2]) def __init__(self, *opts, failure_callback=None): """ Parameters ---------- *opts : The List of optimizers to be applied to a node failure_callback : callable or None Keyword only argument. A callback used when a failure happen during optimization. """ if len(opts) == 1 and isinstance(opts[0], (list, tuple)): opts = opts[0] super().__init__(opts) self.failure_callback = failure_callback def apply(self, fgraph): """Applies each `GlobalOptimizer` in ``self.data`` to `fgraph`.""" l = [] if fgraph.profile: validate_before = fgraph.profile.validate_time sub_validate_time = [validate_before] callbacks_before = fgraph.execute_callbacks_times.copy() else: sub_validate_time = [] callbacks_before = [] callback_before = fgraph.execute_callbacks_time nb_node_before = len(fgraph.apply_nodes) sub_profs = [] nb_nodes = [] self.pre_profile = ( self, l, -1, -1, nb_node_before, -1, sub_profs, sub_validate_time, nb_nodes, {}, ) try: for optimizer in self.data: try: nb_nodes_before = len(fgraph.apply_nodes) t0 = time.time() sub_prof = optimizer.optimize(fgraph) l.append(float(time.time() - t0)) sub_profs.append(sub_prof) nb_nodes.append((nb_nodes_before, len(fgraph.apply_nodes))) if fgraph.profile: sub_validate_time.append(fgraph.profile.validate_time) except AssertionError: # do not catch Assertion failures raise except Exception as e: if self.failure_callback: self.failure_callback(e, self, optimizer) continue else: raise finally: if fgraph.profile: validate_time = fgraph.profile.validate_time - validate_before callbacks_time = {} for k, v in fgraph.execute_callbacks_times.items(): if k in callbacks_before: t = v - callbacks_before[k] if t > 0: callbacks_time[k] = t else: callbacks_time[k] = v else: validate_time = None callbacks_time = {} callback_time = fgraph.execute_callbacks_time - callback_before self.pre_profile = ( self, l, validate_time, callback_time, nb_node_before, len(fgraph.apply_nodes), sub_profs, sub_validate_time, nb_nodes, callbacks_time, ) return self.pre_profile def __repr__(self): return f"SeqOpt({self.data})" def print_summary(self, stream=sys.stdout, level=0, depth=-1): name = getattr(self, "name", None) print( f"{' ' * level}{self.__class__.__name__} {name} id={id(self)}", file=stream ) # This way, -1 will do all depth if depth != 0: depth -= 1 for opt in self.data: opt.print_summary(stream, level=(level + 2), depth=depth) @staticmethod def print_profile(stream, prof, level=0): ( opts, prof, validate_time, callback_time, nb_node_before, nb_node_after, sub_profs, sub_validate_time, nb_nodes, callbacks_time, ) = prof blanc = " " * level print(blanc, "SeqOptimizer", end=" ", file=stream) if hasattr(opts, "name"): print(blanc, opts.name, end=" ", file=stream) elif hasattr(opts, "__name__"): print(blanc, opts.__name__, end=" ", file=stream) print( ( f" time {sum(prof):.3f}s for {int(nb_node_before)}/{int(nb_node_after)} nodes" " before/after optimization" ), file=stream, ) print(blanc, f" {callback_time:.3f}s for callback", file=stream) print(blanc, f" {validate_time:.3f}s for fgraph.validate()", file=stream) if callback_time > 1: print(blanc, " callbacks_time", file=stream) for i in sorted(callbacks_time.items(), key=lambda a: -a[1]): if i[1] > 0: # We want to have the __str__ called, so we can't # just print i. print(blanc, " ", i[0], ",", i[1], file=stream) if level == 0: print( blanc, " time - (name, class, index, nodes before, nodes after) - validate time", file=stream, ) ll = [] for (opt, nb_n) in zip(opts, nb_nodes): if hasattr(opt, "__name__"): name = opt.__name__ else: name = opt.name idx = opts.index(opt) ll.append((name, opt.__class__.__name__, idx) + nb_n) lll = sorted(zip(prof, ll), key=lambda a: a[0]) for (t, opt) in lll[::-1]: i = opt[2] if sub_validate_time: val_time = sub_validate_time[i + 1] - sub_validate_time[i] print( blanc, f" {t:.6f}s - {opt} - {val_time:.3f}s", file=stream, ) else: print(blanc, f" {t:.6f}s - {opt}", file=stream) if sub_profs[i]: opts[i].print_profile(stream, sub_profs[i], level=level + 1) print(file=stream) @staticmethod def merge_profile(prof1, prof2): """Merge two profiles.""" new_t = [] # the time for the optimization new_l = [] # the optimization new_sub_profile = [] # merge common(same object) opt for l in set(prof1[0]).intersection(set(prof2[0])): idx1 = prof1[0].index(l) idx2 = prof2[0].index(l) new_t.append(prof1[1][idx1] + prof2[1][idx2]) new_l.append(l) if hasattr(l, "merge_profile"): assert len(prof1[6][idx1]) == len(prof2[6][idx2]) new_sub_profile.append(l.merge_profile(prof1[6][idx1], prof2[6][idx2])) else: new_sub_profile.append(None) # merge not common opt from io import StringIO for l in set(prof1[0]).symmetric_difference(set(prof2[0])): # The set trick above only work for the same object optimization # It don't work for equivalent optimization. # So we try to merge equivalent optimization here. new_l_names = [o.name for o in new_l] if l.name in new_l_names: idx = new_l_names.index(l.name) io1 = StringIO() io2 = StringIO() l.print_summary(io1) new_l[idx].print_summary(io2) if io1.read() == io2.read(): if l in prof1[0]: p = prof1 else: p = prof2 new_t[idx] += p[1][p[0].index(l)] if hasattr(l, "merge_profile"): assert len(p[6][p[0].index(l)]) == len(new_sub_profile[idx]) new_sub_profile[idx] = l.merge_profile( new_sub_profile[idx], p[6][p[0].index(l)] ) else: new_sub_profile[idx] = None continue if l in prof1[0]: p = prof1 else: p = prof2 new_t.append(p[1][p[0].index(l)]) idx = p[0].index(l) new_l.append(l) new_sub_profile.append(p[6][idx]) new_opt = SeqOptimizer(*new_l) new_nb_nodes = [] for p1, p2 in zip(prof1[8], prof2[8]): new_nb_nodes.append((p1[0] + p2[0], p1[1] + p2[1])) new_nb_nodes.extend(prof1[8][len(new_nb_nodes) :]) new_nb_nodes.extend(prof2[8][len(new_nb_nodes) :]) new_callbacks_times = merge_dict(prof1[9], prof2[9]) # We need to assert based on the name as we merge also based on # the name. assert {l.name for l in prof1[0]}.issubset({l.name for l in new_l}) assert {l.name for l in prof2[0]}.issubset({l.name for l in new_l}) assert len(new_t) == len(new_opt) == len(new_sub_profile) return ( new_opt, new_t, prof1[2] + prof2[2], prof1[3] + prof2[3], -1, -1, new_sub_profile, [], new_nb_nodes, new_callbacks_times, ) class MergeFeature(Feature): """Keeps track of variables in a `FunctionGraph` that cannot be merged together. That way, the `MergeOptimizer` can remember the result of the last merge-pass on the `FunctionGraph`. """ def on_attach(self, fgraph): assert not hasattr(fgraph, "merge_feature") fgraph.merge_feature = self # For constants self.seen_constants = set() # variable -> signature (for constants) self.const_sig = AssocList() # signature -> variable (for constants) self.const_sig_inv = AssocList() # For all Apply nodes # Set of distinct (not mergeable) nodes self.nodes_seen = set() # Ordered set of distinct (not mergeable) nodes without any input self.noinput_nodes = OrderedSet() # Each element of scheduled is a list of list of (out, new_out) pairs. # Each list of pairs represent the substitution needed to replace all # the outputs of a node with the outputs of a replacement candidate. # Each node can have several candidates. For instance, if "node" has # 2 outputs, and there are 3 replacement candidates, we will have: # shelf.scheduled = [ # [[(node.out1, cand1.out1), (node.out2, cand1.out2)], # [(node.out1, cand2.out1), (node.out2, cand2.out2)], # [(node.out1, cand3.out1), (node.out2, cand3.out2)]]] self.scheduled = [] # List of (node, candidate) pairs, where we tried to replace node by # candidate, but it failed. This is used to avoid infinite loops # during the replacement phase. self.blacklist = [] for node in fgraph.toposort(): self.on_import(fgraph, node, "on_attach") def on_change_input(self, fgraph, node, i, r, new_r, reason): # If inputs to node change, it is not guaranteed that it is distinct # from the other nodes in nodes_seen if node in self.nodes_seen: self.nodes_seen.discard(node) self.process_node(fgraph, node) # Since we are in on_change_input, node should have inputs. if not isinstance(node, str): assert node.inputs if isinstance(new_r, Constant): self.process_constant(fgraph, new_r) def on_import(self, fgraph, node, reason): for c in node.inputs: if isinstance(c, Constant): self.process_constant(fgraph, c) self.process_node(fgraph, node) def on_prune(self, fgraph, node, reason): self.nodes_seen.discard(node) if not node.inputs: self.noinput_nodes.discard(node) for c in node.inputs: if isinstance(c, Constant) and (len(fgraph.clients[c]) <= 1): # This was the last node using this constant sig = self.const_sig[c] self.const_sig.discard(c) self.const_sig_inv.discard(sig) self.seen_constants.discard(id(c)) def process_constant(self, fgraph, c): """Check if a constant `c` can be merged, and queue that replacement.""" if id(c) in self.seen_constants: return sig = c.merge_signature() other_c = self.const_sig_inv.get(sig, None) if other_c is not None: # multiple names will clobber each other.. # we adopt convention to keep the last name if c.name: other_c.name = c.name self.scheduled.append([[(c, other_c, "merge")]]) else: # this is a new constant self.const_sig[c] = sig self.const_sig_inv[sig] = c self.seen_constants.add(id(c)) def process_node(self, fgraph, node): """Check if a `node` can be merged, and queue that replacement.""" if node in self.nodes_seen: return node_has_assert = False # These asserts ensure that the fgraph has set the clients field # properly. # The clients should at least contain `node` itself! if node.inputs: # Take the smallest clients list. Some ops like elemwise # have optimization that put constant as the first inputs. # As constant have in general more clients than other type of nodes # using always inputs[0] make us look at more nodes. # Always pick the smallest clints list between inputs 0 # and -1 speed up optimization. a_clients = fgraph.clients[node.inputs[0]] b_clients = fgraph.clients[node.inputs[-1]] if len(a_clients) < len(b_clients): clients = a_clients else: clients = b_clients assert len(clients) > 0 merge_candidates = [c for c, i in clients if c in self.nodes_seen] # Put all clients of Assert inputs (if exist) into merge_candidates # TODO: Deactivated for now as this cause cycle in the graph. # (There is a second deactivation part below.) for i in []: # node.inputs: if i.owner and isinstance(i.owner.op, Assert): node_has_assert = True i_clients = fgraph.clients[i.owner.inputs[0]] assert_clients = [c for (c, _) in i_clients if c in self.nodes_seen] for idx in range(len(assert_clients)): client = assert_clients[idx] if isinstance(i.owner.op, Assert): o_clients = fgraph.clients[client.outputs[0]] for c in o_clients: if c[0] in self.nodes_seen: assert_clients.append(c[0]) merge_candidates.extend(assert_clients) else: # If two nodes have no input, but perform the same operation, # they are not always constant-folded, so we want to merge them. # In that case, the candidates are all the nodes without inputs. merge_candidates = self.noinput_nodes replacement_candidates = [] for candidate in merge_candidates: if candidate is node: continue if len(node.inputs) != len(candidate.inputs): continue cand_has_assert = False # Get input list of the candidate with assert removed cand_inputs_assert_removed = [] # TODO: Deactivated while Assert merging is disabled. (See above and below.) for i in []: # candidate.inputs: if i.owner and isinstance(i.owner.op, Assert): cand_has_assert = True cand_inputs_assert_removed.append(i.owner.inputs[0]) else: cand_inputs_assert_removed.append(i) # TODO: Remove this when Assert merging is re-enabled. (See above.) # Without Assert merging we can still look for identical Asserts, # so we should not treat Asserts separately for now. cand_inputs_assert_removed = candidate.inputs # Get input list of the node with assert removed if node_has_assert: node_inputs_assert_removed = [] for i in node.inputs: if i.owner and isinstance(i.owner.op, Assert): node_inputs_assert_removed.append(i.owner.inputs[0]) else: node_inputs_assert_removed.append(i) else: node_inputs_assert_removed = node.inputs inputs_match = all( node_in is cand_in for node_in, cand_in in zip( node_inputs_assert_removed, cand_inputs_assert_removed ) ) if inputs_match and node.op == candidate.op: if (node, candidate) in self.blacklist: # They were already tried, and there was an error continue # replace node with candidate if not (node_has_assert or cand_has_assert): # Schedule transfer of clients from node to candidate pairs = list( zip( node.outputs, candidate.outputs, ["merge"] * len(node.outputs), ) ) # if the current node has assert input, it should not be # replaced with a candidate node which has no assert input elif node_has_assert and not cand_has_assert: pairs = list( zip( candidate.outputs, node.outputs, ["merge"] * len(node.outputs), ) ) else: new_inputs = self.get_merged_assert_input(node, candidate) new_node = node.op(*new_inputs) pairs = list( zip( node.outputs, new_node.owner.outputs, ["new_node"] * len(node.outputs), ) ) + list( zip( candidate.outputs, new_node.owner.outputs, ["new_node"] * len(node.outputs), ) ) # transfer names for pair in pairs: node_output, cand_output = pair[:2] # clobber old name with new one # it's arbitrary... one of the names has to go if node_output.name: cand_output.name = node_output.name replacement_candidates.append(pairs) if replacement_candidates: self.scheduled.append(replacement_candidates) else: self.nodes_seen.add(node) if not node.inputs: self.noinput_nodes.add(node) def get_merged_assert_input(self, node, candidate): new_inputs = [] for node_i, cand_i in zip(node.inputs, candidate.inputs): # if node_i is assert if node_i.owner and isinstance(node_i.owner.op, Assert): # node_i is assert, cand_i is assert if cand_i.owner and isinstance(cand_i.owner.op, Assert): # Here two assert nodes are merged. # Step 1. Merge conditions of both assert nodes. # Step 2. Make the new assert node node_cond = node_i.owner.inputs[1:] cand_cond = cand_i.owner.inputs[1:] new_cond = list(set(node_cond + cand_cond)) new_inputs.append(assert_op(node_i.owner.inputs[0], *new_cond)) # node_i is assert, cand_i is not assert else: new_inputs.append(node_i) else: # if node_i is not an assert node, append cand_i new_inputs.append(cand_i) return new_inputs class MergeOptimizer(GlobalOptimizer): r"""Merges parts of the graph that are identical and redundant. The basic principle is that if two `Apply`\s have `Op`\s that compare equal, and identical inputs, then they do not both need to be computed. The clients of one are transferred to the other and one of them is removed from the graph. This procedure is carried out in input-to-output order throughout the graph. The first step of merging is constant-merging, so that all clients of an ``int(1)`` for example, are transferred to just one particular instance of ``int(1)``. """ def add_requirements(self, fgraph): if not hasattr(fgraph, "merge_feature"): fgraph.attach_feature(MergeFeature()) def apply(self, fgraph): # Constant and non-constant are now applied in the same phase. # I am not sure why, but it seems to be faster this way. sched = fgraph.merge_feature.scheduled nb_fail = 0 t0 = time.time() if fgraph.profile: validate_before = fgraph.profile.validate_time callback_before = fgraph.execute_callbacks_time callbacks_before = fgraph.execute_callbacks_times.copy() nb_merged = 0 nb_constant = 0 while sched: pairs_list = sched.pop() success = True for pairs_ in pairs_list: # We must check again the equivalence, as the graph # could've changed. If so, doing the replacement can # introduce a node that depends on itself. Doing the # full check of such cycles every time is very time # consuming. I think this double check is faster than # doing the full cycle check. The full cycle check is # skipped by validate() if the graph doesn't contain # destroyers. var, candidate, merge_mode = pairs_[0] if merge_mode == "new_node" and var in fgraph.variables: pass elif var not in fgraph.variables or candidate not in fgraph.variables: continue # Keep len(item) == 2 for item in pairs pairs = [pair[:2] for pair in pairs_] if var.owner and candidate.owner: node = var.owner candidate = candidate.owner # Get input list of the candidate node with assert # nodes removed cand_inputs_assert_removed = [] for i in candidate.inputs: if i.owner and isinstance(i.owner.op, Assert): cand_inputs_assert_removed.append(i.owner.inputs[0]) else: cand_inputs_assert_removed.append(i) # Get input list of the node with assert nodes removed node_inputs_assert_removed = [] for i in node.inputs: if i.owner and isinstance(i.owner.op, Assert): node_inputs_assert_removed.append(i.owner.inputs[0]) else: node_inputs_assert_removed.append(i) if merge_mode == "new_node": inputs_match = True else: inputs_match = all( node_in is cand_in for node_in, cand_in in zip( node_inputs_assert_removed, cand_inputs_assert_removed ) ) # No need to compare the op again, as it don't change. if not inputs_match: continue if hasattr(fgraph, "destroy_handler"): # If both nodes have clients that destroy them, we # can't merge them. clients = ( fgraph.clients[pairs[0][0]] + fgraph.clients[pairs[0][1]] ) if ( sum( [ i in flatten(c.op.destroy_map.values()) for c, i in clients if c != "output" and c.op.destroy_map ] ) > 1 ): continue if len(pairs) == 1 and pairs[0][0].type != pairs[0][1].type: res = pairs[0][0].type.convert_variable(pairs[0][1]) # Since the fgraph.replace only checks the convert_variable # in one way, we change the order in the case that # convert_variable will not be successful. if not res: pairs = [(pairs[0][1], pairs[0][0])] try: # If all Constants, no need to call validate. # Only need to check one of the var of each pairs. # If it is a Constant, the other must also be a Constant as we merge them. if all([isinstance(old, Constant) for old, new in pairs]): fgraph.replace_all(pairs, reason="MergeOptimizer") else: fgraph.replace_all_validate(pairs, reason="MergeOptimizer") except InconsistencyError: success = False nb_fail += 1 fgraph.merge_feature.blacklist.append( (pairs[0][0].owner, pairs[0][1].owner) ) if success: nb_merged += len(pairs) if isinstance(pairs[0][0], Constant): nb_constant += 1 # print pairs, pairs[0][0].type break if fgraph.profile: validate_time = fgraph.profile.validate_time - validate_before callback_time = fgraph.execute_callbacks_time - callback_before callbacks_time = {} for k, v in fgraph.execute_callbacks_times.items(): if k in callbacks_before: t = v - callbacks_before[k] if t > 0: callbacks_time[k] = t else: callbacks_time[k] = v else: validate_time = None callback_time = None callbacks_time = {} # clear blacklist fgraph.merge_feature.blacklist = [] return ( nb_fail, time.time() - t0, validate_time, callback_time, callbacks_time, nb_merged, nb_constant, ) def __str__(self): return self.__class__.__name__ @staticmethod def print_profile(stream, prof, level=0): ( nb_fail, replace_time, validate_time, callback_time, callbacks_time, nb_merged, nb_constant, ) = prof blanc = " " * level print(blanc, "MergeOptimizer", file=stream) print( blanc, f" nb fail={nb_fail:5d} merged={nb_merged:5d} constant={nb_constant:5d}", file=stream, ) print( blanc, f" time replace={replace_time:2.2f} validate={validate_time:2.2f} callback={callback_time:2.2f}", file=stream, ) if callback_time > 1: print(blanc, " callbacks_time", file=stream) for i in sorted(callbacks_time.items(), key=lambda a: a[1]): if i[1] > 0: # We want to have the __str__ called, so we can't # just print i. print(blanc, " ", i[0], ",", i[1], file=stream) @staticmethod def merge_profile(prof1, prof2): def merge_none_number(v1, v2): if v1 is None: return v2 if v2 is None: return v1 return v1 + v2 nb_fail = prof1[0] + prof2[0] replace_time = prof1[1] + prof2[1] validate_time = merge_none_number(prof1[2], prof2[2]) callback_time = merge_none_number(prof1[3], prof2[3]) callbacks_time = merge_dict(prof1[4], prof2[4]) nb_merged = prof1[5] + prof2[5] nb_constant = prof1[6] + prof2[6] return ( nb_fail, replace_time, validate_time, callback_time, callbacks_time, nb_merged, nb_constant, ) def pre_constant_merge(fgraph, variables): """Merge constants in the graphs given by `variables`. .. warning:: This changes the nodes in a graph in-place! Parameters ---------- fgraph A `FunctionGraph` instance in which some of these `variables` may reside. We want to avoid terms in `variables` that are contained in `fgraph`. The reason for that: it will break consistency of `fgraph` and its features (e.g. `ShapeFeature`). variables A list of nodes for which we want to merge constant inputs. Notes ----- It is used to pre-merge nodes generated inside an optimization. It is useful if there are many such replacements to make, so that `DebugMode` will not check each of them. """ seen_var = set() # signature -> variable (for constants) const_sig_inv = {} if isinstance(variables, Variable): variables = [variables] def recursive_merge(var): if var in seen_var: return var if not hasattr(var, "owner"): return var # We don't want to merge constants that are *within* the # `FunctionGraph` if var.owner in fgraph.apply_nodes: return var seen_var.add(var) if isinstance(var, Constant): sig = var.signature() if sig in const_sig_inv: return const_sig_inv[sig] const_sig_inv[sig] = var return var if var.owner: for idx, inp in enumerate(var.owner.inputs): # XXX: This is changing the graph in place! var.owner.inputs[idx] = recursive_merge(inp) return var return [recursive_merge(v) for v in variables] class LocalOptimizer(abc.ABC): """A node-based optimizer.""" def __hash__(self): if not hasattr(self, "_optimizer_idx"): self._optimizer_idx = _optimizer_idx[0] _optimizer_idx[0] += 1 return self._optimizer_idx def tracks(self): """Return the list of `Op` classes to which this optimization applies. Returns ``None`` when the optimization applies to all nodes. """ return None @abc.abstractmethod def transform( self, fgraph: FunctionGraph, node: Apply, *args, **kwargs ) -> Union[bool, List[Variable], Dict[Variable, Variable]]: r"""Transform a subgraph whose output is `node`. Subclasses should implement this function so that it returns one of the following: - ``False`` to indicate that no optimization can be applied to this `node`; - A list of `Variable`\s to use in place of the `node`'s current outputs. - A ``dict`` mapping old `Variable`\s to `Variable`\s. Parameters ---------- fgraph : A `FunctionGraph` containing `node`. node : An `Apply` node to be transformed. """ raise NotImplementedError() def add_requirements(self, fgraph): r"""Add required `Feature`\s to `fgraph`.""" def print_summary(self, stream=sys.stdout, level=0, depth=-1): print(f"{' ' * level}{self.__class__.__name__} id={id(self)}", file=stream) class LocalMetaOptimizer(LocalOptimizer): r""" Base class for meta-optimizers that try a set of `LocalOptimizer`\s to replace a node and choose the one that executes the fastest. If the error ``LocalMetaOptimizerSkipAssertionError`` is raised during compilation, we will skip that function compilation and not print the error. """ def __init__(self): self.verbose = config.metaopt__verbose self.track_dict = defaultdict(lambda: []) self.tag_dict = defaultdict(lambda: []) self._tracks = [] self.optimizers = [] def register(self, optimizer, tag_list): self.optimizers.append(optimizer) for c in optimizer.tracks(): self.track_dict[c].append(optimizer) self._tracks.append(c) for tag in tag_list: self.tag_dict[tag].append(optimizer) def tracks(self): return self._tracks def transform(self, fgraph, node, *args, **kwargs): # safety check: depending on registration, tracks may have been ignored if self._tracks is not None: if not isinstance(node.op, tuple(self._tracks)): return # first, we need to provide dummy values for all inputs # to the node that are not shared variables anyway givens = {} missing = set() for input in node.inputs: if isinstance(input, aesara.compile.SharedVariable): pass elif hasattr(input.tag, "test_value"): givens[input] = aesara.shared( input.type.filter(input.tag.test_value), input.name, broadcastable=input.broadcastable, borrow=True, ) else: missing.add(input) if missing: givens.update(self.provide_inputs(node, missing)) missing.difference_update(givens.keys()) # ensure we have data for all input variables that need it if missing: if self.verbose > 0: print( f"{self.__class__.__name__} cannot meta-optimize {node}, " f"{len(missing)} of {int(node.nin)} input shapes unknown" ) return # now we can apply the different optimizations in turn, # compile the resulting subgraphs and time their execution if self.verbose > 1: print( f"{self.__class__.__name__} meta-optimizing {node} ({len(self.get_opts(node))} choices):" ) timings = [] for opt in self.get_opts(node): outputs = opt.transform(fgraph, node, *args, **kwargs) if outputs: try: fn = aesara.function( [], outputs, givens=givens, on_unused_input="ignore" ) fn.trust_input = True timing = min(self.time_call(fn) for _ in range(2)) except LocalMetaOptimizerSkipAssertionError: continue except Exception as e: if self.verbose > 0: print(f"* {opt}: exception", e) continue else: if self.verbose > 1: print(f"* {opt}: {timing:.5g} sec") timings.append((timing, outputs, opt)) else: if self.verbose > 0: print(f"* {opt}: not applicable") # finally, we choose the fastest one if timings: timings.sort() if self.verbose > 1: print(f"= {timings[0][2]}") return timings[0][1] return def provide_inputs(self, node, inputs): """Return a dictionary mapping some `inputs` to `SharedVariable` instances of with dummy values. The `node` argument can be inspected to infer required input shapes. """ raise NotImplementedError() def get_opts(self, node): """Return the optimizations that apply to `node`. This uses ``self.track_dict[type(node.op)]`` by default. """ return self.track_dict[type(node.op)] def time_call(self, fn): start = time.time() fn() return time.time() - start class FromFunctionLocalOptimizer(LocalOptimizer): """A `LocalOptimizer` constructed from a function.""" def __init__(self, fn, tracks=None, requirements=()): self.fn = fn self._tracks = tracks self.requirements = requirements def transform(self, *args, **kwargs): return self.fn(*args, **kwargs) def add_requirements(self, fgraph): for req in self.requirements: req(fgraph) def tracks(self): return self._tracks def __str__(self): return getattr(self, "__name__", "<FromFunctionLocalOptimizer instance>") def print_summary(self, stream=sys.stdout, level=0, depth=-1): print(f"{' ' * level}{self.transform} id={id(self)}", file=stream) def local_optimizer( tracks: Optional[List[Union[Op, type]]], inplace: bool = False, requirements: Optional[Tuple[type, ...]] = (), ): r"""A decorator used to construct `FromFunctionLocalOptimizer` instances. Parameters ---------- tracks : The `Op` types or instances to which this optimization applies. inplace : A boolean indicating whether or not the optimization works in-place. If ``True``, a `DestroyHandler` `Feature` is added automatically added to the `FunctionGraph`\s applied to this optimization. requirements : `Feature` types required by this optimization. """ if requirements is None: requirements = () def decorator(f): if tracks is not None: if len(tracks) == 0: raise ValueError( "Use None instead of an empty list to apply to all nodes.", f.__module__, f.__name__, ) for t in tracks: if not (isinstance(t, Op) or issubclass(t, Op)): raise ValueError( "Tracks are op classes or instances", f.__module__, f.__name__ ) req = requirements if inplace: dh_handler = dh.DestroyHandler req = tuple(requirements) + ( lambda fgraph: fgraph.attach_feature(dh_handler()), ) rval = FromFunctionLocalOptimizer(f, tracks, req) rval.__name__ = f.__name__ return rval return decorator class LocalOptGroup(LocalOptimizer): r"""An optimizer that applies a list of `LocalOptimizer`\s to a node. Parameters ---------- optimizers : A list of optimizers to be applied to nodes. apply_all_opts : bool (Default False) If ``False``, it will return after the new node after the first optimizer applied. Otherwise, it will start again with the new node until no new optimization apply. profile : Whether or not to profile the optimizations. Attributes ---------- reentrant : bool Some global optimizer like `NavigatorOptimizer` can use this value to determine if it ignore new nodes during a pass on the nodes. Sometimes, ``ignore_newtrees`` is not reentrant. retains_inputs : bool States whether or not the inputs of a transformed node are transferred to the outputs. """ def __init__(self, *optimizers, apply_all_opts=False, profile=False): if len(optimizers) == 1 and isinstance(optimizers[0], list): # This happen when created by LocalGroupDB. optimizers = tuple(optimizers[0]) self.opts = optimizers assert isinstance(self.opts, tuple) self.reentrant = any(getattr(opt, "reentrant", True) for opt in optimizers) self.retains_inputs = all( getattr(opt, "retains_inputs", False) for opt in optimizers ) self.apply_all_opts = apply_all_opts self.profile = profile self.track_map = defaultdict(lambda: []) if self.profile: self.time_opts = {} self.process_count = {} self.applied_true = {} self.node_created = {} for o in self.opts: if self.profile: self.time_opts.setdefault(o, 0) self.process_count.setdefault(o, 0) self.applied_true.setdefault(o, 0) self.node_created.setdefault(o, 0) tracks = o.tracks() if tracks is None: self.track_map[None].append(o) else: for c in tracks: self.track_map[c].append(o) def __str__(self): return getattr( self, "__name__", f"LocalOptGroup({','.join([str(o) for o in self.opts])})", ) def tracks(self): t = [] for l in self.opts: aet = l.tracks() if aet: t.extend(aet) return t def transform(self, fgraph, node): if len(self.opts) == 0: return repl = None while True: opts = ( self.track_map[type(node.op)] + self.track_map[node.op] + self.track_map[None] ) new_repl = None for opt in opts: opt_start = time.time() new_repl = opt.transform(fgraph, node) opt_finish = time.time() if self.profile: self.time_opts[opt] += opt_start - opt_finish self.process_count[opt] += 1 if not new_repl: continue if isinstance(new_repl, (tuple, list)): new_vars = new_repl else: # It must be a dict new_vars = list(new_repl.values()) if self.profile: self.node_created[opt] += len( list(applys_between(fgraph.variables, new_vars)) ) self.applied_true[opt] += 1 break # break from the for loop over optimization. if not new_repl: # No optimization applied in the last iteration return repl # only 1 iteration if not self.apply_all_opts: return new_repl if not new_vars[0].owner: # We are at the start of the graph. return new_repl if len(new_repl) > 1: s = {v.owner for v in new_repl} assert len(s) == 1 repl = new_repl node = new_vars[0].owner @staticmethod def print_profile(stream, prof, level=0): (time_opts, process_count, applied_true, node_created, profile) = prof if not profile: return blanc = " " * int(level) print(blanc, "LocalOptGroup", file=stream) print(blanc, "---------------------", file=stream) count_opt = [] not_used = [] not_used_time = 0 for o, count in process_count.items(): if count > 0: count_opt.append( (time_opts[o], applied_true[o], count, o, node_created[o]) ) else: not_used.append((time_opts[o], o)) not_used_time += time_opts[o] if count_opt: print( blanc, " time taken - times applied - times tried - name - node_created:", file=stream, ) count_opt.sort() for (t, a_t, count, o, n_c) in count_opt[::-1]: print( blanc, f" {t:.3f}s - {int(a_t)} - {int(count)} - {o} - {int(n_c)}", file=stream, ) print( blanc, f" {not_used_time:.3f}s - in {len(not_used)} optimization that were not used (display those with runtime greater than 0)", file=stream, ) not_used.sort(key=lambda nu: (nu[0], str(nu[1]))) for (t, o) in not_used[::-1]: if t > 0: # Skip opt that have 0 times, they probably wasn't even tried. print(blanc + " ", f" {t:.3f}s - {o}", file=stream) else: print(blanc, " The optimizer wasn't successful ", file=stream) print(file=stream) def merge_profile(prof1, prof2): raise NotImplementedError def print_summary(self, stream=sys.stdout, level=0, depth=-1): print(f"{' ' * level}{self.__class__.__name__} id={id(self)}", file=stream) if depth != 0: depth -= 1 for lopt in self.opts: lopt.print_summary(stream, level=(level + 2), depth=depth) def add_requirements(self, fgraph): for opt in self.opts: opt.add_requirements(fgraph) class GraphToGPULocalOptGroup(LocalOptGroup): """This is the equivalent of `LocalOptGroup` for `GraphToGPU`. The main different is the function signature of the local optimizer that use the `GraphToGPU` signature and not the normal `LocalOptimizer` signature. ``apply_all_opts=True`` is not supported """ def __init__(self, *optimizers, **kwargs): super().__init__(*optimizers, **kwargs) assert self.apply_all_opts is False def transform(self, fgraph, op, context_name, inputs, outputs): if len(self.opts) == 0: return opts = self.track_map[type(op)] + self.track_map[op] + self.track_map[None] for opt in opts: opt_start = time.time() new_repl = opt.transform(fgraph, op, context_name, inputs, outputs) opt_finish = time.time() if self.profile: self.time_opts[opt] += opt_start - opt_finish self.process_count[opt] += 1 if not new_repl: continue if self.profile: self.node_created[opt] += len( list(applys_between(fgraph.variables, new_repl)) ) self.applied_true[opt] += 1 return new_repl class OpSub(LocalOptimizer): """ Replaces the application of a certain `Op` by the application of another `Op` that takes the same inputs as what it is replacing. Parameters ---------- op1, op2 ``op1.make_node`` and ``op2.make_node`` must take the same number of inputs and have the same number of outputs. Examples -------- OpSub(add, sub) ==> add(div(x, y), add(y, x)) -> sub(div(x, y), sub(y, x)) """ # an OpSub does not apply to the nodes it produces reentrant = False # all the inputs of the original node are transferred to the outputs retains_inputs = True def __init__(self, op1, op2, transfer_tags=True): self.op1 = op1 self.op2 = op2 self.transfer_tags = transfer_tags def op_key(self): return self.op1 def tracks(self): return [self.op1] def transform(self, fgraph, node): if node.op != self.op1: return False repl = self.op2.make_node(*node.inputs) if self.transfer_tags: repl.tag = copy.copy(node.tag) for output, new_output in zip(node.outputs, repl.outputs): new_output.tag = copy.copy(output.tag) return repl.outputs def __str__(self): return f"{self.op1} -> {self.op2}" class OpRemove(LocalOptimizer): """ Removes all applications of an `Op` by transferring each of its outputs to the corresponding input. """ reentrant = False # no nodes are added at all def __init__(self, op): self.op = op def op_key(self): return self.op def tracks(self): return [self.op] def transform(self, fgraph, node): if node.op != self.op: return False return node.inputs def __str__(self): return f"{self.op}(x) -> x" def print_summary(self, stream=sys.stdout, level=0, depth=-1): print( f"{' ' * level}{self.__class__.__name__}(self.op) id={id(self)}", file=stream, ) class PatternSub(LocalOptimizer): """ @todo update Replaces all occurrences of the input pattern by the output pattern: input_pattern ::= (op, <sub_pattern1>, <sub_pattern2>, ...) input_pattern ::= dict(pattern = <input_pattern>, constraint = <constraint>) sub_pattern ::= input_pattern sub_pattern ::= string sub_pattern ::= a Constant instance sub_pattern ::= int sub_pattern ::= float constraint ::= lambda fgraph, expr: additional matching condition output_pattern ::= (op, <output_pattern1>, <output_pattern2>, ...) output_pattern ::= string output_pattern ::= int output_pattern ::= float Each string in the input pattern is a variable that will be set to whatever expression is found in its place. If the same string is used more than once, the same expression must be found in those places. If a string used in the input pattern is used in the output pattern, the matching expression will be inserted in its place. The input pattern cannot just be a string but the output pattern can. If you put a constant variable in the input pattern, there will be a match iff a constant variable with the same value and the same type is found in its place. You can add a constraint to the match by using the ``dict(...)`` form described above with a ``'constraint'`` key. The constraint must be a function that takes the fgraph and the current Variable that we are trying to match and returns True or False according to an arbitrary criterion. The constructor creates a `PatternSub` that replaces occurrences of `in_pattern` by occurrences of `out_pattern`. Parameters ---------- in_pattern : The input pattern that we want to replace. out_pattern : The replacement pattern. allow_multiple_clients : bool If False, the pattern matching will fail if one of the subpatterns has more than one client. skip_identities_fn : TODO name : Allows to override this optimizer name. pdb : bool If True, we invoke pdb when the first node in the pattern matches. tracks : optional The values that :meth:`self.tracks` will return. Useful to speed up optimization sometimes. get_nodes : optional If you provide `tracks`, you must provide this parameter. It must be a function that takes the tracked node and returns a list of nodes on which we will try this optimizer. Notes ----- `tracks` and `get_nodes` can be used to make this optimizer track a less frequent `Op`, so this will make this optimizer tried less frequently. Examples -------- PatternSub((add, 'x', 'y'), (add, 'y', 'x')) PatternSub((multiply, 'x', 'x'), (square, 'x')) PatternSub((subtract, (add, 'x', 'y'), 'y'), 'x') PatternSub((power, 'x', Constant(double, 2.0)), (square, 'x')) PatternSub((boggle, {'pattern': 'x', 'constraint': lambda expr: expr.type == scrabble}), (scrabble, 'x')) """ def __init__( self, in_pattern, out_pattern, allow_multiple_clients=False, skip_identities_fn=None, name=None, pdb=False, tracks=(), get_nodes=None, values_eq_approx=None, ): self.in_pattern = in_pattern self.out_pattern = out_pattern self.values_eq_approx = values_eq_approx if isinstance(in_pattern, (list, tuple)): self.op = self.in_pattern[0] elif isinstance(in_pattern, dict): self.op = self.in_pattern["pattern"][0] else: raise TypeError( "The pattern to search for must start with a specific Op instance." ) self.__doc__ = ( self.__class__.__doc__ + "\n\nThis instance does: " + str(self) + "\n" ) self.allow_multiple_clients = allow_multiple_clients self.skip_identities_fn = skip_identities_fn if name: self.__name__ = name self.pdb = pdb self._tracks = tracks self.get_nodes = get_nodes if tracks != (): assert get_nodes def op_key(self): return self.op def tracks(self): if self._tracks != (): return self._tracks return [self.op] def transform(self, fgraph, node, get_nodes=True): """Check if the graph from node corresponds to ``in_pattern``. If it does, it constructs ``out_pattern`` and performs the replacement. """ from aesara.graph import unify if get_nodes and self.get_nodes is not None: for real_node in self.get_nodes(fgraph, node): if real_node == "output": continue ret = self.transform(fgraph, real_node, get_nodes=False) if ret is not False and ret is not None: return dict(zip(real_node.outputs, ret)) if node.op != self.op: return False # TODO: if we remove pdb, do this speed things up? def match(pattern, expr, u, allow_multiple_clients=False, pdb=False): # TODO move outside match def retry_with_equiv(): if not self.skip_identities_fn: return False expr_equiv = self.skip_identities_fn(expr) if expr_equiv is None: return False # TODO: Not sure how to handle multiple_clients flag return match( pattern, expr_equiv, u, allow_multiple_clients=allow_multiple_clients, ) if isinstance(pattern, (list, tuple)): if expr.owner is None: return False if not (expr.owner.op == pattern[0]) or ( not allow_multiple_clients and len(fgraph.clients[expr]) > 1 ): return retry_with_equiv() if len(pattern) - 1 != len(expr.owner.inputs): return retry_with_equiv() for p, v in zip(pattern[1:], expr.owner.inputs): u = match(p, v, u, self.allow_multiple_clients) if not u: return False elif isinstance(pattern, dict): try: real_pattern = pattern["pattern"] except KeyError: raise KeyError( f"Malformed pattern: {pattern} (expected key 'pattern')" ) constraint = pattern.get("constraint", lambda expr: True) if constraint(expr): return match( real_pattern, expr, u, pattern.get("allow_multiple_clients", allow_multiple_clients), ) else: return retry_with_equiv() elif isinstance(pattern, str): v = unify.Var(pattern) if u[v] is not v and u[v] is not expr: return retry_with_equiv() else: u = u.merge(expr, v) elif isinstance(pattern, (int, float)) and isinstance(expr, Constant): if np.all(aesara.tensor.constant(pattern).value == expr.value): return u else: return retry_with_equiv() elif ( isinstance(pattern, Constant) and isinstance(expr, Constant) and pattern.equals(expr) ): return u else: return retry_with_equiv() if pdb: import pdb pdb.set_trace() return u u = match(self.in_pattern, node.out, unify.Unification(), True, self.pdb) if not u: return False def build(pattern, u): if isinstance(pattern, (list, tuple)): args = [build(p, u) for p in pattern[1:]] return pattern[0](*args) elif isinstance(pattern, str): return u[unify.Var(pattern)] elif isinstance(pattern, (int, float)): return pattern else: return pattern.clone() ret = build(self.out_pattern, u) if isinstance(ret, (int, float)): # TODO: Should we convert these to constants explicitly? return [ret] if self.values_eq_approx: ret.tag.values_eq_approx = self.values_eq_approx if ret.owner: if [out.type for out in ret.owner.outputs] != [ out.type for out in node.outputs ]: return False else: # ret is just an input variable assert len(node.outputs) == 1 if ret.type != node.outputs[0].type: return False return [ret] def __str__(self): if getattr(self, "__name__", None): return self.__name__ def pattern_to_str(pattern): if isinstance(pattern, (list, tuple)): return "{}({})".format( str(pattern[0]), ", ".join([pattern_to_str(p) for p in pattern[1:]]), ) elif isinstance(pattern, dict): return "{} subject to {}".format( pattern_to_str(pattern["pattern"]), str(pattern.get("constraint", "no conditions")), ) else: return str(pattern) return "{} -> {}".format( pattern_to_str(self.in_pattern), pattern_to_str(self.out_pattern), ) def __repr__(self): return str(self) def print_summary(self, stream=sys.stdout, level=0, depth=-1): name = getattr(self, "__name__", getattr(self, "name", None)) print( f"{' ' * level}{self.__class__.__name__} {name}({self.in_pattern}, {self.out_pattern}) id={id(self)}", file=stream, ) class Updater(Feature): def __init__(self, importer, pruner, chin, name=None): self.importer = importer self.pruner = pruner self.chin = chin self.name = name def __str__(self): return "Updater{%s}" % str(self.name) def on_import(self, fgraph, node, reason): if self.importer: self.importer(node) def on_prune(self, fgraph, node, reason): if self.pruner: self.pruner(node) def on_change_input(self, fgraph, node, i, r, new_r, reason): if self.chin: self.chin(node, i, r, new_r, reason) def on_detach(self, fgraph): # To allow pickling this object self.importer = None self.pruner = None self.chin = None class NavigatorOptimizer(GlobalOptimizer): r"""An optimizer that applies a `LocalOptimizer` with considerations for the new nodes it creates. This optimizer also allows the `LocalOptimizer` to use a special ``"remove"`` value in the ``dict``\s returned by :meth:`LocalOptimizer`. `Variable`\s mapped to this value are removed from the `FunctionGraph`. Parameters ---------- local_opt : A `LocalOptimizer` to apply over a `FunctionGraph` (or ``None``). ignore_newtrees : - ``True``: new subgraphs returned by an optimization are not a candidate for optimization. - ``False``: new subgraphs returned by an optimization is a candidate for optimization. - ``'auto'``: let the `local_opt` set this parameter via its :attr:`reentrant` attribute. failure_callback A function with the signature ``(exception, navigator, [(old, new), (old,new),...])`` that is called when there's an exception. If the exception is raised in ``local_opt.transform``, the ``new`` variables will be ``None``. If the exception is raised during validation (e.g. the new types don't match) then the new variables will be the ones created by ``self.transform``. If this parameter is ``None``, then exceptions are not caught here and are raised normally. """ @staticmethod def warn(exc, nav, repl_pairs, local_opt, node): """A failure callback that prints a traceback.""" if config.on_opt_error != "ignore": _logger.error(f"Optimization failure due to: {local_opt}") _logger.error(f"node: {node}") _logger.error("TRACEBACK:") _logger.error(traceback.format_exc()) if config.on_opt_error == "pdb": pdb.post_mortem(sys.exc_info()[2]) elif isinstance(exc, AssertionError) or config.on_opt_error == "raise": # We always crash on AssertionError because something may be # seriously wrong if such an exception is raised. raise exc @staticmethod def warn_inplace(exc, nav, repl_pairs, local_opt, node): r"""A failure callback that ignores ``InconsistencyError``\s and prints a traceback. If the error occurred during replacement, ``repl_pairs`` is set; otherwise, its value is ``None``. """ if isinstance(exc, InconsistencyError): return return NavigatorOptimizer.warn(exc, nav, repl_pairs, local_opt, node) @staticmethod def warn_ignore(exc, nav, repl_pairs, local_opt, node): """A failure callback that ignores all errors.""" def __init__(self, local_opt, ignore_newtrees="auto", failure_callback=None): self.local_opt = local_opt if ignore_newtrees == "auto": self.ignore_newtrees = not getattr(local_opt, "reentrant", True) else: self.ignore_newtrees = ignore_newtrees self.failure_callback = failure_callback def attach_updater(self, fgraph, importer, pruner, chin=None, name=None): r"""Install `FunctionGraph` listeners to help the navigator deal with the ``ignore_trees``-related functionality. Parameters ---------- importer : Function that will be called whenever optimizations add stuff to the graph. pruner : Function to be called when optimizations remove stuff from the graph. chin : "on change input" called whenever a node's inputs change. name : name of the ``Updater`` to attach. Returns ------- The `FunctionGraph` plugin that handles the three tasks. Keep this around so that `Feature`\s can be detached later. """ if self.ignore_newtrees: importer = None if importer is None and pruner is None: return None u = Updater(importer, pruner, chin, name=name) fgraph.attach_feature(u) return u def detach_updater(self, fgraph, u): """Undo the work of ``attach_updater``. Parameters ---------- fgraph The `FunctionGraph`. u A return-value of ``attach_updater``. Returns ------- None """ if u is not None: fgraph.remove_feature(u) def process_node(self, fgraph, node, lopt=None): r"""Apply `lopt` to `node`. The :meth:`lopt.transform` method will return either ``False`` or a list of `Variable`\s that are intended to replace :attr:`node.outputs`. If the `fgraph` accepts the replacement, then the optimization is successful, and this function returns ``True``. If there are no replacement candidates or the `fgraph` rejects the replacements, this function returns ``False``. Parameters ---------- fgraph : A `FunctionGraph`. node : An `Apply` instance in `fgraph` lopt : A `LocalOptimizer` instance that may have a better idea for how to compute node's outputs. Returns ------- bool ``True`` iff the `node`'s outputs were replaced in the `fgraph`. """ lopt = lopt or self.local_opt try: replacements = lopt.transform(fgraph, node) except Exception as e: if self.failure_callback is not None: self.failure_callback( e, self, [(x, None) for x in node.outputs], lopt, node ) return False else: raise if replacements is False or replacements is None: return False old_vars = node.outputs remove = [] if isinstance(replacements, dict): if "remove" in replacements: remove = replacements.pop("remove") old_vars = list(replacements.keys()) replacements = list(replacements.values()) elif not isinstance(replacements, (tuple, list)): raise TypeError( f"Optimizer {lopt} gave wrong type of replacement. " f"Expected list or tuple. Got {replacements}" ) if len(old_vars) != len(replacements): raise ValueError(f"Optimizer {lopt} gave wrong number of replacements") # None in the replacement mean that this variable isn't used # and we want to remove it for r, rnew in zip(old_vars, replacements): if rnew is None and len(fgraph.clients[r]) > 0: raise ValueError( "A local optimizer tried to remove a Variable that is used" ) # If an output would be replaced by itself, no need to perform # the replacement repl_pairs = [ (r, rnew) for r, rnew in zip(old_vars, replacements) if rnew is not r and rnew is not None ] if len(repl_pairs) == 0: return False try: fgraph.replace_all_validate_remove(repl_pairs, reason=lopt, remove=remove) return True except Exception as e: # This means the replacements were rejected by the fgraph. # # This is not supposed to happen. The default failure_callback # will print a traceback as a warning. if self.failure_callback is not None: self.failure_callback(e, self, repl_pairs, lopt, node) return False else: raise def add_requirements(self, fgraph): super().add_requirements(fgraph) # Added by default # fgraph.attach_feature(ReplaceValidate()) if self.local_opt: self.local_opt.add_requirements(fgraph) def print_summary(self, stream=sys.stdout, level=0, depth=-1): print(f"{' ' * level}{self.__class__.__name__} id={id(self)}", file=stream) if depth != 0: self.local_opt.print_summary(stream, level=(level + 2), depth=(depth - 1)) class TopoOptimizer(NavigatorOptimizer): """An optimizer that applies a single `LocalOptimizer` to each node in topological order (or reverse).""" def __init__( self, local_opt, order="in_to_out", ignore_newtrees=False, failure_callback=None ): if order not in ["out_to_in", "in_to_out"]: raise ValueError("order must be 'out_to_in' or 'in_to_out'") self.order = order super().__init__(local_opt, ignore_newtrees, failure_callback) def apply(self, fgraph, start_from=None): if start_from is None: start_from = fgraph.outputs callback_before = fgraph.execute_callbacks_time nb_nodes_start = len(fgraph.apply_nodes) t0 = time.time() q = deque(io_toposort(fgraph.inputs, start_from)) io_t = time.time() - t0 def importer(node): if node is not current_node: q.append(node) u = self.attach_updater( fgraph, importer, None, name=getattr(self, "name", None) ) nb = 0 try: t0 = time.time() while q: if self.order == "out_to_in": node = q.pop() else: node = q.popleft() if node not in fgraph.apply_nodes: continue current_node = node nb += self.process_node(fgraph, node) loop_t = time.time() - t0 finally: self.detach_updater(fgraph, u) callback_time = fgraph.execute_callbacks_time - callback_before nb_nodes_end = len(fgraph.apply_nodes) return ( self, nb, nb_nodes_start, nb_nodes_end, io_t, loop_t, callback_time, self.local_opt, ) @staticmethod def print_profile(stream, prof, level=0): blanc = " " * level if prof is None: # Happen as merge_profile() isn't implemented print(blanc, "TopoOptimizer merge_profile not implemented", file=stream) return ( opt, nb, nb_nodes_start, nb_nodes_end, io_t, loop_t, callback_time, lopt, ) = prof print( blanc, "TopoOptimizer ", getattr(opt, "name", getattr(opt, "__name__", "")), file=stream, ) print( blanc, " nb_node (start, end, changed)", (nb_nodes_start, nb_nodes_end, nb), file=stream, ) print(blanc, " init io_toposort", io_t, file=stream) print(blanc, " loop time", loop_t, file=stream) print(blanc, " callback_time", callback_time, file=stream) if isinstance(lopt, LocalOptGroup): if lopt.profile: lopt.print_profile( stream, ( lopt.time_opts, lopt.process_count, lopt.applied_true, lopt.node_created, lopt.profile, ), level=level + 1, ) def __str__(self): return getattr(self, "__name__", "<TopoOptimizer instance>") def topogroup_optimizer(order, *local_opts, name=None, **kwargs): """Apply `local_opts` from the input/output nodes to the output/input nodes of a graph. This uses a combination of `LocalOptGroup` and `TopoOptimizer`. """ if len(local_opts) > 1: # Don't wrap it uselessly if their is only 1 optimization. local_opts = LocalOptGroup(*local_opts) else: (local_opts,) = local_opts if not name: name = local_opts.__name__ ret = TopoOptimizer( local_opts, order="in_to_out", failure_callback=TopoOptimizer.warn_inplace, **kwargs, ) if name: ret.__name__ = name return ret in2out = partial(topogroup_optimizer, "in_to_out") out2in = partial(topogroup_optimizer, "out_to_in") class OpKeyOptimizer(NavigatorOptimizer): r"""An optimizer that applies a `LocalOptimizer` to specific `Op`\s. The `Op`\s are provided by a :meth:`LocalOptimizer.op_key` method (either as a list of `Op`\s or a single `Op`), and discovered within a `FunctionGraph` using the `NodeFinder` `Feature`. This is similar to the ``tracks`` feature used by other optimizers. """ def __init__(self, local_opt, ignore_newtrees=False, failure_callback=None): if not hasattr(local_opt, "op_key"): raise TypeError(f"{local_opt} must have an `op_key` method.") super().__init__(local_opt, ignore_newtrees, failure_callback) def apply(self, fgraph): op = self.local_opt.op_key() if isinstance(op, (list, tuple)): q = reduce(list.__iadd__, map(fgraph.get_nodes, op)) else: q = list(fgraph.get_nodes(op)) def importer(node): if node is not current_node: if node.op == op: q.append(node) u = self.attach_updater( fgraph, importer, None, name=getattr(self, "name", None) ) try: while q: node = q.pop() if node not in fgraph.apply_nodes: continue current_node = node self.process_node(fgraph, node) finally: self.detach_updater(fgraph, u) def add_requirements(self, fgraph): super().add_requirements(fgraph) fgraph.attach_feature(NodeFinder()) class ChangeTracker(Feature): def __init__(self): self.changed = False self.nb_imported = 0 def on_import(self, fgraph, node, reason): self.nb_imported += 1 self.changed = True def on_change_input(self, fgraph, node, i, r, new_r, reason): self.changed = True def reset(self): self.changed = False def on_attach(self, fgraph): fgraph.change_tracker = self def on_detach(self, fgraph): del fgraph.change_tracker def merge_dict(d1, d2): r"""Merge two ``dict``\s by adding their values.""" d = d1.copy() for k, v in d2.items(): if k in d: d[k] += v else: d[k] = v return d class EquilibriumOptimizer(NavigatorOptimizer): """An optimizer that applies an optimization until a fixed-point/equilibrium is reached. Parameters ---------- optimizers : list or set Local or global optimizations to apply until equilibrium. The global optimizer will be run at the start of each iteration before the local optimizer. max_use_ratio : int or float Each optimizer can be applied at most ``(size of graph * this number)`` times. ignore_newtrees : See :attr:`EquilibriumDB.ignore_newtrees`. final_optimizers : Global optimizers that will be run after each iteration. cleanup_optimizers : Global optimizers that apply a list of pre determined optimization. They must not traverse the graph as they are called very frequently. The MergeOptimizer is one example of optimization that respect this. They are applied after all global optimizers, then when one local optimizer is applied, then after all final optimizers. """ def __init__( self, optimizers, failure_callback=None, ignore_newtrees=True, tracks_on_change_inputs=False, max_use_ratio=None, final_optimizers=None, cleanup_optimizers=None, ): super().__init__( None, ignore_newtrees=ignore_newtrees, failure_callback=failure_callback ) self.local_optimizers_map = OrderedDict() self.local_optimizers_all = [] self.global_optimizers = [] self.final_optimizers = [] self.cleanup_optimizers = [] self.tracks_on_change_inputs = tracks_on_change_inputs for opt in optimizers: if isinstance(opt, LocalOptimizer): if opt.tracks() is None: self.local_optimizers_all.append(opt) else: for c in opt.tracks(): self.local_optimizers_map.setdefault(c, []).append(opt) else: self.global_optimizers.append(opt) if final_optimizers: self.final_optimizers = final_optimizers if cleanup_optimizers: self.cleanup_optimizers = cleanup_optimizers self.max_use_ratio = max_use_ratio assert self.max_use_ratio is not None, "max_use_ratio has to be a number" def get_local_optimizers(self): for opt in self.local_optimizers_all: yield opt # if repeat is not a problem we can drop the set s = set() for lopt in self.local_optimizers_map.values(): for opt in lopt: if opt not in s: yield opt s.add(opt) def add_requirements(self, fgraph): super().add_requirements(fgraph) for opt in self.get_local_optimizers(): opt.add_requirements(fgraph) for opt in self.global_optimizers: opt.add_requirements(fgraph) for opt in self.final_optimizers: opt.add_requirements(fgraph) for opt in self.cleanup_optimizers: opt.add_requirements(fgraph) def apply(self, fgraph, start_from=None): change_tracker = ChangeTracker() fgraph.attach_feature(change_tracker) if start_from is None: start_from = fgraph.outputs else: for node in start_from: assert node in fgraph.outputs changed = True max_use_abort = False opt_name = None global_process_count = {} start_nb_nodes = len(fgraph.apply_nodes) max_nb_nodes = len(fgraph.apply_nodes) max_use = max_nb_nodes * self.max_use_ratio loop_timing = [] loop_process_count = [] global_opt_timing = [] time_opts = {} io_toposort_timing = [] nb_nodes = [] node_created = {} global_sub_profs = [] final_sub_profs = [] cleanup_sub_profs = [] for opt in ( self.global_optimizers + list(self.get_local_optimizers()) + self.final_optimizers + self.cleanup_optimizers ): global_process_count.setdefault(opt, 0) time_opts.setdefault(opt, 0) node_created.setdefault(opt, 0) def apply_cleanup(profs_dict): changed = False for copt in self.cleanup_optimizers: change_tracker.reset() nb = change_tracker.nb_imported t_opt = time.time() sub_prof = copt.apply(fgraph) time_opts[copt] += time.time() - t_opt profs_dict[copt].append(sub_prof) if change_tracker.changed: process_count.setdefault(copt, 0) process_count[copt] += 1 global_process_count[copt] += 1 changed = True node_created[copt] += change_tracker.nb_imported - nb return changed while changed and not max_use_abort: process_count = {} t0 = time.time() changed = False iter_cleanup_sub_profs = {} for copt in self.cleanup_optimizers: iter_cleanup_sub_profs[copt] = [] # apply global optimizers sub_profs = [] for gopt in self.global_optimizers: change_tracker.reset() nb = change_tracker.nb_imported t_opt = time.time() sub_prof = gopt.apply(fgraph) time_opts[gopt] += time.time() - t_opt sub_profs.append(sub_prof) if change_tracker.changed: process_count.setdefault(gopt, 0) process_count[gopt] += 1 global_process_count[gopt] += 1 changed = True node_created[gopt] += change_tracker.nb_imported - nb if global_process_count[gopt] > max_use: max_use_abort = True opt_name = getattr(gopt, "name", None) or getattr( gopt, "__name__", "" ) global_sub_profs.append(sub_profs) global_opt_timing.append(float(time.time() - t0)) # apply clean up as global opt can have done changes that # request that changed |= apply_cleanup(iter_cleanup_sub_profs) # apply local optimizer topo_t0 = time.time() q = deque(io_toposort(fgraph.inputs, start_from)) io_toposort_timing.append(time.time() - topo_t0) nb_nodes.append(len(q)) max_nb_nodes = max(max_nb_nodes, len(q)) max_use = max_nb_nodes * self.max_use_ratio def importer(node): if node is not current_node: q.append(node) chin = None if self.tracks_on_change_inputs: def chin(node, i, r, new_r, reason): if node is not current_node and not isinstance(node, str): q.append(node) u = self.attach_updater( fgraph, importer, None, chin=chin, name=getattr(self, "name", None) ) try: while q: node = q.pop() if node not in fgraph.apply_nodes: continue current_node = node for lopt in ( self.local_optimizers_all + self.local_optimizers_map.get(type(node.op), []) + self.local_optimizers_map.get(node.op, []) ): nb = change_tracker.nb_imported t_opt = time.time() lopt_change = self.process_node(fgraph, node, lopt) time_opts[lopt] += time.time() - t_opt if not lopt_change: continue process_count.setdefault(lopt, 0) process_count[lopt] += 1 global_process_count[lopt] += 1 changed = True node_created[lopt] += change_tracker.nb_imported - nb changed |= apply_cleanup(iter_cleanup_sub_profs) if global_process_count[lopt] > max_use: max_use_abort = True opt_name = getattr(lopt, "name", None) or getattr( lopt, "__name__", "" ) if node not in fgraph.apply_nodes: # go to next node break finally: self.detach_updater(fgraph, u) # Apply final optimizers sub_profs = [] t_before_final_opt = time.time() for gopt in self.final_optimizers: change_tracker.reset() nb = change_tracker.nb_imported t_opt = time.time() sub_prof = gopt.apply(fgraph) time_opts[gopt] += time.time() - t_opt sub_profs.append(sub_prof) if change_tracker.changed: process_count.setdefault(gopt, 0) process_count[gopt] += 1 global_process_count[gopt] += 1 changed = True node_created[gopt] += change_tracker.nb_imported - nb if global_process_count[gopt] > max_use: max_use_abort = True opt_name = getattr(gopt, "name", None) or getattr( gopt, "__name__", "" ) final_sub_profs.append(sub_profs) global_opt_timing[-1] += time.time() - t_before_final_opt # apply clean up as final opt can have done changes that # request that changed |= apply_cleanup(iter_cleanup_sub_profs) # merge clean up profiles during that iteration. c_sub_profs = [] for copt, sub_profs in iter_cleanup_sub_profs.items(): sub_prof = sub_profs[0] for s_p in sub_profs[1:]: sub_prof = copt.merge_profile(sub_prof, s_p) c_sub_profs.append(sub_prof) cleanup_sub_profs.append(c_sub_profs) loop_process_count.append(process_count) loop_timing.append(float(time.time() - t0)) end_nb_nodes = len(fgraph.apply_nodes) if max_use_abort: msg = ( f"EquilibriumOptimizer max'ed out by '{opt_name}'" + ". You can safely raise the current threshold of " + "{config.optdb__max_use_ratio:f} with the aesara flag 'optdb__max_use_ratio'." ) if config.on_opt_error == "raise": raise AssertionError(msg) else: _logger.error(msg) fgraph.remove_feature(change_tracker) assert len(loop_process_count) == len(loop_timing) assert len(loop_process_count) == len(global_opt_timing) assert len(loop_process_count) == len(nb_nodes) assert len(loop_process_count) == len(io_toposort_timing) assert len(loop_process_count) == len(global_sub_profs) assert len(loop_process_count) == len(final_sub_profs) assert len(loop_process_count) == len(cleanup_sub_profs) return ( self, loop_timing, loop_process_count, (start_nb_nodes, end_nb_nodes, max_nb_nodes), global_opt_timing, nb_nodes, time_opts, io_toposort_timing, node_created, global_sub_profs, final_sub_profs, cleanup_sub_profs, ) def print_summary(self, stream=sys.stdout, level=0, depth=-1): name = getattr(self, "name", None) print( f"{' ' * level}{self.__class__.__name__} {name} id={id(self)}", file=stream ) if depth != 0: for lopt in self.get_local_optimizers(): lopt.print_summary(stream, level=(level + 2), depth=(depth - 1)) @staticmethod def print_profile(stream, prof, level=0): ( opt, loop_timing, loop_process_count, (start_nb_nodes, end_nb_nodes, max_nb_nodes), global_opt_timing, nb_nodes, time_opts, io_toposort_timing, node_created, global_sub_profs, final_sub_profs, cleanup_sub_profs, ) = prof blanc = " " * level print(blanc, "EquilibriumOptimizer", end=" ", file=stream) print(blanc, getattr(opt, "name", getattr(opt, "__name__", "")), file=stream) print( blanc, f" time {sum(loop_timing):.3f}s for {len(loop_timing)} passes", file=stream, ) print( blanc, f" nb nodes (start, end, max) {int(start_nb_nodes)} {int(end_nb_nodes)} {int(max_nb_nodes)}", file=stream, ) print(blanc, f" time io_toposort {sum(io_toposort_timing):.3f}s", file=stream) s = sum([time_opts[o] for o in opt.get_local_optimizers()]) print(blanc, f" time in local optimizers {s:.3f}s", file=stream) s = sum([time_opts[o] for o in opt.global_optimizers]) print(blanc, f" time in global optimizers {s:.3f}s", file=stream) s = sum([time_opts[o] for o in opt.final_optimizers]) print(blanc, f" time in final optimizers {s:.3f}s", file=stream) s = sum([time_opts[o] for o in opt.cleanup_optimizers]) print(blanc, f" time in cleanup optimizers {s:.3f}s", file=stream) for i in range(len(loop_timing)): lopt = "" if loop_process_count[i]: d = list( reversed(sorted(loop_process_count[i].items(), key=lambda a: a[1])) ) lopt = " ".join([str((str(k), v)) for k, v in d[:5]]) if len(d) > 5: lopt += " ..." print( blanc, ( f" {int(i):2d} - {loop_timing[i]:.3f}s {int(sum(loop_process_count[i].values()))} ({global_opt_timing[i]:.3f}s in global opts, " f"{io_toposort_timing[i]:.3f}s io_toposort) - {int(nb_nodes[i])} nodes - {lopt}" ), file=stream, ) count_opt = [] not_used = [] not_used_time = 0 process_count = {} for o in ( opt.global_optimizers + list(opt.get_local_optimizers()) + list(opt.final_optimizers) + list(opt.cleanup_optimizers) ): process_count.setdefault(o, 0) for count in loop_process_count: for o, v in count.items(): process_count[o] += v for o, count in process_count.items(): if count > 0: count_opt.append((time_opts[o], count, node_created[o], o)) else: not_used.append((time_opts[o], o)) not_used_time += time_opts[o] if count_opt: print( blanc, " times - times applied - nb node created - name:", file=stream ) count_opt.sort() for (t, count, n_created, o) in count_opt[::-1]: print( blanc, f" {t:.3f}s - {int(count)} - {int(n_created)} - {o}", file=stream, ) print( blanc, f" {not_used_time:.3f}s - in {len(not_used)} optimization that were not used (display only those with a runtime > 0)", file=stream, ) not_used.sort(key=lambda nu: (nu[0], str(nu[1]))) for (t, o) in not_used[::-1]: if t > 0: # Skip opt that have 0 times, they probably wasn't even tried. print(blanc + " ", f" {t:.3f}s - {o}", file=stream) print(file=stream) gf_opts = [ o for o in ( opt.global_optimizers + list(opt.final_optimizers) + list(opt.cleanup_optimizers) ) if o.print_profile.__code__ is not GlobalOptimizer.print_profile.__code__ ] if not gf_opts: return print(blanc, "Global, final and clean up optimizers", file=stream) for i in range(len(loop_timing)): print(blanc, f"Iter {int(i)}", file=stream) for o, prof in zip(opt.global_optimizers, global_sub_profs[i]): try: o.print_profile(stream, prof, level + 2) except NotImplementedError: print(blanc, "merge not implemented for ", o) for o, prof in zip(opt.final_optimizers, final_sub_profs[i]): try: o.print_profile(stream, prof, level + 2) except NotImplementedError: print(blanc, "merge not implemented for ", o) for o, prof in zip(opt.cleanup_optimizers, cleanup_sub_profs[i]): try: o.print_profile(stream, prof, level + 2) except NotImplementedError: print(blanc, "merge not implemented for ", o) @staticmethod def merge_profile(prof1, prof2): # (opt, loop_timing, loop_process_count, max_nb_nodes, # global_opt_timing, nb_nodes, time_opts, io_toposort_timing) = prof1 local_optimizers = OrderedSet(prof1[0].get_local_optimizers()).union( prof2[0].get_local_optimizers() ) global_optimizers = OrderedSet(prof1[0].global_optimizers).union( prof2[0].global_optimizers ) final_optimizers = list( OrderedSet(prof1[0].final_optimizers).union(prof2[0].final_optimizers) ) cleanup_optimizers = list( OrderedSet(prof1[0].cleanup_optimizers).union(prof2[0].cleanup_optimizers) ) new_opt = EquilibriumOptimizer( local_optimizers.union(global_optimizers), max_use_ratio=1, final_optimizers=final_optimizers, cleanup_optimizers=cleanup_optimizers, ) def add_append_list(l1, l2): l = copy.copy(l1) for idx, nb in enumerate(l2): if idx < len(l): l[idx] += nb else: l.append(nb) return l loop_timing = add_append_list(prof1[1], prof2[1]) loop_process_count = list(prof1[2]) global_sub_profs = [] final_sub_profs = [] cleanup_sub_profs = [] for i in range(min(len(loop_process_count), len(prof2[2]))): process_count = loop_process_count[i] for process, count in prof2[2][i].items(): if process in process_count: process_count[process] += count else: process_count[process] = count def merge(opts, attr, idx): tmp = [] for opt in opts: o1 = getattr(prof1[0], attr) o2 = getattr(prof2[0], attr) if opt in o1 and opt in o2: p1 = prof1[idx][i][o1.index(opt)] p2 = prof2[idx][i][o2.index(opt)] m = None if hasattr(opt, "merge_profile"): m = opt.merge_profile(p1, p2) elif opt in o1: m = prof1[idx][i][o1.index(opt)] else: m = prof2[idx][i][o2.index(opt)] tmp.append(m) return tmp global_sub_profs.append(merge(global_optimizers, "global_optimizers", 9)) final_sub_profs.append(merge(final_optimizers, "final_optimizers", 10)) cleanup_sub_profs.append( merge(cleanup_optimizers, "cleanup_optimizers", 11) ) # Add the iteration done by only one of the profile. loop_process_count.extend(prof1[2][len(loop_process_count) :]) global_sub_profs.extend(prof1[9][len(global_sub_profs) :]) final_sub_profs.extend(prof1[10][len(final_sub_profs) :]) cleanup_sub_profs.extend(prof1[11][len(cleanup_sub_profs) :]) global_sub_profs.extend(prof2[9][len(loop_process_count) :]) final_sub_profs.extend(prof2[10][len(loop_process_count) :]) cleanup_sub_profs.extend(prof2[11][len(loop_process_count) :]) max_nb_nodes = max(prof1[3], prof2[3]) global_opt_timing = add_append_list(prof1[4], prof2[4]) nb_nodes = add_append_list(prof1[5], prof2[5]) time_opts = merge_dict(prof1[6], prof2[6]) io_toposort_timing = add_append_list(prof1[7], prof2[7]) assert ( len(loop_timing) == len(global_opt_timing) == len(global_sub_profs) == len(io_toposort_timing) == len(nb_nodes) ) assert len(loop_timing) == max(len(prof1[1]), len(prof2[1])) node_created = merge_dict(prof1[8], prof2[8]) return ( new_opt, loop_timing, loop_process_count, max_nb_nodes, global_opt_timing, nb_nodes, time_opts, io_toposort_timing, node_created, global_sub_profs, final_sub_profs, cleanup_sub_profs, ) def _check_chain(r, chain): """ WRITEME """ chain = list(reversed(chain)) while chain: elem = chain.pop() if elem is None: if r.owner is not None: return False elif r.owner is None: return False elif isinstance(elem, Op): if not r.owner.op == elem: return False else: try: if issubclass(elem, Op) and not isinstance(r.owner.op, elem): return False except TypeError: return False if chain: r = r.owner.inputs[chain.pop()] # print 'check_chain', _check_chain.n_calls # _check_chain.n_calls += 1 # The return value will be used as a Boolean, but some Variables cannot # be used as Booleans (the results of comparisons, for instance) return r is not None def check_chain(r, *chain): """ WRITEME """ if isinstance(r, Apply): r = r.outputs[0] return _check_chain(r, reduce(list.__iadd__, ([x, 0] for x in chain))) def pre_greedy_local_optimizer(fgraph, optimizations, out): """Apply local optimizations to a graph. This function traverses the computation graph in the graph before the variable `out` but that are not in the `fgraph`. It applies `optimizations` to each variable on the traversed graph. .. warning:: This changes the nodes in a graph in-place. Its main use is to apply locally constant folding when generating the graph of the indices of a subtensor. Changes should not be applied to nodes that are in an `fgraph`, so we use `fgraph` to prevent that. Notes ----- This doesn't do an equilibrium optimization, so, if there is an optimization--like `local_upcast_elemwise_constant_inputs`--in the list that adds additional nodes to the inputs of the node, it might be necessary to call this function multiple times. Parameters ---------- fgraph : FunctionGraph The graph used to avoid/filter nodes. optimizations : list of LocalOptimizer The list of local optimizations to apply out : Variable A `Variable` specifying the graph to optimize. """ def local_recursive_function(list_opt, out, optimized_vars, depth): if not getattr(out, "owner", None): return [out], optimized_vars node = out.owner if node in fgraph.apply_nodes: return node.outputs, optimized_vars # Walk up the graph via the node's inputs for idx, inp in enumerate(node.inputs): if inp in optimized_vars: nw_in = optimized_vars[inp] else: if inp.owner: outs, optimized_vars = local_recursive_function( list_opt, inp, optimized_vars, depth + 1 ) for k, v in zip(inp.owner.outputs, outs): optimized_vars[k] = v nw_in = outs[inp.owner.outputs.index(inp)] else: nw_in = inp optimized_vars[inp] = inp # XXX: An in-place change node.inputs[idx] = nw_in # Apply the optimizations results = node.outputs for opt in list_opt: ret = opt.transform(fgraph, node) if ret is not False and ret is not None: assert len(ret) == len(node.outputs), opt for k, v in zip(node.outputs, ret): optimized_vars[k] = v results = ret if ret[0].owner: node = out.owner else: break return results, optimized_vars if out.owner: out_index = out.owner.outputs.index(out) else: out_index = 0 final_outs, optimized_nodes = local_recursive_function(optimizations, out, {}, 0) return final_outs[out_index] def copy_stack_trace(from_var, to_var): r"""Copy the stack traces from `from_var` to `to_var`. Parameters ---------- from_var : `Variable` or list `Variable`\s to copy stack traces from. to_var : `Variable` or list `Variable`\s to copy stack traces to. Notes ----- The stacktrace is assumed to be of the form of a list of lists of tuples. Each tuple contains the filename, line number, function name and so on. Each list of tuples contains the truples belonging to a particular `Variable`. """ # Store stack traces from from_var tr = [] if isinstance(from_var, Iterable) and not isinstance(from_var, Variable): # If from_var is a list, store concatenated stack traces for v in from_var: tr += getattr(v.tag, "trace", []) else: # If from_var is not a list, it must be a single tensor variable, # so just store that particular stack trace tr = getattr(from_var.tag, "trace", []) if tr and isinstance(tr[0], tuple): # There was one single stack trace, we encapsulate it in a list tr = [tr] # Copy over stack traces to to_var if isinstance(to_var, Iterable) and not isinstance(to_var, Variable): # Copy over stack traces from from_var to each variable in # to_var, including the stack_trace of the to_var before for v in to_var: v.tag.trace = getattr(v.tag, "trace", []) + tr else: # Copy over stack traces from from_var to each variable to # to_var, including the stack_trace of the to_var before to_var.tag.trace = getattr(to_var.tag, "trace", []) + tr return to_var @contextlib.contextmanager def inherit_stack_trace(from_var): """ A context manager that copies the stack trace from one or more variable nodes to all variable nodes constructed in the body. ``new_nodes`` is the list of all the newly created variable nodes inside an optimization that is managed by ``graph.nodes_constructed``. Parameters ---------- from_var : `Variable` node or a list of `Variable` nodes to copy stack traces from. """ with nodes_constructed() as new_nodes: yield copy_stack_trace(from_var, new_nodes) def check_stack_trace(f_or_fgraph, ops_to_check="last", bug_print="raise"): r"""Checks if the outputs of specific `Op`\s have a stack trace. Parameters ---------- f_or_fgraph : Function or FunctionGraph The compiled function or the function graph to be analysed. ops_to_check This value can be of four different types: - classes or instances inheriting from `Op` - tuple/list of classes or instances inheriting from `Op` - string - function returning a boolean and taking as input an instance of `Op` - if `ops_to_check` is a string, it should be either ``'last'`` or ``'all'``. ``'last'`` will check only the last `Op` of the graph while ``'all'`` will check all the `Op`\s of the graph. - if `ops_to_check` is an `Op` or a tuple/list of `Op`\s, the function will check that all the outputs of their occurrences in the graph have a stack trace. - if `ops_to_check` is a function, it should take as input a `Op` and return a boolean indicating if the input `Op` should be checked or not. bug_print This value is a string belonging to ``{'raise', 'warn', 'ignore'}``. You can specify the behaviour of the function when the specified `ops_to_check` are not in the graph of `f_or_fgraph`: it can either raise an exception, write a warning or simply ignore it. Returns ------- boolean ``True`` if the outputs of the specified ops have a stack, ``False`` otherwise. """ if isinstance(f_or_fgraph, aesara.compile.function.types.Function): fgraph = f_or_fgraph.maker.fgraph elif isinstance(f_or_fgraph, aesara.graph.fg.FunctionGraph): fgraph = f_or_fgraph else: raise ValueError("The type of f_or_fgraph is not supported") if isinstance(ops_to_check, Op) or ( inspect.isclass(ops_to_check) and issubclass(ops_to_check, Op) ): ops_to_check = (ops_to_check,) # if ops_to_check is a string if isinstance(ops_to_check, str): if ops_to_check == "last": apply_nodes_to_check = [ fgraph.outputs[i].owner for i in range(len(fgraph.outputs)) ] elif ops_to_check == "all": apply_nodes_to_check = fgraph.apply_nodes else: raise ValueError("The string ops_to_check is not recognised") # if ops_to_check is a list/tuple of ops elif isinstance(ops_to_check, (tuple, list)): # Separate classes from instances in ops_to_check op_instances = [] op_classes = [] for obj in ops_to_check: if isinstance(obj, Op): op_instances.append(obj) else: op_classes.append(obj) op_classes = tuple(op_classes) apply_nodes_to_check = [ node for node in fgraph.apply_nodes if node.op in ops_to_check ] + [ node for node in fgraph.apply_nodes if isinstance(node.op, op_classes) or ( hasattr(node.op, "scalar_op") and isinstance(node.op.scalar_op, op_classes) ) ] # if ops_to_check is a function elif callable(ops_to_check): apply_nodes_to_check = [ node for node in fgraph.apply_nodes if ops_to_check(node) ] else: raise ValueError("ops_to_check does not have the right type") if not apply_nodes_to_check: msg = ( "Provided op instances/classes are not in the graph or the " "graph is empty" ) if bug_print == "warn": warnings.warn(msg) elif bug_print == "raise": raise Exception(msg) elif bug_print == "ignore": pass else: raise ValueError("The string bug_print is not recognised") for node in apply_nodes_to_check: for output in node.outputs: if not hasattr(output.tag, "trace") or not output.tag.trace: return False return True class CheckStackTraceFeature(Feature): def on_import(self, fgraph, node, reason): # In optdb we only register the CheckStackTraceOptimization when # config.check_stack_trace is not off but we also double check here. if config.check_stack_trace != "off" and not check_stack_trace(fgraph, "all"): if config.check_stack_trace == "raise": raise AssertionError( "Empty stack trace! The optimization that inserted this variable is " + str(reason) ) elif config.check_stack_trace in ["log", "warn"]: apply_nodes_to_check = fgraph.apply_nodes for node in apply_nodes_to_check: for output in node.outputs: if not hasattr(output.tag, "trace") or not output.tag.trace: output.tag.trace = [ [ ( "", 0, "Empty stack trace! The optimization that" + "inserted this variable is " + str(reason), "", ) ] ] if config.check_stack_trace == "warn": warnings.warn( "Empty stack trace! The optimization that inserted this variable is" + str(reason) ) class CheckStackTraceOptimization(GlobalOptimizer): """Optimizer that serves to add `CheckStackTraceOptimization` as a feature.""" def add_requirements(self, fgraph): if not hasattr(fgraph, "CheckStackTraceFeature"): fgraph.attach_feature(CheckStackTraceFeature()) def apply(self, fgraph): pass
#!/usr/bin/env python3 import boto3 import json import os import os import pprint from sys import version_info import sys AWS_REGION = "us-west-1" EC2_CLIENT = boto3.client('ec2', region_name=AWS_REGION) INSTANCE_ID = 'i-06a2ac220369ddb08' # Stopping the instance using stop_instances. instances = EC2_CLIENT.stop_instances( InstanceIds=[ INSTANCE_ID, ], ) for instance in instances['StoppingInstances']: print(f'Stopping instance "{instance['InstanceId']}"') print(f'Status of instance "{instance['CurrentState']['Name']}"') print(json.dumps(instances, indent=4, sort_keys=True)) def terminating_instances(): # Terminating the instance using terminate_instances. instances = EC2_CLIENT.terminate_instances( InstanceIds=[ INSTANCE_ID, ], ) for instance in instances['TerminatingInstances']: print(f'Terminating instance "{instance['InstanceId']}"') print(f'Status of instance "{instance['CurrentState']['Name']}"') print(json.dumps(instances, indent=4, sort_keys=True)) yes = {'yes','y', 'ye', ''} no = {'no','n'} print("Do you want to delete instance? (y/n)") choice = input().lower() if choice in yes: print('Now it is beeing deleted') terminating_instances() elif choice in no: print('Successfully stopped') else: sys.stdout.write("Please respond with 'yes' or 'no'")
#!/usr/bin/env python3 import boto3 import json import os import os import pprint from sys import version_info import sys AWS_REGION = "us-west-1" EC2_CLIENT = boto3.client('ec2', region_name=AWS_REGION) INSTANCE_ID = 'i-06a2ac220369ddb08' # Stopping the instance using stop_instances. instances = EC2_CLIENT.stop_instances( InstanceIds=[ INSTANCE_ID, ], ) for instance in instances['StoppingInstances']: print(f'Stopping instance "{instance["InstanceId"]}"') print(f'Status of instance "{instance["CurrentState"]["Name"]}"') print(json.dumps(instances, indent=4, sort_keys=True)) def terminating_instances(): # Terminating the instance using terminate_instances. instances = EC2_CLIENT.terminate_instances( InstanceIds=[ INSTANCE_ID, ], ) for instance in instances['TerminatingInstances']: print(f'Terminating instance "{instance["InstanceId"]}"') print(f'Status of instance "{instance["CurrentState"]["Name"]}"') print(json.dumps(instances, indent=4, sort_keys=True)) yes = {'yes','y', 'ye', ''} no = {'no','n'} print("Do you want to delete instance? (y/n)") choice = input().lower() if choice in yes: print('Now it is beeing deleted') terminating_instances() elif choice in no: print('Successfully stopped') else: sys.stdout.write("Please respond with 'yes' or 'no'")
import pandas as pd import psycopg2 as pg2 import yaml import io import ohio.ext.pandas from sqlalchemy import create_engine def open_db_connection(secrets_file="secrets.yaml", verbose=True): """ Opens connection to psql db :return: connection object """ try: with open(secrets_file, 'r') as f: # loads contents of secrets.yaml into a python dictionary secret_config = yaml.safe_load(f.read()) db_params = secret_config['db'] except FileNotFoundError: print("Cannot establish connection to database. Please provide db_params in secrets.yaml file.") exit(1) conn = pg2.connect( host=db_params['host'], port=db_params['port'], dbname=db_params['dbname'], user=db_params['user'], password=db_params['password'] ) if verbose: print(f"Connection opened to database {db_params["dbname"]}") return conn connection = open_db_connection() def write_df_in_table(conn, df, schema_name, table_name): """write pandas dataframe in table Args: conn: a pSQL databse connection object df: a pandas dataframe to write to the database schema_name: name of the schema for the table table_name: name of the table """ # write df to memory buffer SEP = "~" buffer = io.StringIO() df.to_csv(buffer, index_label='id', header=False, sep=SEP) buffer.seek(0) type_mapping = {'int64': 'integer', 'float64': 'double precision', 'object': 'varchar'} cur = conn.cursor() cur.execute(f"DROP TABLE IF EXISTS {schema_name}.{table_name};") cur.execute(f"CREATE TABLE {schema_name}.{table_name} (id integer PRIMARY KEY);") # cur.execute(f"GRANT ALL PRIVILEGES ON {schema_name}.{table_name} TO bills1;") cur.execute(f"ALTER TABLE {schema_name}.{table_name} OWNER TO bills1;") # create table column for col_name, col_type in zip(df.columns, df.dtypes): print(col_name) col_type = type_mapping[str(col_type)] cur.execute(f"ALTER table {schema_name}.{table_name} ADD COLUMN {col_name} {col_type};") # hard-coded for now, may be made dynamic later # TODO: need to figure out how to change NULL values to date as well #if col_name == "introduced_date": # cur.execute(f"""ALTER table {schema_name}.{table_name} ALTER COLUMN {col_name} # TYPE date using to_date({col_name}, 'YYYY-MM-DD');""") # copy data from buffer to table cur.copy_from(buffer, f'{schema_name}.{table_name}', sep=SEP) conn.commit() cur.close() # If you need to recreate the SQL tables for whatever reason object = pd.read_pickle(r'/data/groups/bills1/mlpolicylab_fall20_bills1/bid_groups.pkl') white_df = pd.DataFrame(object['white'], columns=['bill_id']) write_df_in_table(conn=connection, df=white_df, schema_name="sketch", table_name="reference_bills_w") """ black_df = pd.DataFrame(object['black'], columns=['bill_id']) asian_df = pd.DataFrame(object['asian'], columns=['bill_id']) write_df_in_table(conn=connection, df= black_df, schema_name="sketch", table_name="protected_bills_b") write_df_in_table(conn=connection, df= asian_df, schema_name="sketch", table_name="protected_bills_a") """
import pandas as pd import psycopg2 as pg2 import yaml import io import ohio.ext.pandas from sqlalchemy import create_engine def open_db_connection(secrets_file="secrets.yaml", verbose=True): """ Opens connection to psql db :return: connection object """ try: with open(secrets_file, 'r') as f: # loads contents of secrets.yaml into a python dictionary secret_config = yaml.safe_load(f.read()) db_params = secret_config['db'] except FileNotFoundError: print("Cannot establish connection to database. Please provide db_params in secrets.yaml file.") exit(1) conn = pg2.connect( host=db_params['host'], port=db_params['port'], dbname=db_params['dbname'], user=db_params['user'], password=db_params['password'] ) if verbose: print(f"Connection opened to database {db_params['dbname']}") return conn connection = open_db_connection() def write_df_in_table(conn, df, schema_name, table_name): """write pandas dataframe in table Args: conn: a pSQL databse connection object df: a pandas dataframe to write to the database schema_name: name of the schema for the table table_name: name of the table """ # write df to memory buffer SEP = "~" buffer = io.StringIO() df.to_csv(buffer, index_label='id', header=False, sep=SEP) buffer.seek(0) type_mapping = {'int64': 'integer', 'float64': 'double precision', 'object': 'varchar'} cur = conn.cursor() cur.execute(f"DROP TABLE IF EXISTS {schema_name}.{table_name};") cur.execute(f"CREATE TABLE {schema_name}.{table_name} (id integer PRIMARY KEY);") # cur.execute(f"GRANT ALL PRIVILEGES ON {schema_name}.{table_name} TO bills1;") cur.execute(f"ALTER TABLE {schema_name}.{table_name} OWNER TO bills1;") # create table column for col_name, col_type in zip(df.columns, df.dtypes): print(col_name) col_type = type_mapping[str(col_type)] cur.execute(f"ALTER table {schema_name}.{table_name} ADD COLUMN {col_name} {col_type};") # hard-coded for now, may be made dynamic later # TODO: need to figure out how to change NULL values to date as well #if col_name == "introduced_date": # cur.execute(f"""ALTER table {schema_name}.{table_name} ALTER COLUMN {col_name} # TYPE date using to_date({col_name}, 'YYYY-MM-DD');""") # copy data from buffer to table cur.copy_from(buffer, f'{schema_name}.{table_name}', sep=SEP) conn.commit() cur.close() # If you need to recreate the SQL tables for whatever reason object = pd.read_pickle(r'/data/groups/bills1/mlpolicylab_fall20_bills1/bid_groups.pkl') white_df = pd.DataFrame(object['white'], columns=['bill_id']) write_df_in_table(conn=connection, df=white_df, schema_name="sketch", table_name="reference_bills_w") """ black_df = pd.DataFrame(object['black'], columns=['bill_id']) asian_df = pd.DataFrame(object['asian'], columns=['bill_id']) write_df_in_table(conn=connection, df= black_df, schema_name="sketch", table_name="protected_bills_b") write_df_in_table(conn=connection, df= asian_df, schema_name="sketch", table_name="protected_bills_a") """
import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.dates as dt import matplotlib.ticker as ticker import datetime import pickle import copy import snake_case YAXPARAMS = { 'cases': { 'total': { 'ymax': 90, 'yinterval':10 }, 'adj': { 'ymax': 100, 'yinterval': 10 } }, 'deaths': { 'total': { 'ymax': 5, 'yinterval': 1 }, 'adj': { 'ymax': 5, 'yinterval': 1 } }, } YINTERVAL_TOTAL = 5 YINTERVAL_ADJ = 10 SOURCE_LABELS = { 'nyt': 'New York Times', 'jhu': 'Johns Hopkins University' } STATE_COLORS = { 'Vermont': '#1f77b4', 'New Hampshire': '#871f78', } df_start = pickle.load( open('output/pickles/df_us_nyt.p', 'rb')).reset_index() # If you pass in a population, the output will be per 1,000 people # If you pass in an output filename, the plots will be written to ./images and not rendered to the screen def county_plot(county, state, metrics=['cases', 'deaths'], source='nyt', total_population=None): df = copy.deepcopy(df_start) start_date = pd.to_datetime('2020-03-01') location = { 'type': 'county', 'value': [county, state] } for metric in metrics: for population in [False, total_population]: count_of = f'{metric}' county = location['value'][0] state = location['value'][1] color = STATE_COLORS[state] df = df[df.county == county] df = df[df.state == state] df = df[df.date >= start_date] if population: df[count_of] = df[count_of].apply(lambda x: (x / population) * 100000) df['count_of_diff'] = df[count_of].diff() df['count_of_diff_7_day_mean'] = df.count_of_diff.rolling(7).mean() df = df.iloc[1:] fig = plt.figure(figsize=(7, 3)) ax = fig.add_subplot(111) ax.bar('date', 'count_of_diff', data=df, color=color, alpha=0.35) ax.plot('date', 'count_of_diff_7_day_mean', color=color, data=df) ax.xaxis.set_major_locator(dt.MonthLocator()) ax.xaxis.set_major_formatter(dt.DateFormatter('%b')) ax.set_ylim(ymin=0) yaxparams = YAXPARAMS[metric]['adj' if population else 'total'] ymax = yaxparams['ymax'] yinterval = yaxparams['yinterval'] # ax.set_ylim(ymax=yaxparams['ymax']) ax.yaxis.set_ticks(np.arange(0, ymax + yinterval, yinterval)) ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.0f')) ax.tick_params(axis='y', colors=color) ax.tick_params(axis='x', colors=color) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) ax.grid(axis='x') plt.style.use('seaborn-whitegrid') plt.text(df.date.iloc[-1] + datetime.timedelta(days=3), df.count_of_diff_7_day_mean.iloc[-1], "7-day\navg.", color=color, style='italic') filename = snake_case.convert(f'{county} {state} {metric}{' adjusted' if population else ''}.svg') plt.savefig(f'output/charts/{filename}') county_dicts = [ {'county': 'Orange', 'state': 'Vermont', 'total_population': 28892}, {'county': 'Orange', 'state': 'Vermont', 'total_population': 28892}, {'county': 'Windsor', 'state': 'Vermont', 'total_population': 55062}, {'county': 'Grafton', 'state': 'New Hampshire', 'total_population': 89886}, {'county': 'Sullivan', 'state': 'New Hampshire', 'total_population': 43146}, ] for county_dict in county_dicts: county_plot(**county_dict)
import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.dates as dt import matplotlib.ticker as ticker import datetime import pickle import copy import snake_case YAXPARAMS = { 'cases': { 'total': { 'ymax': 90, 'yinterval':10 }, 'adj': { 'ymax': 100, 'yinterval': 10 } }, 'deaths': { 'total': { 'ymax': 5, 'yinterval': 1 }, 'adj': { 'ymax': 5, 'yinterval': 1 } }, } YINTERVAL_TOTAL = 5 YINTERVAL_ADJ = 10 SOURCE_LABELS = { 'nyt': 'New York Times', 'jhu': 'Johns Hopkins University' } STATE_COLORS = { 'Vermont': '#1f77b4', 'New Hampshire': '#871f78', } df_start = pickle.load( open('output/pickles/df_us_nyt.p', 'rb')).reset_index() # If you pass in a population, the output will be per 1,000 people # If you pass in an output filename, the plots will be written to ./images and not rendered to the screen def county_plot(county, state, metrics=['cases', 'deaths'], source='nyt', total_population=None): df = copy.deepcopy(df_start) start_date = pd.to_datetime('2020-03-01') location = { 'type': 'county', 'value': [county, state] } for metric in metrics: for population in [False, total_population]: count_of = f'{metric}' county = location['value'][0] state = location['value'][1] color = STATE_COLORS[state] df = df[df.county == county] df = df[df.state == state] df = df[df.date >= start_date] if population: df[count_of] = df[count_of].apply(lambda x: (x / population) * 100000) df['count_of_diff'] = df[count_of].diff() df['count_of_diff_7_day_mean'] = df.count_of_diff.rolling(7).mean() df = df.iloc[1:] fig = plt.figure(figsize=(7, 3)) ax = fig.add_subplot(111) ax.bar('date', 'count_of_diff', data=df, color=color, alpha=0.35) ax.plot('date', 'count_of_diff_7_day_mean', color=color, data=df) ax.xaxis.set_major_locator(dt.MonthLocator()) ax.xaxis.set_major_formatter(dt.DateFormatter('%b')) ax.set_ylim(ymin=0) yaxparams = YAXPARAMS[metric]['adj' if population else 'total'] ymax = yaxparams['ymax'] yinterval = yaxparams['yinterval'] # ax.set_ylim(ymax=yaxparams['ymax']) ax.yaxis.set_ticks(np.arange(0, ymax + yinterval, yinterval)) ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.0f')) ax.tick_params(axis='y', colors=color) ax.tick_params(axis='x', colors=color) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) ax.grid(axis='x') plt.style.use('seaborn-whitegrid') plt.text(df.date.iloc[-1] + datetime.timedelta(days=3), df.count_of_diff_7_day_mean.iloc[-1], "7-day\navg.", color=color, style='italic') filename = snake_case.convert(f'{county} {state} {metric}{" adjusted" if population else ""}.svg') plt.savefig(f'output/charts/{filename}') county_dicts = [ {'county': 'Orange', 'state': 'Vermont', 'total_population': 28892}, {'county': 'Orange', 'state': 'Vermont', 'total_population': 28892}, {'county': 'Windsor', 'state': 'Vermont', 'total_population': 55062}, {'county': 'Grafton', 'state': 'New Hampshire', 'total_population': 89886}, {'county': 'Sullivan', 'state': 'New Hampshire', 'total_population': 43146}, ] for county_dict in county_dicts: county_plot(**county_dict)
#!/usr/bin/env python """ 1a. As you have done in previous classes, create a Python file named "my_devices.py". In this file, define the connection information for: 'cisco3', 'arista1', 'arista2', and 'srx2'. This file should contain all the necessary information to create a Netmiko connection. Use getpass() for the password handling. Use a global_delay_factor of 4 for both the arista1 device and the arista2 device. This Python module should be used to store the connection information for all of the exercises in this lesson. 1b. Create a Python script that executes "show version" on each of the network devices defined in my_devices.py. This script should execute serially i.e. one SSH connection after the other. Record the total execution time for the script. Print the "show version" output and the total execution time to standard output. As part of this exercise, you should create a function that both establishes a Netmiko connection and that executes a single show command that you pass in as argument. This function's arguments should be the Netmiko device dictionary and the "show-command" argument. The function should return the result from the show command. """ from netmiko import ConnectHandler from my_devices import devices from datetime import datetime import time def netmiko_show_ver(device, command): with ConnectHandler(**device) as net_connect: output = net_connect.send_command(command) return output show_command = "show version" if __name__=="__main__": start_time = datetime.now() t0 = time.time() for device in devices: result = netmiko_show_ver(device, show_command) print("#" * 80) print(f"OUTPUT ----------> {device["host"]}") print("#" * 80) print(result) end_time = datetime.now() t1 = time.time() print("#" * 80) print("SCRIPT FINISHED EXECUTION") print("#" * 80) print(f"Execution time: {end_time - start_time}") print(f"Execution time: {t1 - t0:.2f}") print("#" * 80)
#!/usr/bin/env python """ 1a. As you have done in previous classes, create a Python file named "my_devices.py". In this file, define the connection information for: 'cisco3', 'arista1', 'arista2', and 'srx2'. This file should contain all the necessary information to create a Netmiko connection. Use getpass() for the password handling. Use a global_delay_factor of 4 for both the arista1 device and the arista2 device. This Python module should be used to store the connection information for all of the exercises in this lesson. 1b. Create a Python script that executes "show version" on each of the network devices defined in my_devices.py. This script should execute serially i.e. one SSH connection after the other. Record the total execution time for the script. Print the "show version" output and the total execution time to standard output. As part of this exercise, you should create a function that both establishes a Netmiko connection and that executes a single show command that you pass in as argument. This function's arguments should be the Netmiko device dictionary and the "show-command" argument. The function should return the result from the show command. """ from netmiko import ConnectHandler from my_devices import devices from datetime import datetime import time def netmiko_show_ver(device, command): with ConnectHandler(**device) as net_connect: output = net_connect.send_command(command) return output show_command = "show version" if __name__=="__main__": start_time = datetime.now() t0 = time.time() for device in devices: result = netmiko_show_ver(device, show_command) print("#" * 80) print(f"OUTPUT ----------> {device['host']}") print("#" * 80) print(result) end_time = datetime.now() t1 = time.time() print("#" * 80) print("SCRIPT FINISHED EXECUTION") print("#" * 80) print(f"Execution time: {end_time - start_time}") print(f"Execution time: {t1 - t0:.2f}") print("#" * 80)
import base64 import fnmatch import glob import json import os import re import shutil import stat import subprocess import urllib.parse import warnings from datetime import datetime, timedelta from distutils.util import strtobool from packaging.version import Version from pathlib import Path from typing import Tuple, Any, Union, List, Dict, Optional from zipfile import ZipFile, ZIP_DEFLATED import git import google.auth import sys import yaml from google.cloud import storage import Tests.Marketplace.marketplace_statistics as mp_statistics from Tests.Marketplace.marketplace_constants import PackFolders, Metadata, GCPConfig, BucketUploadFlow, PACKS_FOLDER, \ PackTags, PackIgnored, Changelog, BASE_PACK_DEPENDENCY_DICT, SIEM_RULES_OBJECTS, PackStatus from Utils.release_notes_generator import aggregate_release_notes_for_marketplace from Tests.scripts.utils import logging_wrapper as logging class Pack(object): """ Class that manipulates and manages the upload of pack's artifact and metadata to cloud storage. Args: pack_name (str): Pack root folder name. pack_path (str): Full path to pack folder. Attributes: PACK_INITIAL_VERSION (str): pack initial version that will be used as default. CHANGELOG_JSON (str): changelog json full name, may be changed in the future. README (str): pack's readme file name. METADATA (str): pack's metadata file name, the one that will be deployed to cloud storage. USER_METADATA (str); user metadata file name, the one that located in content repo. EXCLUDE_DIRECTORIES (list): list of directories to excluded before uploading pack zip to storage. AUTHOR_IMAGE_NAME (str): author image file name. RELEASE_NOTES (str): release notes folder name. """ PACK_INITIAL_VERSION = "1.0.0" CHANGELOG_JSON = "changelog.json" README = "README.md" USER_METADATA = "pack_metadata.json" METADATA = "metadata.json" AUTHOR_IMAGE_NAME = "Author_image.png" EXCLUDE_DIRECTORIES = [PackFolders.TEST_PLAYBOOKS.value] RELEASE_NOTES = "ReleaseNotes" def __init__(self, pack_name, pack_path): self._pack_name = pack_name self._pack_path = pack_path self._zip_path = None # zip_path will be updated as part of zip_pack self._marketplaces = [] # initialized in load_user_metadata function self._status = None self._public_storage_path = "" self._remove_files_list = [] # tracking temporary files, in order to delete in later step self._server_min_version = "99.99.99" # initialized min version self._latest_version = None # pack latest version found in changelog self._support_type = None # initialized in load_user_metadata function self._current_version = None # initialized in load_user_metadata function self._hidden = False # initialized in load_user_metadata function self._description = None # initialized in load_user_metadata function self._display_name = None # initialized in load_user_metadata function self._user_metadata = {} # initialized in load_user_metadata function self._eula_link = None # initialized in load_user_metadata function self._is_feed = False # a flag that specifies if pack is a feed pack self._downloads_count = 0 # number of pack downloads self._bucket_url = None # URL of where the pack was uploaded. self._aggregated = False # weather the pack's rn was aggregated or not. self._aggregation_str = "" # the aggregation string msg when the pack versions are aggregated self._create_date = None # initialized in enhance_pack_attributes function self._update_date = None # initialized in enhance_pack_attributes function self._uploaded_author_image = False # whether the pack author image was uploaded or not self._uploaded_integration_images = [] # the list of all integration images that were uploaded for the pack self._support_details = None # initialized in enhance_pack_attributes function self._author = None # initialized in enhance_pack_attributes function self._certification = None # initialized in enhance_pack_attributes function self._legacy = None # initialized in enhance_pack_attributes function self._author_image = None # initialized in upload_author_image function self._displayed_integration_images = [] # initialized in upload_integration_images function self._price = 0 # initialized in enhance_pack_attributes function self._is_private_pack = False # initialized in enhance_pack_attributes function self._is_premium = False # initialized in enhance_pack_attributes function self._vendor_id = None # initialized in enhance_pack_attributes function self._partner_id = None # initialized in enhance_pack_attributes function self._partner_name = None # initialized in enhance_pack_attributes function self._content_commit_hash = None # initialized in enhance_pack_attributes function self._preview_only = None # initialized in enhance_pack_attributes function self._tags = None # initialized in enhance_pack_attributes function self._categories = None # initialized in enhance_pack_attributes function self._content_items = None # initialized in collect_content_items function self._search_rank = None # initialized in enhance_pack_attributes function self._related_integration_images = None # initialized in enhance_pack_attributes function self._use_cases = None # initialized in enhance_pack_attributes function self._keywords = None # initialized in enhance_pack_attributes function self._pack_statistics_handler = None # initialized in enhance_pack_attributes function self._contains_transformer = False # initialized in collect_content_items function self._contains_filter = False # initialized in collect_content_items function self._is_missing_dependencies = False # initialized in _load_pack_dependencies function self._is_modified = None # initialized in detect_modified function self._is_siem = False # initialized in collect_content_items function # Dependencies attributes - these contain only packs that are a part of this marketplace self._first_level_dependencies = {} # initialized in set_pack_dependencies function self._all_levels_dependencies = [] # initialized in set_pack_dependencies function self._displayed_images_dependent_on_packs = [] # initialized in set_pack_dependencies function self._parsed_dependencies = None # initialized in enhance_pack_attributes function @property def name(self): """ str: pack root folder name. """ return self._pack_name @property def path(self): """ str: pack folder full path. """ return self._pack_path @property def latest_version(self): """ str: pack latest version from sorted keys of changelog.json file. """ if not self._latest_version: self._latest_version = self._get_latest_version() return self._latest_version else: return self._latest_version @latest_version.setter def latest_version(self, latest_version): self._latest_version = latest_version @property def status(self): """ str: current status of the packs. """ return self._status @property def is_feed(self): """ bool: whether the pack is a feed pack """ return self._is_feed @is_feed.setter def is_feed(self, is_feed): """ setter of is_feed """ self._is_feed = is_feed @property def is_siem(self): """ bool: whether the pack is a siem pack """ return self._is_siem @is_siem.setter def is_siem(self, is_siem): """ setter of is_siem """ self._is_siem = is_siem @status.setter # type: ignore[attr-defined,no-redef] def status(self, status_value): """ setter of pack current status. """ self._status = status_value @property def public_storage_path(self): """ str: public gcs path of uploaded pack. """ return self._public_storage_path @public_storage_path.setter def public_storage_path(self, path_value): """ setter of public gcs path of uploaded pack. """ self._public_storage_path = path_value @property def support_type(self): """ str: support type of the pack. """ return self._support_type @support_type.setter def support_type(self, support_value): """ setter of support type of the pack. """ self._support_type = support_value @property def current_version(self): """ str: current version of the pack (different from latest_version). """ return self._current_version @current_version.setter def current_version(self, current_version_value): """ setter of current version of the pack. """ self._current_version = current_version_value @property def hidden(self): """ bool: internal content field for preventing pack from being displayed. """ return self._hidden @hidden.setter def hidden(self, hidden_value): """ setter of hidden property of the pack. """ self._hidden = hidden_value @property def description(self): """ str: Description of the pack (found in pack_metadata.json). """ return self._description @description.setter def description(self, description_value): """ setter of description property of the pack. """ self._description = description_value @property def display_name(self): """ str: Display name of the pack (found in pack_metadata.json). """ return self._display_name @property def user_metadata(self): """ dict: the pack_metadata. """ return self._user_metadata @display_name.setter # type: ignore[attr-defined,no-redef] def display_name(self, display_name_value): """ setter of display name property of the pack. """ self._display_name = display_name_value @property def server_min_version(self): """ str: server min version according to collected items. """ if not self._server_min_version or self._server_min_version == "99.99.99": return Metadata.SERVER_DEFAULT_MIN_VERSION else: return self._server_min_version @property def downloads_count(self): """ str: packs downloads count. """ return self._downloads_count @downloads_count.setter def downloads_count(self, download_count_value): """ setter of downloads count property of the pack. """ self._downloads_count = download_count_value @property def bucket_url(self): """ str: pack bucket_url. """ return self._bucket_url @bucket_url.setter def bucket_url(self, bucket_url): """ str: pack bucket_url. """ self._bucket_url = bucket_url @property def aggregated(self): """ str: pack aggregated release notes or not. """ return self._aggregated @property def aggregation_str(self): """ str: pack aggregated release notes or not. """ return self._aggregation_str @property def create_date(self): """ str: pack create date. """ return self._create_date @create_date.setter def create_date(self, value): self._create_date = value @property def update_date(self): """ str: pack update date. """ return self._update_date @update_date.setter def update_date(self, value): self._update_date = value @property def uploaded_author_image(self): """ bool: whether the pack author image was uploaded or not. """ return self._uploaded_author_image @uploaded_author_image.setter def uploaded_author_image(self, uploaded_author_image): """ bool: whether the pack author image was uploaded or not. """ self._uploaded_author_image = uploaded_author_image @property def uploaded_integration_images(self): """ str: the list of uploaded integration images """ return self._uploaded_integration_images @property def is_missing_dependencies(self): return self._is_missing_dependencies @property def zip_path(self): return self._zip_path @property def is_modified(self): return self._is_modified @property def marketplaces(self): return self._marketplaces @property def all_levels_dependencies(self): return self._all_levels_dependencies def _get_latest_version(self): """ Return latest semantic version of the pack. In case that changelog.json file was not found, default value of 1.0.0 will be returned. Otherwise, keys of semantic pack versions will be collected and sorted in descending and return latest version. For additional information regarding changelog.json format go to issue #19786 Returns: str: Pack latest version. """ changelog_path = os.path.join(self._pack_path, Pack.CHANGELOG_JSON) if not os.path.exists(changelog_path): return self._current_version with open(changelog_path, "r") as changelog_file: changelog = json.load(changelog_file) pack_versions = [Version(v) for v in changelog.keys()] pack_versions.sort(reverse=True) return str(pack_versions[0]) @staticmethod def organize_integration_images(pack_integration_images: list, pack_dependencies_integration_images_dict: dict, pack_dependencies_by_download_count: list): """ By Issue #32038 1. Sort pack integration images by alphabetical order 2. Sort pack dependencies by download count Pack integration images are shown before pack dependencies integration images Args: pack_integration_images (list): list of pack integration images pack_dependencies_integration_images_dict: a mapping of pack dependency name to its integration images pack_dependencies_by_download_count: a list of pack dependencies sorted by download count Returns: list: list of sorted integration images """ def sort_by_name(integration_image: dict): return integration_image.get('name', '') # sort packs integration images pack_integration_images = sorted(pack_integration_images, key=sort_by_name) # sort pack dependencies integration images all_dep_int_imgs = pack_integration_images for dep_pack_name in pack_dependencies_by_download_count: if dep_pack_name in pack_dependencies_integration_images_dict: logging.info(f'Adding {dep_pack_name} to deps int imgs') dep_int_imgs = sorted(pack_dependencies_integration_images_dict[dep_pack_name], key=sort_by_name) for dep_int_img in dep_int_imgs: if dep_int_img not in all_dep_int_imgs: # avoid duplicates all_dep_int_imgs.append(dep_int_img) return all_dep_int_imgs @staticmethod def _get_all_pack_images(pack_integration_images: List, display_dependencies_images: List, dependencies_metadata: Dict, pack_dependencies_by_download_count): """ Returns data of uploaded pack integration images and it's path in gcs. Pack dependencies integration images are added to that result as well. Args: pack_integration_images (list): list of uploaded to gcs integration images and it paths in gcs. display_dependencies_images (list): list of pack names of additional dependencies images to display. dependencies_metadata (dict): all level dependencies data. pack_dependencies_by_download_count (list): list of pack names that are dependencies of the given pack sorted by download count. Returns: list: collection of integration display name and it's path in gcs. """ dependencies_integration_images_dict: dict = {} additional_dependencies_data = {k: v for k, v in dependencies_metadata.items() if k in display_dependencies_images} for dependency_data in additional_dependencies_data.values(): for dep_int_img in dependency_data.get('integrations', []): dep_int_img_gcs_path = dep_int_img.get('imagePath', '') # image public url dep_int_img['name'] = Pack.remove_contrib_suffix_from_name(dep_int_img.get('name', '')) dep_pack_name = os.path.basename(os.path.dirname(dep_int_img_gcs_path)) if dep_pack_name not in display_dependencies_images: continue # skip if integration image is not part of displayed images of the given pack if dep_int_img not in pack_integration_images: # avoid duplicates in list if dep_pack_name in dependencies_integration_images_dict: dependencies_integration_images_dict[dep_pack_name].append(dep_int_img) else: dependencies_integration_images_dict[dep_pack_name] = [dep_int_img] return Pack.organize_integration_images( pack_integration_images, dependencies_integration_images_dict, pack_dependencies_by_download_count ) def add_pack_type_tags(self, yaml_content, yaml_type): """ Checks if an pack objects is siem or feed object. If so, updates Pack._is_feed or Pack._is_siem Args: yaml_content: The yaml content extracted by yaml.safe_load(). yaml_type: The type of object to check. Returns: Doesn't return """ if yaml_type == 'Integration': if yaml_content.get('script', {}).get('feed', False) is True: self._is_feed = True if yaml_content.get('isfetchevents', False) is True: self._is_siem = True if yaml_type == 'Playbook': if yaml_content.get('name').startswith('TIM '): self._is_feed = True if yaml_type in SIEM_RULES_OBJECTS: self._is_siem = True @staticmethod def _clean_release_notes(release_notes_lines): return re.sub(r'<\!--.*?-->', '', release_notes_lines, flags=re.DOTALL) @staticmethod def _parse_pack_dependencies(first_level_dependencies, dependencies_metadata_dict): """ Parses user defined dependencies and returns dictionary with relevant data about each dependency pack. Args: first_level_dependencies (dict): first lever dependencies that were retrieved from user pack_metadata.json file. dependencies_metadata_dict (dict): dict of pack dependencies data. Returns: dict: parsed dictionary with pack dependency data. """ parsed_result = {} for dependency_id, dependency_data in dependencies_metadata_dict.items(): parsed_result[dependency_id] = { "mandatory": first_level_dependencies.get(dependency_id, {}).get('mandatory', True), "minVersion": dependency_data.get(Metadata.CURRENT_VERSION, Pack.PACK_INITIAL_VERSION), "author": dependency_data.get('author', ''), "name": dependency_data.get('name') if dependency_data.get('name') else dependency_id, "certification": dependency_data.get('certification', 'certified') } return parsed_result @staticmethod def _create_support_section(support_type, support_url=None, support_email=None): """ Creates support dictionary that is part of metadata. In case of support type xsoar, adds default support url. If support is xsoar and support url is defined and doesn't match xsoar default url, warning is raised. Args: support_type (str): support type of pack. support_url (str): support full url. support_email (str): support email address. Returns: dict: supported data dictionary. """ support_details = {} if support_url: # set support url from user input support_details['url'] = support_url elif support_type == Metadata.XSOAR_SUPPORT: # in case support type is xsoar, set default xsoar support url support_details['url'] = Metadata.XSOAR_SUPPORT_URL # add support email if defined if support_email: support_details['email'] = support_email return support_details @staticmethod def _get_author(support_type, author=None): """ Returns pack author. In case support type is xsoar, more additional validation are applied. Args: support_type (str): support type of pack. author (str): author of the pack. Returns: str: returns author from the input. """ if support_type == Metadata.XSOAR_SUPPORT and not author: return Metadata.XSOAR_AUTHOR # returned xsoar default author elif support_type == Metadata.XSOAR_SUPPORT and author != Metadata.XSOAR_AUTHOR: logging.warning(f"{author} author doest not match {Metadata.XSOAR_AUTHOR} default value") return author else: return author @staticmethod def _get_certification(support_type, certification=None): """ Returns pack certification. In case support type is xsoar or partner, CERTIFIED is returned. In case support is not xsoar or partner but pack_metadata has certification field, certification value will be taken from pack_metadata defined value. Otherwise empty certification value (empty string) will be returned Args: support_type (str): support type of pack. certification (str): certification value from pack_metadata, if exists. Returns: str: certification value """ if support_type in [Metadata.XSOAR_SUPPORT, Metadata.PARTNER_SUPPORT]: return Metadata.CERTIFIED elif certification: return certification else: return "" def _get_tags_from_landing_page(self, landing_page_sections: dict) -> set: """ Build the pack's tag list according to the user metadata and the landingPage sections file. Args: landing_page_sections (dict): landingPage sections and the packs in each one of them. Returns: set: Pack's tags. """ tags = set() sections = landing_page_sections.get('sections', []) if landing_page_sections else [] for section in sections: if self._pack_name in landing_page_sections.get(section, []): tags.add(section) return tags def _parse_pack_metadata(self, build_number, commit_hash): """ Parses pack metadata according to issue #19786 and #20091. Part of field may change over the time. Args: build_number (str): circleCI build number. commit_hash (str): current commit hash. Returns: dict: parsed pack metadata. """ pack_metadata = { Metadata.NAME: self._display_name or self._pack_name, Metadata.ID: self._pack_name, Metadata.DESCRIPTION: self._description or self._pack_name, Metadata.CREATED: self._create_date, Metadata.UPDATED: self._update_date, Metadata.LEGACY: self._legacy, Metadata.SUPPORT: self._support_type, Metadata.SUPPORT_DETAILS: self._support_details, Metadata.EULA_LINK: self._eula_link, Metadata.AUTHOR: self._author, Metadata.AUTHOR_IMAGE: self._author_image, Metadata.CERTIFICATION: self._certification, Metadata.PRICE: self._price, Metadata.SERVER_MIN_VERSION: self.user_metadata.get(Metadata.SERVER_MIN_VERSION) or self.server_min_version, Metadata.CURRENT_VERSION: self.user_metadata.get(Metadata.CURRENT_VERSION, ''), Metadata.VERSION_INFO: build_number, Metadata.COMMIT: commit_hash, Metadata.DOWNLOADS: self._downloads_count, Metadata.TAGS: list(self._tags or []), Metadata.CATEGORIES: self._categories, Metadata.CONTENT_ITEMS: self._content_items, Metadata.SEARCH_RANK: self._search_rank, Metadata.INTEGRATIONS: self._related_integration_images, Metadata.USE_CASES: self._use_cases, Metadata.KEY_WORDS: self._keywords, Metadata.DEPENDENCIES: self._parsed_dependencies, Metadata.VIDEOS: self.user_metadata.get(Metadata.VIDEOS) or [], } if self._is_private_pack: pack_metadata.update({ Metadata.PREMIUM: self._is_premium, Metadata.VENDOR_ID: self._vendor_id, Metadata.PARTNER_ID: self._partner_id, Metadata.PARTNER_NAME: self._partner_name, Metadata.CONTENT_COMMIT_HASH: self._content_commit_hash, Metadata.PREVIEW_ONLY: self._preview_only }) return pack_metadata def _load_pack_dependencies_metadata(self, index_folder_path, packs_dict): """ Loads dependencies metadata and returns mapping of pack id and it's loaded data. There are 2 cases: Case 1: The dependency is present in the index.zip. In this case, we add it to the dependencies results. Case 2: The dependency is missing from the index.zip since it is a new pack. In this case, handle missing dependency - This means we mark this pack as 'missing dependency', and once the new index.zip is created, and therefore it contains the new pack, we call this function again, and hitting case 1. Args: index_folder_path (str): full path to download index folder. packs_dict (dict): dict of all packs relevant for current marketplace, as {pack_id: pack_object}. Returns: dict: pack id as key and loaded metadata of packs as value. bool: True if the pack is missing dependencies, False otherwise. """ dependencies_metadata_result = {} dependencies_ids = {dep for dep in self._first_level_dependencies} dependencies_ids.update(self._displayed_images_dependent_on_packs) for dependency_pack_id in dependencies_ids: dependency_metadata_path = os.path.join(index_folder_path, dependency_pack_id, Pack.METADATA) if os.path.exists(dependency_metadata_path): # Case 1: the dependency is found in the index.zip with open(dependency_metadata_path, 'r') as metadata_file: dependency_metadata = json.load(metadata_file) dependencies_metadata_result[dependency_pack_id] = dependency_metadata else: # Case 2: the dependency is not in the index since it is a new pack self._is_missing_dependencies = True logging.warning(f"{self._pack_name} pack dependency with id {dependency_pack_id} " f"was not found in index, marking it as missing dependencies - to be resolved in " f"next iteration over packs") return dependencies_metadata_result, self._is_missing_dependencies @staticmethod def _get_updated_changelog_entry(changelog: dict, version: str, release_notes: str = None, version_display_name: str = None, build_number_with_prefix: str = None, released_time: str = None): """ Args: changelog (dict): The changelog from the production bucket. version (str): The version that is the key in the changelog of the entry wished to be updated. release_notes (str): The release notes lines to update the entry with. version_display_name (str): The version display name to update the entry with. build_number_with_prefix(srt): the build number to modify the entry to, including the prefix R (if present). released_time: The released time to update the entry with. """ changelog_entry = changelog.get(version) if not changelog_entry: raise Exception('The given version is not a key in the changelog') version_display_name = \ version_display_name if version_display_name else changelog_entry[Changelog.DISPLAY_NAME].split('-')[0] build_number_with_prefix = \ build_number_with_prefix if build_number_with_prefix else \ changelog_entry[Changelog.DISPLAY_NAME].split('-')[1] changelog_entry[Changelog.RELEASE_NOTES] = release_notes if release_notes else changelog_entry[ Changelog.RELEASE_NOTES] changelog_entry[Changelog.DISPLAY_NAME] = f'{version_display_name} - {build_number_with_prefix}' changelog_entry[Changelog.RELEASED] = released_time if released_time else changelog_entry[Changelog.RELEASED] return changelog_entry def _create_changelog_entry(self, release_notes, version_display_name, build_number, new_version=True, initial_release=False): """ Creates dictionary entry for changelog. Args: release_notes (str): release notes md. version_display_name (str): display name version. build_number (srt): current build number. new_version (bool): whether the entry is new or not. If not new, R letter will be appended to build number. initial_release (bool): whether the entry is an initial release or not. Returns: dict: release notes entry of changelog """ if new_version: return {Changelog.RELEASE_NOTES: release_notes, Changelog.DISPLAY_NAME: f'{version_display_name} - {build_number}', Changelog.RELEASED: datetime.utcnow().strftime(Metadata.DATE_FORMAT)} elif initial_release: return {Changelog.RELEASE_NOTES: release_notes, Changelog.DISPLAY_NAME: f'{version_display_name} - {build_number}', Changelog.RELEASED: self._create_date} elif self.is_modified: return {Changelog.RELEASE_NOTES: release_notes, Changelog.DISPLAY_NAME: f'{version_display_name} - R{build_number}', Changelog.RELEASED: datetime.utcnow().strftime(Metadata.DATE_FORMAT)} return {} def remove_unwanted_files(self, delete_test_playbooks=True): """ Iterates over pack folder and removes hidden files and unwanted folders. Args: delete_test_playbooks (bool): whether to delete test playbooks folder. Returns: bool: whether the operation succeeded. """ task_status = True try: for directory in Pack.EXCLUDE_DIRECTORIES: if delete_test_playbooks and os.path.isdir(f'{self._pack_path}/{directory}'): shutil.rmtree(f'{self._pack_path}/{directory}') logging.info(f"Deleted {directory} directory from {self._pack_name} pack") for root, dirs, files in os.walk(self._pack_path, topdown=True): for pack_file in files: full_file_path = os.path.join(root, pack_file) # removing unwanted files if pack_file.startswith('.') \ or pack_file in [Pack.AUTHOR_IMAGE_NAME, Pack.USER_METADATA] \ or pack_file in self._remove_files_list: os.remove(full_file_path) logging.info(f"Deleted pack {pack_file} file for {self._pack_name} pack") continue except Exception: task_status = False logging.exception(f"Failed to delete ignored files for pack {self._pack_name}") finally: return task_status def sign_pack(self, signature_string=None): """ Signs pack folder and creates signature file. Args: signature_string (str): Base64 encoded string used to sign the pack. Returns: bool: whether the operation succeeded. """ task_status = False try: if signature_string: with open("keyfile", "wb") as keyfile: keyfile.write(signature_string.encode()) arg = f'./signDirectory {self._pack_path} keyfile base64' signing_process = subprocess.Popen(arg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) output, err = signing_process.communicate() if err: logging.error(f"Failed to sign pack for {self._pack_name} - {str(err)}") return logging.info(f"Signed {self._pack_name} pack successfully") else: logging.info(f"No signature provided. Skipped signing {self._pack_name} pack") task_status = True except Exception: logging.exception(f"Failed to sign pack for {self._pack_name}") finally: return task_status @staticmethod def zip_folder_items(source_path, source_name, zip_pack_path): """ Zips the source_path Args: source_path (str): The source path of the folder the items are in. zip_pack_path (str): The path to the zip folder. source_name (str): The name of the source that should be zipped. """ task_status = False try: with ZipFile(zip_pack_path, 'w', ZIP_DEFLATED) as pack_zip: for root, dirs, files in os.walk(source_path, topdown=True): for f in files: full_file_path = os.path.join(root, f) relative_file_path = os.path.relpath(full_file_path, source_path) pack_zip.write(filename=full_file_path, arcname=relative_file_path) task_status = True logging.success(f"Finished zipping {source_name} folder.") except Exception: logging.exception(f"Failed in zipping {source_name} folder") finally: return task_status @staticmethod def encrypt_pack(zip_pack_path, pack_name, encryption_key, extract_destination_path, private_artifacts_dir, secondary_encryption_key): """ decrypt the pack in order to see that the pack was encrypted in the first place. Args: zip_pack_path (str): The path to the encrypted zip pack. pack_name (str): The name of the pack that should be encrypted. encryption_key (str): The key which we can decrypt the pack with. extract_destination_path (str): The path in which the pack resides. private_artifacts_dir (str): The chosen name for the private artifacts directory. secondary_encryption_key (str) : A second key which we can decrypt the pack with. """ try: current_working_dir = os.getcwd() shutil.copy('./encryptor', os.path.join(extract_destination_path, 'encryptor')) os.chmod(os.path.join(extract_destination_path, 'encryptor'), stat.S_IXOTH) os.chdir(extract_destination_path) subprocess.call('chmod +x ./encryptor', shell=True) output_file = zip_pack_path.replace("_not_encrypted.zip", ".zip") full_command = f'./encryptor ./{pack_name}_not_encrypted.zip {output_file} "{encryption_key}"' subprocess.call(full_command, shell=True) secondary_encryption_key_output_file = zip_pack_path.replace("_not_encrypted.zip", ".enc2.zip") full_command_with_secondary_encryption = f'./encryptor ./{pack_name}_not_encrypted.zip ' \ f'{secondary_encryption_key_output_file}' \ f' "{secondary_encryption_key}"' subprocess.call(full_command_with_secondary_encryption, shell=True) new_artefacts = os.path.join(current_working_dir, private_artifacts_dir) if os.path.exists(new_artefacts): shutil.rmtree(new_artefacts) os.mkdir(path=new_artefacts) shutil.copy(zip_pack_path, os.path.join(new_artefacts, f'{pack_name}_not_encrypted.zip')) shutil.copy(output_file, os.path.join(new_artefacts, f'{pack_name}.zip')) shutil.copy(secondary_encryption_key_output_file, os.path.join(new_artefacts, f'{pack_name}.enc2.zip')) os.chdir(current_working_dir) except (subprocess.CalledProcessError, shutil.Error) as error: print(f"Error while trying to encrypt pack. {error}") def decrypt_pack(self, encrypted_zip_pack_path, decryption_key): """ decrypt the pack in order to see that the pack was encrypted in the first place. Args: encrypted_zip_pack_path (str): The path for the encrypted zip pack. decryption_key (str): The key which we can decrypt the pack with. Returns: bool: whether the decryption succeeded. """ try: current_working_dir = os.getcwd() extract_destination_path = f'{current_working_dir}/decrypt_pack_dir' os.mkdir(extract_destination_path) shutil.copy('./decryptor', os.path.join(extract_destination_path, 'decryptor')) secondary_encrypted_pack_path = os.path.join(extract_destination_path, 'encrypted_zip_pack.zip') shutil.copy(encrypted_zip_pack_path, secondary_encrypted_pack_path) os.chmod(os.path.join(extract_destination_path, 'decryptor'), stat.S_IXOTH) output_decrypt_file_path = f"{extract_destination_path}/decrypt_pack.zip" os.chdir(extract_destination_path) subprocess.call('chmod +x ./decryptor', shell=True) full_command = f'./decryptor {secondary_encrypted_pack_path} {output_decrypt_file_path} "{decryption_key}"' process = subprocess.Popen(full_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdout, stderr = process.communicate() shutil.rmtree(extract_destination_path) os.chdir(current_working_dir) if stdout: logging.info(str(stdout)) if stderr: logging.error(f"Error: Premium pack {self._pack_name} should be encrypted, but isn't.") return False return True except subprocess.CalledProcessError as error: logging.exception(f"Error while trying to decrypt pack. {error}") return False def is_pack_encrypted(self, encrypted_zip_pack_path, decryption_key): """ Checks if the pack is encrypted by trying to decrypt it. Args: encrypted_zip_pack_path (str): The path for the encrypted zip pack. decryption_key (str): The key which we can decrypt the pack with. Returns: bool: whether the pack is encrypted. """ return self.decrypt_pack(encrypted_zip_pack_path, decryption_key) def zip_pack(self, extract_destination_path="", encryption_key="", private_artifacts_dir='private_artifacts', secondary_encryption_key=""): """ Zips pack folder. Returns: bool: whether the operation succeeded. str: full path to created pack zip. """ self._zip_path = f"{self._pack_path}.zip" if not encryption_key else f"{self._pack_path}_not_encrypted.zip" source_path = self._pack_path source_name = self._pack_name task_status = self.zip_folder_items(source_path, source_name, self._zip_path) # if failed to zip, skip encryption if task_status and encryption_key: try: Pack.encrypt_pack(self._zip_path, source_name, encryption_key, extract_destination_path, private_artifacts_dir, secondary_encryption_key) # If the pack needs to be encrypted, it is initially at a different location than this final path except Exception: task_status = False logging.exception(f"Failed in encrypting {source_name} folder") final_path_to_zipped_pack = f"{source_path}.zip" return task_status, final_path_to_zipped_pack def detect_modified(self, content_repo, index_folder_path, current_commit_hash, previous_commit_hash): """ Detects pack modified files. The diff is done between current commit and previous commit that was saved in metadata that was downloaded from index. In case that no commit was found in index (initial run), the default value will be set to previous commit from origin/master. Args: content_repo (git.repo.base.Repo): content repo object. index_folder_path (str): full path to downloaded index folder. current_commit_hash (str): last commit hash of head. previous_commit_hash (str): the previous commit to diff with. Returns: bool: whether the operation succeeded. list: list of RN files that were modified. bool: whether pack was modified and override will be required. """ task_status = False modified_rn_files_paths = [] pack_was_modified = False try: pack_index_metadata_path = os.path.join(index_folder_path, self._pack_name, Pack.METADATA) if not os.path.exists(pack_index_metadata_path): logging.info(f"{self._pack_name} pack was not found in index, skipping detection of modified pack.") task_status = True return with open(pack_index_metadata_path, 'r') as metadata_file: downloaded_metadata = json.load(metadata_file) previous_commit_hash = downloaded_metadata.get(Metadata.COMMIT, previous_commit_hash) # set 2 commits by hash value in order to check the modified files of the diff current_commit = content_repo.commit(current_commit_hash) previous_commit = content_repo.commit(previous_commit_hash) for modified_file in current_commit.diff(previous_commit): if modified_file.a_path.startswith(PACKS_FOLDER): modified_file_path_parts = os.path.normpath(modified_file.a_path).split(os.sep) if modified_file_path_parts[1] and modified_file_path_parts[1] == self._pack_name: if not is_ignored_pack_file(modified_file_path_parts): logging.info(f"Detected modified files in {self._pack_name} pack") task_status, pack_was_modified = True, True modified_rn_files_paths.append(modified_file.a_path) else: logging.debug(f'{modified_file.a_path} is an ignored file') task_status = True if pack_was_modified: # Make sure the modification is not only of release notes files, if so count that as not modified pack_was_modified = not all(self.RELEASE_NOTES in path for path in modified_rn_files_paths) # Filter modifications in release notes config JSON file - they will be handled later on. modified_rn_files_paths = [path_ for path_ in modified_rn_files_paths if path_.endswith('.md')] self._is_modified = pack_was_modified return except Exception: logging.exception(f"Failed in detecting modified files of {self._pack_name} pack") finally: return task_status, modified_rn_files_paths def upload_to_storage(self, zip_pack_path, latest_version, storage_bucket, override_pack, storage_base_path, private_content=False, pack_artifacts_path=None, overridden_upload_path=None): """ Manages the upload of pack zip artifact to correct path in cloud storage. The zip pack will be uploaded by defaualt to following path: /content/packs/pack_name/pack_latest_version. In case that zip pack artifact already exist at constructed path, the upload will be skipped. If flag override_pack is set to True, pack will forced for upload. If item_upload_path is provided it will override said path, and will save the item to that destination. Args: zip_pack_path (str): full path to pack zip artifact. latest_version (str): pack latest version. storage_bucket (google.cloud.storage.bucket.Bucket): google cloud storage bucket. override_pack (bool): whether to override existing pack. private_content (bool): Is being used in a private content build. storage_base_path (str): The upload destination in the target bucket for all packs (in the format of <some_path_in_the_target_bucket>/content/Packs). pack_artifacts_path (str): Path to where we are saving pack artifacts. overridden_upload_path (str): If provided, will override version_pack_path calculation and will use this path instead Returns: bool: whether the operation succeeded. bool: True in case of pack existence at targeted path and upload was skipped, otherwise returned False. str: Path to pack's zip in the bucket after the upload. """ task_status = True try: if overridden_upload_path: if private_content: logging.warning("Private content does not support overridden argument") return task_status, True, None zip_to_upload_full_path = overridden_upload_path else: version_pack_path = os.path.join(storage_base_path, self._pack_name, latest_version) existing_files = [Path(f.name).name for f in storage_bucket.list_blobs(prefix=version_pack_path)] if override_pack: logging.warning(f"Uploading {self._pack_name} pack to storage and overriding the existing pack " f"files already in storage.") elif existing_files: logging.warning(f"The following packs already exist in the storage: {", ".join(existing_files)}") logging.warning(f"Skipping step of uploading {self._pack_name}.zip to storage.") return task_status, True, None zip_to_upload_full_path = os.path.join(version_pack_path, f"{self._pack_name}.zip") blob = storage_bucket.blob(zip_to_upload_full_path) blob.cache_control = "no-cache,max-age=0" # disabling caching for pack blob with open(zip_pack_path, "rb") as pack_zip: blob.upload_from_file(pack_zip) if private_content: secondary_encryption_key_pack_name = f"{self._pack_name}.enc2.zip" secondary_encryption_key_bucket_path = os.path.join(version_pack_path, secondary_encryption_key_pack_name) # In some cases the path given is actually a zip. if isinstance(pack_artifacts_path, str) and pack_artifacts_path.endswith('content_packs.zip'): _pack_artifacts_path = pack_artifacts_path.replace('/content_packs.zip', '') else: _pack_artifacts_path = pack_artifacts_path secondary_encryption_key_artifacts_path = zip_pack_path.replace(f'{self._pack_name}', f'{self._pack_name}.enc2') blob = storage_bucket.blob(secondary_encryption_key_bucket_path) blob.cache_control = "no-cache,max-age=0" # disabling caching for pack blob with open(secondary_encryption_key_artifacts_path, "rb") as pack_zip: blob.upload_from_file(pack_zip) print( f"Copying {secondary_encryption_key_artifacts_path} to {_pack_artifacts_path}/" f"packs/{self._pack_name}.zip") shutil.copy(secondary_encryption_key_artifacts_path, f'{_pack_artifacts_path}/packs/{self._pack_name}.zip') self.public_storage_path = blob.public_url logging.success(f"Uploaded {self._pack_name} pack to {zip_to_upload_full_path} path.") return task_status, False, zip_to_upload_full_path except Exception: task_status = False logging.exception(f"Failed in uploading {self._pack_name} pack to gcs.") return task_status, True, None def copy_and_upload_to_storage(self, production_bucket, build_bucket, successful_packs_dict, storage_base_path, build_bucket_base_path): """ Manages the copy of pack zip artifact from the build bucket to the production bucket. The zip pack will be copied to following path: /content/packs/pack_name/pack_latest_version if the pack exists in the successful_packs_dict from Prepare content step in Create Instances job. Args: production_bucket (google.cloud.storage.bucket.Bucket): google cloud production bucket. build_bucket (google.cloud.storage.bucket.Bucket): google cloud build bucket. successful_packs_dict (dict): the dict of all packs were uploaded in prepare content step storage_base_path (str): The target destination of the upload in the target bucket. build_bucket_base_path (str): The path of the build bucket in gcp. Returns: bool: Status - whether the operation succeeded. bool: Skipped pack - true in case of pack existence at the targeted path and the copy process was skipped, otherwise returned False. """ pack_not_uploaded_in_prepare_content = self._pack_name not in successful_packs_dict if pack_not_uploaded_in_prepare_content: logging.warning("The following packs already exist at storage.") logging.warning(f"Skipping step of uploading {self._pack_name}.zip to storage.") return True, True latest_version = successful_packs_dict[self._pack_name][BucketUploadFlow.LATEST_VERSION] self._latest_version = latest_version build_version_pack_path = os.path.join(build_bucket_base_path, self._pack_name, latest_version) # Verifying that the latest version of the pack has been uploaded to the build bucket existing_bucket_version_files = [f.name for f in build_bucket.list_blobs(prefix=build_version_pack_path)] if not existing_bucket_version_files: logging.error(f"{self._pack_name} latest version ({latest_version}) was not found on build bucket at " f"path {build_version_pack_path}.") return False, False # We upload the pack zip object taken from the build bucket into the production bucket prod_version_pack_path = os.path.join(storage_base_path, self._pack_name, latest_version) prod_pack_zip_path = os.path.join(prod_version_pack_path, f'{self._pack_name}.zip') build_pack_zip_path = os.path.join(build_version_pack_path, f'{self._pack_name}.zip') build_pack_zip_blob = build_bucket.blob(build_pack_zip_path) try: copied_blob = build_bucket.copy_blob( blob=build_pack_zip_blob, destination_bucket=production_bucket, new_name=prod_pack_zip_path ) copied_blob.cache_control = "no-cache,max-age=0" # disabling caching for pack blob self.public_storage_path = copied_blob.public_url task_status = copied_blob.exists() except Exception as e: pack_suffix = os.path.join(self._pack_name, latest_version, f'{self._pack_name}.zip') logging.exception(f"Failed copying {pack_suffix}. Additional Info: {str(e)}") return False, False if not task_status: logging.error(f"Failed in uploading {self._pack_name} pack to production gcs.") else: # Determine if pack versions were aggregated during upload pack_uploaded_in_prepare_content = not pack_not_uploaded_in_prepare_content if pack_uploaded_in_prepare_content: agg_str = successful_packs_dict[self._pack_name].get('aggregated') if agg_str: self._aggregated = True self._aggregation_str = agg_str logging.success(f"Uploaded {self._pack_name} pack to {prod_pack_zip_path} path.") # handle dependenices zip upload when found in build bucket self.copy_and_upload_dependencies_zip_to_storage( build_bucket, build_bucket_base_path, production_bucket, storage_base_path ) return task_status, False def copy_and_upload_dependencies_zip_to_storage(self, build_bucket, build_bucket_base_path, production_bucket, storage_base_path): pack_with_deps_name = f'{self._pack_name}_with_dependencies.zip' build_pack_with_deps_path = os.path.join(build_bucket_base_path, self._pack_name, pack_with_deps_name) existing_bucket_deps_files = [f.name for f in build_bucket.list_blobs(prefix=build_pack_with_deps_path)] if existing_bucket_deps_files: logging.info(f"{self._pack_name} with dependencies was found. path {build_pack_with_deps_path}.") # We upload the pack dependencies zip object taken from the build bucket into the production bucket prod_version_pack_deps_zip_path = os.path.join(storage_base_path, self._pack_name, pack_with_deps_name) build_pack_deps_zip_blob = build_bucket.blob(build_pack_with_deps_path) try: copied_blob = build_bucket.copy_blob( blob=build_pack_deps_zip_blob, destination_bucket=production_bucket, new_name=prod_version_pack_deps_zip_path ) copied_blob.cache_control = "no-cache,max-age=0" # disabling caching for pack blob self.public_storage_path = copied_blob.public_url dep_task_status = copied_blob.exists() if not dep_task_status: logging.error(f"Failed in uploading {self._pack_name} pack with dependencies to production gcs.") except Exception as e: pack_deps_zip_suffix = os.path.join(self._pack_name, pack_with_deps_name) logging.exception(f"Failed copying {pack_deps_zip_suffix}. Additional Info: {str(e)}") def get_changelog_latest_rn(self, changelog_index_path: str) -> Tuple[dict, Version, str]: """ Returns the changelog file contents and the last version of rn in the changelog file Args: changelog_index_path (str): the changelog.json file path in the index Returns: the changelog file contents, the last version, and contents of rn in the changelog file """ logging.info(f"Found Changelog for: {self._pack_name}") if os.path.exists(changelog_index_path): try: with open(changelog_index_path, "r") as changelog_file: changelog = json.load(changelog_file) except json.JSONDecodeError: changelog = {} else: changelog = {} # get the latest rn version in the changelog.json file changelog_rn_versions = [Version(ver) for ver in changelog] # no need to check if changelog_rn_versions isn't empty because changelog file exists changelog_latest_rn_version = max(changelog_rn_versions) changelog_latest_rn = changelog[str(changelog_latest_rn_version)]["releaseNotes"] return changelog, changelog_latest_rn_version, changelog_latest_rn def get_modified_release_notes_lines(self, release_notes_dir: str, new_release_notes_versions: list, changelog: dict, modified_rn_files: list): """ In the case where an rn file was changed, this function returns the new content of the release note in the format suitable for the changelog file. In general, if two rn files are created between two consecutive upload runs (i.e. pack was changed twice), the rn files are being aggregated and the latter version is the one that is being used as a key in the changelog file, and the aggregated rns as the value. Hence, in the case of changing an rn as such, this function re-aggregates all of the rns under the corresponding version key, and returns the aggregated data, in the right format, as value under that key. Args: release_notes_dir (str): the path to the release notes dir new_release_notes_versions (list): a list of the new versions of release notes in the pack since the last upload. This means they were already handled on this upload run (and aggregated if needed). changelog (dict): the changelog from the production bucket. modified_rn_files (list): a list of the rn files that were modified according to the last commit in 'filename.md' format. Returns: A dict of modified version and their release notes contents, for modified in the current index file """ modified_versions_dict = {} for rn_filename in modified_rn_files: version = underscore_file_name_to_dotted_version(rn_filename) # Should only apply on modified files that are not the last rn file if version in new_release_notes_versions: continue # The case where the version is a key in the changelog file, # and the value is not an aggregated release note if is_the_only_rn_in_block(release_notes_dir, version, changelog): logging.info("The version is a key in the changelog file and by itself in the changelog block") with open(os.path.join(release_notes_dir, rn_filename), 'r') as rn_file: rn_lines = rn_file.read() modified_versions_dict[version] = self._clean_release_notes(rn_lines).strip() # The case where the version is not a key in the changelog file or it is a key of aggregated content else: logging.debug(f'The "{version}" version is not a key in the changelog file or it is a key of' f' aggregated content') same_block_versions_dict, higher_nearest_version = self.get_same_block_versions( release_notes_dir, version, changelog) modified_versions_dict[higher_nearest_version] = aggregate_release_notes_for_marketplace( same_block_versions_dict) return modified_versions_dict def get_same_block_versions(self, release_notes_dir: str, version: str, changelog: dict): """ Get a dict of the version as key and rn data as value of all of the versions that are in the same block in the changelog file as the given version (these are the versions that were aggregates together during a single upload priorly). Args: release_notes_dir (str): the path to the release notes dir version (str): the wanted version changelog (dict): the changelog from the production bucket. Returns: A dict of version, rn data for all corresponding versions, and the highest version among those keys as str """ lowest_version = [Version(Pack.PACK_INITIAL_VERSION)] lower_versions: list = [] higher_versions: list = [] same_block_versions_dict: dict = dict() for item in changelog.keys(): # divide the versions into lists of lower and higher than given version (lower_versions if Version(item) < Version(version) else higher_versions).append(Version(item)) higher_nearest_version = min(higher_versions) lower_versions = lower_versions + lowest_version # if the version is 1.0.0, ensure lower_versions is not empty lower_nearest_version = max(lower_versions) for rn_filename in filter_dir_files_by_extension(release_notes_dir, '.md'): current_version = underscore_file_name_to_dotted_version(rn_filename) # Catch all versions that are in the same block if lower_nearest_version < Version(current_version) <= higher_nearest_version: with open(os.path.join(release_notes_dir, rn_filename), 'r') as rn_file: rn_lines = rn_file.read() same_block_versions_dict[current_version] = self._clean_release_notes(rn_lines).strip() return same_block_versions_dict, str(higher_nearest_version) def get_release_notes_lines(self, release_notes_dir: str, changelog_latest_rn_version: Version, changelog_latest_rn: str) -> Tuple[str, str, list]: """ Prepares the release notes contents for the new release notes entry Args: release_notes_dir (str): the path to the release notes dir changelog_latest_rn_version (Version): the last version of release notes in the changelog.json file changelog_latest_rn (str): the last release notes in the changelog.json file Returns: The release notes contents, the latest release notes version (in the release notes directory), and a list of the new rn versions that this is the first time they have been uploaded. """ found_versions: list = list() pack_versions_dict: dict = dict() for filename in sorted(filter_dir_files_by_extension(release_notes_dir, '.md')): version = underscore_file_name_to_dotted_version(filename) # Aggregate all rn files that are bigger than what we have in the changelog file if Version(version) > changelog_latest_rn_version: with open(os.path.join(release_notes_dir, filename), 'r') as rn_file: rn_lines = rn_file.read() pack_versions_dict[version] = self._clean_release_notes(rn_lines).strip() found_versions.append(Version(version)) latest_release_notes_version = max(found_versions) latest_release_notes_version_str = str(latest_release_notes_version) logging.info(f"Latest ReleaseNotes version is: {latest_release_notes_version_str}") if len(pack_versions_dict) > 1: # In case that there is more than 1 new release notes file, wrap all release notes together for one # changelog entry aggregation_str = f"[{", ".join(str(lv) for lv in found_versions if lv > changelog_latest_rn_version)}]"\ f" => {latest_release_notes_version_str}" logging.info(f"Aggregating ReleaseNotes versions: {aggregation_str}") release_notes_lines = aggregate_release_notes_for_marketplace(pack_versions_dict) self._aggregated = True self._aggregation_str = aggregation_str elif len(pack_versions_dict) == 1: # In case where there is only one new release notes file release_notes_lines = pack_versions_dict[latest_release_notes_version_str] else: # In case where the pack is up to date, i.e. latest changelog is latest rn file # We should take the release notes from the index as it has might been aggregated logging.info(f'No new RN file was detected for pack {self._pack_name}, taking latest RN from the index') release_notes_lines = changelog_latest_rn new_release_notes_versions = list(pack_versions_dict.keys()) return release_notes_lines, latest_release_notes_version_str, new_release_notes_versions def assert_upload_bucket_version_matches_release_notes_version(self, changelog: dict, latest_release_notes: str) -> None: """ Sometimes there is a the current bucket is not merged from master there could be another version in the upload bucket, that does not exist in the current branch. This case can cause unpredicted behavior and we want to fail the build. This method validates that this is not the case in the current build, and if it does - fails it with an assertion error. Args: changelog: The changelog from the production bucket. latest_release_notes: The latest release notes version string in the current branch """ changelog_latest_release_notes = max(changelog, key=lambda k: Version(k)) # pylint: disable=W0108 assert Version(latest_release_notes) >= Version(changelog_latest_release_notes), \ f'{self._pack_name}: Version mismatch detected between upload bucket and current branch\n' \ f'Upload bucket version: {changelog_latest_release_notes}\n' \ f'current branch version: {latest_release_notes}\n' \ 'Please Merge from master and rebuild' def get_rn_files_names(self, modified_rn_files_paths): """ Args: modified_rn_files_paths: a list containing all modified files in the current pack, generated by comparing the old and the new commit hash. Returns: The names of the modified release notes files out of the given list only, as in the names of the files that are under ReleaseNotes directory in the format of 'filename.md'. """ modified_rn_files = [] for file_path in modified_rn_files_paths: modified_file_path_parts = os.path.normpath(file_path).split(os.sep) if self.RELEASE_NOTES in modified_file_path_parts: modified_rn_files.append(modified_file_path_parts[-1]) return modified_rn_files def prepare_release_notes(self, index_folder_path, build_number, modified_rn_files_paths=None): """ Handles the creation and update of the changelog.json files. Args: index_folder_path (str): Path to the unzipped index json. build_number (str): circleCI build number. modified_rn_files_paths (list): list of paths of the pack's modified file Returns: bool: whether the operation succeeded. bool: whether running build has not updated pack release notes. """ task_status = False not_updated_build = False release_notes_dir = os.path.join(self._pack_path, Pack.RELEASE_NOTES) modified_rn_files_paths = modified_rn_files_paths if modified_rn_files_paths else [] try: # load changelog from downloaded index logging.info(f"Loading changelog for {self._pack_name} pack") changelog_index_path = os.path.join(index_folder_path, self._pack_name, Pack.CHANGELOG_JSON) if os.path.exists(changelog_index_path): changelog, changelog_latest_rn_version, changelog_latest_rn = \ self.get_changelog_latest_rn(changelog_index_path) if os.path.exists(release_notes_dir): # Handling latest release notes files release_notes_lines, latest_release_notes, new_release_notes_versions = \ self.get_release_notes_lines( release_notes_dir, changelog_latest_rn_version, changelog_latest_rn) self.assert_upload_bucket_version_matches_release_notes_version(changelog, latest_release_notes) # Handling modified old release notes files, if there are any rn_files_names = self.get_rn_files_names(modified_rn_files_paths) modified_release_notes_lines_dict = self.get_modified_release_notes_lines( release_notes_dir, new_release_notes_versions, changelog, rn_files_names) if self._current_version != latest_release_notes: logging.error(f"Version mismatch detected between the pack's current version in " f"pack_metadata.json: {self._current_version} and latest release notes " f"version: {latest_release_notes}.") task_status = False return task_status, not_updated_build else: if latest_release_notes in changelog: logging.debug(f"Found existing release notes for version: {latest_release_notes}") version_changelog = self._create_changelog_entry(release_notes=release_notes_lines, version_display_name=latest_release_notes, build_number=build_number, new_version=False) else: logging.info(f"Created new release notes for version: {latest_release_notes}") version_changelog = self._create_changelog_entry(release_notes=release_notes_lines, version_display_name=latest_release_notes, build_number=build_number, new_version=True) if version_changelog: changelog[latest_release_notes] = version_changelog if modified_release_notes_lines_dict: logging.info("Updating changelog entries for modified release notes") for version, modified_release_notes_lines in modified_release_notes_lines_dict.items(): updated_entry = self._get_updated_changelog_entry( changelog, version, release_notes=modified_release_notes_lines) changelog[version] = updated_entry else: if len(changelog.keys()) > 1: # If there is no release notes dir but the changelog has a few entries in it, # there is a mismatch logging.warning( f"{self._pack_name} pack mismatch between {Pack.CHANGELOG_JSON} and {Pack.RELEASE_NOTES}") task_status, not_updated_build = True, True return task_status, not_updated_build else: # allow changing the initial changelog version first_key_in_changelog = list(changelog.keys())[0] changelog[first_key_in_changelog] = self._create_changelog_entry( release_notes=self.description, version_display_name=first_key_in_changelog, build_number=build_number, initial_release=True, new_version=False) logging.info(f"Found existing release notes in {Pack.CHANGELOG_JSON} for version: " f"{first_key_in_changelog} of pack {self._pack_name}. Modifying this version in " f"{Pack.CHANGELOG_JSON}") elif self._hidden: logging.warning(f"Pack {self._pack_name} is deprecated. Skipping release notes handling.") task_status = True not_updated_build = True return task_status, not_updated_build else: # if there is no changelog file for the pack, this is a new pack, and we start it's changelog at it's # current version version_changelog = self._create_changelog_entry( release_notes=self.description, version_display_name=self._current_version, build_number=build_number, new_version=True, initial_release=True ) changelog = { self._current_version: version_changelog } logging.info(f'Created {Pack.CHANGELOG_JSON} for pack {self._pack_name} starting at version' f' {self._current_version}') # Update change log entries with BC flag. self.add_bc_entries_if_needed(release_notes_dir, changelog) # write back changelog with changes to pack folder with open(os.path.join(self._pack_path, Pack.CHANGELOG_JSON), "w") as pack_changelog: json.dump(changelog, pack_changelog, indent=4) task_status = True logging.success(f"Finished creating {Pack.CHANGELOG_JSON} for {self._pack_name}") except Exception as e: logging.error(f"Failed creating {Pack.CHANGELOG_JSON} file for {self._pack_name}.\n " f"Additional info: {e}") finally: return task_status, not_updated_build def create_local_changelog(self, build_index_folder_path): """ Copies the pack index changelog.json file to the pack path Args: build_index_folder_path: The path to the build index folder Returns: bool: whether the operation succeeded. """ task_status = True build_changelog_index_path = os.path.join(build_index_folder_path, self._pack_name, Pack.CHANGELOG_JSON) pack_changelog_path = os.path.join(self._pack_path, Pack.CHANGELOG_JSON) if os.path.exists(build_changelog_index_path): try: shutil.copyfile(src=build_changelog_index_path, dst=pack_changelog_path) logging.success(f"Successfully copied pack index changelog.json file from {build_changelog_index_path}" f" to {pack_changelog_path}.") except shutil.Error as e: task_status = False logging.error(f"Failed copying changelog.json file from {build_changelog_index_path} to " f"{pack_changelog_path}. Additional info: {str(e)}") return task_status else: task_status = False logging.error( f"{self._pack_name} index changelog file is missing in build bucket path: {build_changelog_index_path}") return task_status and self.is_changelog_exists() def collect_content_items(self): """ Iterates over content items folders inside pack and collects content items data. Returns: dict: Parsed content items . """ task_status = False content_items_result: dict = {} try: # the format is defined in issue #19786, may change in the future content_item_name_mapping = { PackFolders.SCRIPTS.value: "automation", PackFolders.PLAYBOOKS.value: "playbook", PackFolders.INTEGRATIONS.value: "integration", PackFolders.INCIDENT_FIELDS.value: "incidentfield", PackFolders.INCIDENT_TYPES.value: "incidenttype", PackFolders.DASHBOARDS.value: "dashboard", PackFolders.INDICATOR_FIELDS.value: "indicatorfield", PackFolders.REPORTS.value: "report", PackFolders.INDICATOR_TYPES.value: "reputation", PackFolders.LAYOUTS.value: "layoutscontainer", PackFolders.CLASSIFIERS.value: "classifier", PackFolders.WIDGETS.value: "widget", PackFolders.GENERIC_DEFINITIONS.value: "genericdefinition", PackFolders.GENERIC_FIELDS.value: "genericfield", PackFolders.GENERIC_MODULES.value: "genericmodule", PackFolders.GENERIC_TYPES.value: "generictype", PackFolders.LISTS.value: "list", PackFolders.PREPROCESS_RULES.value: "preprocessrule", PackFolders.JOBS.value: "job", PackFolders.PARSING_RULES.value: "parsingrule", PackFolders.MODELING_RULES.value: "modelingrule", PackFolders.CORRELATION_RULES.value: "correlationrule", PackFolders.XSIAM_DASHBOARDS.value: "xsiamdashboard", PackFolders.XSIAM_REPORTS.value: "xsiamreport", PackFolders.TRIGGERS.value: "trigger", PackFolders.WIZARDS.value: "wizard", } for root, pack_dirs, pack_files_names in os.walk(self._pack_path, topdown=False): current_directory = root.split(os.path.sep)[-1] parent_directory = root.split(os.path.sep)[-2] if parent_directory in [PackFolders.GENERIC_TYPES.value, PackFolders.GENERIC_FIELDS.value]: current_directory = parent_directory elif current_directory in [PackFolders.GENERIC_TYPES.value, PackFolders.GENERIC_FIELDS.value]: continue folder_collected_items = [] for pack_file_name in pack_files_names: if not pack_file_name.endswith(('.json', '.yml')): continue pack_file_path = os.path.join(root, pack_file_name) # reputation in old format aren't supported in 6.0.0 server version if current_directory == PackFolders.INDICATOR_TYPES.value \ and not fnmatch.fnmatch(pack_file_name, 'reputation-*.json'): os.remove(pack_file_path) logging.info(f"Deleted pack {pack_file_name} reputation file for {self._pack_name} pack") continue with open(pack_file_path, 'r') as pack_file: if current_directory in PackFolders.yml_supported_folders(): content_item = yaml.safe_load(pack_file) elif current_directory in PackFolders.json_supported_folders(): content_item = json.load(pack_file) else: continue # check if content item has to version to_version = content_item.get('toversion') or content_item.get('toVersion') if to_version and Version(to_version) < Version(Metadata.SERVER_DEFAULT_MIN_VERSION): os.remove(pack_file_path) logging.info( f"{self._pack_name} pack content item {pack_file_name} has to version: {to_version}. " f"{pack_file_name} file was deleted.") continue if current_directory not in PackFolders.pack_displayed_items(): continue # skip content items that are not displayed in contentItems logging.debug( f"Iterating over {pack_file_path} file and collecting items of {self._pack_name} pack") # updated min server version from current content item self._server_min_version = get_updated_server_version(self._server_min_version, content_item, self._pack_name) content_item_tags = content_item.get('tags', []) if current_directory == PackFolders.SCRIPTS.value: folder_collected_items.append({ 'id': content_item.get('commonfields', {}).get('id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('comment', ''), 'tags': content_item_tags, }) if not self._contains_transformer and 'transformer' in content_item_tags: self._contains_transformer = True if not self._contains_filter and 'filter' in content_item_tags: self._contains_filter = True elif current_directory == PackFolders.PLAYBOOKS.value: self.add_pack_type_tags(content_item, 'Playbook') folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('description', ''), }) elif current_directory == PackFolders.INTEGRATIONS.value: integration_commands = content_item.get('script', {}).get('commands', []) self.add_pack_type_tags(content_item, 'Integration') folder_collected_items.append({ 'id': content_item.get('commonfields', {}).get('id', ''), 'name': content_item.get('display', ''), 'description': content_item.get('description', ''), 'category': content_item.get('category', ''), 'commands': [ {'name': c.get('name', ''), 'description': c.get('description', '')} for c in integration_commands], }) elif current_directory == PackFolders.INCIDENT_FIELDS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'type': content_item.get('type', ''), 'description': content_item.get('description', ''), }) elif current_directory == PackFolders.INCIDENT_TYPES.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'playbook': content_item.get('playbookId', ''), 'closureScript': content_item.get('closureScript', ''), 'hours': int(content_item.get('hours', 0)), 'days': int(content_item.get('days', 0)), 'weeks': int(content_item.get('weeks', 0)), }) elif current_directory == PackFolders.DASHBOARDS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), }) elif current_directory == PackFolders.INDICATOR_FIELDS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'type': content_item.get('type', ''), 'description': content_item.get('description', ''), }) elif current_directory == PackFolders.REPORTS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('description', ''), }) elif current_directory == PackFolders.INDICATOR_TYPES.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'details': content_item.get('details', ''), 'reputationScriptName': content_item.get('reputationScriptName', ''), 'enhancementScriptNames': content_item.get('enhancementScriptNames', []), }) elif current_directory == PackFolders.LAYOUTS.value: layout_metadata = { 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), } layout_description = content_item.get('description') if layout_description is not None: layout_metadata['description'] = layout_description folder_collected_items.append(layout_metadata) elif current_directory == PackFolders.CLASSIFIERS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name') or content_item.get('id', ''), 'description': content_item.get('description', ''), }) elif current_directory == PackFolders.WIDGETS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'dataType': content_item.get('dataType', ''), 'widgetType': content_item.get('widgetType', ''), }) elif current_directory == PackFolders.LISTS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', '') }) elif current_directory == PackFolders.GENERIC_DEFINITIONS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('description', ''), }) elif parent_directory == PackFolders.GENERIC_FIELDS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('description', ''), 'type': content_item.get('type', ''), }) elif current_directory == PackFolders.GENERIC_MODULES.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('description', ''), }) elif parent_directory == PackFolders.GENERIC_TYPES.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('description', ''), }) elif current_directory == PackFolders.PREPROCESS_RULES.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('description', ''), }) elif current_directory == PackFolders.JOBS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), # note that `name` may technically be blank, but shouldn't pass validations 'name': content_item.get('name', ''), 'details': content_item.get('details', ''), }) elif current_directory == PackFolders.PARSING_RULES.value: self.add_pack_type_tags(content_item, 'ParsingRule') folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), }) elif current_directory == PackFolders.MODELING_RULES.value: self.add_pack_type_tags(content_item, 'ModelingRule') folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), }) elif current_directory == PackFolders.CORRELATION_RULES.value: self.add_pack_type_tags(content_item, 'CorrelationRule') folder_collected_items.append({ 'id': content_item.get('global_rule_id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('description', ''), }) elif current_directory == PackFolders.XSIAM_DASHBOARDS.value: folder_collected_items.append({ 'id': content_item.get('dashboards_data', [{}])[0].get('global_id', ''), 'name': content_item.get('dashboards_data', [{}])[0].get('name', ''), 'description': content_item.get('dashboards_data', [{}])[0].get('description', ''), }) elif current_directory == PackFolders.XSIAM_REPORTS.value: folder_collected_items.append({ 'id': content_item.get('templates_data', [{}])[0].get('global_id', ''), 'name': content_item.get('templates_data', [{}])[0].get('report_name', ''), 'description': content_item.get('templates_data', [{}])[0].get('report_description', ''), }) elif current_directory == PackFolders.TRIGGERS.value: folder_collected_items.append({ 'id': content_item.get('trigger_id', ''), 'name': content_item.get('trigger_name', ''), 'description': content_item.get('description', ''), }) elif current_directory == PackFolders.WIZARDS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('description', ''), 'dependency_packs': content_item.get('dependency_packs', {}) }) else: logging.info(f'Failed to collect: {current_directory}') if current_directory in PackFolders.pack_displayed_items(): content_item_key = content_item_name_mapping[current_directory] content_items_result[content_item_key] = \ content_items_result.get(content_item_key, []) + folder_collected_items logging.success(f"Finished collecting content items for {self._pack_name} pack") task_status = True except Exception: logging.exception(f"Failed collecting content items in {self._pack_name} pack") finally: self._content_items = content_items_result return task_status def load_user_metadata(self): """ Loads user defined metadata and stores part of it's data in defined properties fields. Returns: bool: whether the operation succeeded. """ task_status = False user_metadata = {} try: user_metadata_path = os.path.join(self._pack_path, Pack.USER_METADATA) # user metadata path before parsing if not os.path.exists(user_metadata_path): logging.error(f"{self._pack_name} pack is missing {Pack.USER_METADATA} file.") return task_status with open(user_metadata_path, "r") as user_metadata_file: user_metadata = json.load(user_metadata_file) # loading user metadata # part of old packs are initialized with empty list user_metadata = {} if isinstance(user_metadata, list) else user_metadata # store important user metadata fields self.support_type = user_metadata.get(Metadata.SUPPORT, Metadata.XSOAR_SUPPORT) self.current_version = user_metadata.get(Metadata.CURRENT_VERSION, '') self.hidden = user_metadata.get(Metadata.HIDDEN, False) self.description = user_metadata.get(Metadata.DESCRIPTION, False) self.display_name = user_metadata.get(Metadata.NAME, '') # type: ignore[misc] self._user_metadata = user_metadata self._eula_link = user_metadata.get(Metadata.EULA_LINK, Metadata.EULA_URL) self._marketplaces = user_metadata.get('marketplaces', ['xsoar']) logging.info(f"Finished loading {self._pack_name} pack user metadata") task_status = True except Exception: logging.exception(f"Failed in loading {self._pack_name} user metadata.") finally: return task_status def _collect_pack_tags(self, user_metadata, landing_page_sections, trending_packs): tags = set(input_to_list(input_data=user_metadata.get('tags'))) tags |= self._get_tags_from_landing_page(landing_page_sections) tags |= {PackTags.TIM} if self._is_feed else set() tags |= {PackTags.USE_CASE} if self._use_cases else set() tags |= {PackTags.TRANSFORMER} if self._contains_transformer else set() tags |= {PackTags.FILTER} if self._contains_filter else set() tags |= {PackTags.COLLECTION} if self._is_siem else set() if self._create_date: days_since_creation = (datetime.utcnow() - datetime.strptime(self._create_date, Metadata.DATE_FORMAT)).days if days_since_creation <= 30: tags |= {PackTags.NEW} else: tags -= {PackTags.NEW} if trending_packs: if self._pack_name in trending_packs: tags |= {PackTags.TRENDING} else: tags -= {PackTags.TRENDING} return tags def _enhance_pack_attributes(self, index_folder_path, dependencies_metadata_dict, statistics_handler=None, format_dependencies_only=False): """ Enhances the pack object with attributes for the metadata file Args: dependencies_metadata_dict (dict): mapping of pack dependencies metadata, for first level dependencies. format_dependencies_only (bool): Indicates whether the metadata formation is just for formatting the dependencies or not. Returns: dict: parsed pack metadata. """ landing_page_sections = mp_statistics.StatisticsHandler.get_landing_page_sections() trending_packs = None pack_dependencies_by_download_count = self._displayed_images_dependent_on_packs if not format_dependencies_only: # ===== Pack Regular Attributes ===== self._support_type = self.user_metadata.get(Metadata.SUPPORT, Metadata.XSOAR_SUPPORT) self._support_details = self._create_support_section( support_type=self._support_type, support_url=self.user_metadata.get(Metadata.URL), support_email=self.user_metadata.get(Metadata.EMAIL) ) self._author = self._get_author( support_type=self._support_type, author=self.user_metadata.get(Metadata.AUTHOR, '')) self._certification = self._get_certification( support_type=self._support_type, certification=self.user_metadata.get(Metadata.CERTIFICATION) ) self._legacy = self.user_metadata.get(Metadata.LEGACY, True) self._create_date = self._get_pack_creation_date(index_folder_path) self._update_date = self._get_pack_update_date(index_folder_path) self._use_cases = input_to_list(input_data=self.user_metadata.get(Metadata.USE_CASES), capitalize_input=True) self._categories = input_to_list(input_data=self.user_metadata.get(Metadata.CATEGORIES), capitalize_input=True) self._keywords = input_to_list(self.user_metadata.get(Metadata.KEY_WORDS)) self._parsed_dependencies = self._parse_pack_dependencies(self.user_metadata.get(Metadata.DEPENDENCIES, {}), dependencies_metadata_dict) # ===== Pack Private Attributes ===== if not format_dependencies_only: self._is_private_pack = Metadata.PARTNER_ID in self.user_metadata self._is_premium = self._is_private_pack self._preview_only = get_valid_bool(self.user_metadata.get(Metadata.PREVIEW_ONLY, False)) self._price = convert_price(pack_id=self._pack_name, price_value_input=self.user_metadata.get('price')) if self._is_private_pack: self._vendor_id = self.user_metadata.get(Metadata.VENDOR_ID, "") self._partner_id = self.user_metadata.get(Metadata.PARTNER_ID, "") self._partner_name = self.user_metadata.get(Metadata.PARTNER_NAME, "") self._content_commit_hash = self.user_metadata.get(Metadata.CONTENT_COMMIT_HASH, "") # Currently all content packs are legacy. # Since premium packs cannot be legacy, we directly set this attribute to false. self._legacy = False # ===== Pack Statistics Attributes ===== if not self._is_private_pack and statistics_handler: # Public Content case self._pack_statistics_handler = mp_statistics.PackStatisticsHandler( self._pack_name, statistics_handler.packs_statistics_df, statistics_handler.packs_download_count_desc, self._displayed_images_dependent_on_packs ) self._downloads_count = self._pack_statistics_handler.download_count trending_packs = statistics_handler.trending_packs pack_dependencies_by_download_count = self._pack_statistics_handler.displayed_dependencies_sorted self._tags = self._collect_pack_tags(self.user_metadata, landing_page_sections, trending_packs) self._search_rank = mp_statistics.PackStatisticsHandler.calculate_search_rank( tags=self._tags, certification=self._certification, content_items=self._content_items ) self._related_integration_images = self._get_all_pack_images( self._displayed_integration_images, self._displayed_images_dependent_on_packs, dependencies_metadata_dict, pack_dependencies_by_download_count ) def format_metadata(self, index_folder_path, packs_dependencies_mapping, build_number, commit_hash, statistics_handler, packs_dict=None, marketplace='xsoar', format_dependencies_only=False): """ Re-formats metadata according to marketplace metadata format defined in issue #19786 and writes back the result. Args: index_folder_path (str): downloaded index folder directory path. packs_dependencies_mapping (dict): all packs dependencies lookup mapping. build_number (str): circleCI build number. commit_hash (str): current commit hash. statistics_handler (StatisticsHandler): The marketplace statistics handler packs_dict (dict): dict of all packs relevant for current marketplace, as {pack_id: pack_object}. marketplace (str): Marketplace of current upload. format_dependencies_only (bool): Indicates whether the metadata formation is just for formatting the dependencies or not. Returns: bool: True is returned in case metadata file was parsed successfully, otherwise False. bool: True is returned in pack is missing dependencies. """ task_status = False packs_dict = packs_dict if packs_dict else {} is_missing_dependencies = False try: self.set_pack_dependencies(packs_dependencies_mapping, packs_dict, marketplace=marketplace) logging.info(f"Loading pack dependencies metadata for {self._pack_name} pack") dependencies_metadata_dict, is_missing_dependencies = self._load_pack_dependencies_metadata( index_folder_path, packs_dict) self._enhance_pack_attributes(index_folder_path, dependencies_metadata_dict, statistics_handler, format_dependencies_only) formatted_metadata = self._parse_pack_metadata(build_number, commit_hash) metadata_path = os.path.join(self._pack_path, Pack.METADATA) # deployed metadata path after parsing json_write(metadata_path, formatted_metadata) # writing back parsed metadata logging.success(f"Finished formatting {self._pack_name} packs's {Pack.METADATA} {metadata_path} file.") task_status = True except Exception as e: logging.exception(f"Failed in formatting {self._pack_name} pack metadata. Additional Info: {str(e)}") finally: return task_status, is_missing_dependencies @staticmethod def pack_created_in_time_delta(pack_name, time_delta: timedelta, index_folder_path: str) -> bool: """ Checks if pack created before delta specified in the 'time_delta' argument and return boolean according to the result Args: pack_name: the pack name. time_delta: time_delta to check if pack was created before. index_folder_path: downloaded index folder directory path. Returns: True if pack was created before the time_delta from now, and False otherwise. """ pack_creation_time_str = Pack._calculate_pack_creation_date(pack_name, index_folder_path) return datetime.utcnow() - datetime.strptime(pack_creation_time_str, Metadata.DATE_FORMAT) < time_delta def _get_pack_creation_date(self, index_folder_path): return self._calculate_pack_creation_date(self._pack_name, index_folder_path) @staticmethod def _calculate_pack_creation_date(pack_name, index_folder_path): """ Gets the pack created date. Args: index_folder_path (str): downloaded index folder directory path. Returns: datetime: Pack created date. """ created_time = datetime.utcnow().strftime(Metadata.DATE_FORMAT) metadata = load_json(os.path.join(index_folder_path, pack_name, Pack.METADATA)) if metadata: if metadata.get(Metadata.CREATED): created_time = metadata.get(Metadata.CREATED, '') else: raise Exception(f'The metadata file of the {pack_name} pack does not contain "{Metadata.CREATED}" time') return created_time def _get_pack_update_date(self, index_folder_path): """ Gets the pack update date. Args: index_folder_path (str): downloaded index folder directory path. Returns: datetime: Pack update date. """ latest_changelog_released_date = datetime.utcnow().strftime(Metadata.DATE_FORMAT) changelog = load_json(os.path.join(index_folder_path, self._pack_name, Pack.CHANGELOG_JSON)) if changelog and not self.is_modified: packs_latest_release_notes = max(Version(ver) for ver in changelog) latest_changelog_version = changelog.get(str(packs_latest_release_notes), {}) latest_changelog_released_date = latest_changelog_version.get('released') return latest_changelog_released_date def set_pack_dependencies(self, packs_dependencies_mapping, packs_dict, marketplace='xsoar'): """ Retrieve all pack's dependencies by merging the calculated dependencies from pack_dependencies.json file, given as input priorly, and the hard coded dependencies featured in the pack_metadata.json file. This is done for both first level dependencies and the all levels dependencies. Args: packs_dependencies_mapping: the calculated dependencies from pack_dependencies.json file packs_dict (dict): Dict of packs relevant for current marketplace as {pack_name: pack_object} marketplace: the current marketplace this upload is for """ pack_dependencies_mapping = packs_dependencies_mapping.get(self._pack_name, {}) first_level_dependencies = pack_dependencies_mapping.get(Metadata.DEPENDENCIES, {}) all_levels_dependencies = pack_dependencies_mapping.get(Metadata.ALL_LEVELS_DEPENDENCIES, []) displayed_images_dependent_on_packs = pack_dependencies_mapping.get(Metadata.DISPLAYED_IMAGES, []) # filter out packs that are not a part of the marketplace this upload is for first_level_dependencies = {k: v for k, v in first_level_dependencies.items() if k in packs_dict} all_levels_dependencies = [k for k in all_levels_dependencies if k in packs_dict] displayed_images_dependent_on_packs = [k for k in displayed_images_dependent_on_packs if k in packs_dict] if Metadata.DISPLAYED_IMAGES not in self._user_metadata: self._user_metadata[Metadata.DISPLAYED_IMAGES] = displayed_images_dependent_on_packs if Metadata.DEPENDENCIES not in self._user_metadata: self._user_metadata[Metadata.DEPENDENCIES] = {} if self._pack_name != GCPConfig.BASE_PACK: # add base as a mandatory pack dependency, by design for all packs first_level_dependencies.update(BASE_PACK_DEPENDENCY_DICT) # update the calculated dependencies with the hardcoded dependencies first_level_dependencies.update(self.user_metadata[Metadata.DEPENDENCIES]) # If it is a core pack, check that no new mandatory packs (that are not core packs) were added # They can be overridden in the user metadata to be not mandatory so we need to check there as well core_packs = GCPConfig.get_core_packs(marketplace) if self._pack_name in core_packs: mandatory_dependencies = [k for k, v in first_level_dependencies.items() if v.get(Metadata.MANDATORY, False) is True and k not in core_packs and k not in self._user_metadata[Metadata.DEPENDENCIES].keys()] if mandatory_dependencies: raise Exception(f'New mandatory dependencies {mandatory_dependencies} were ' f'found in the core pack {self._pack_name}') self._user_metadata[Metadata.DEPENDENCIES] = first_level_dependencies self._first_level_dependencies = first_level_dependencies self._all_levels_dependencies = all_levels_dependencies self._displayed_images_dependent_on_packs = displayed_images_dependent_on_packs def prepare_for_index_upload(self): """ Removes and leaves only necessary files in pack folder. Returns: bool: whether the operation succeeded. """ task_status = False files_to_leave = [Pack.METADATA, Pack.CHANGELOG_JSON, Pack.README] try: for file_or_folder in os.listdir(self._pack_path): files_or_folder_path = os.path.join(self._pack_path, file_or_folder) if file_or_folder in files_to_leave: continue if os.path.isdir(files_or_folder_path): shutil.rmtree(files_or_folder_path) else: os.remove(files_or_folder_path) task_status = True except Exception: logging.exception(f"Failed in preparing index for upload in {self._pack_name} pack.") finally: return task_status @staticmethod def _get_spitted_yml_image_data(root, target_folder_files): """ Retrieves pack integration image and integration display name and returns binding image data. Args: root (str): full path to the target folder to search integration image. target_folder_files (list): list of files inside the targeted folder. Returns: dict: path to integration image and display name of the integration. """ image_data = {} for pack_file in target_folder_files: if pack_file.startswith('.'): continue if pack_file.endswith('_image.png'): image_data['repo_image_path'] = os.path.join(root, pack_file) elif pack_file.endswith('.yml'): with open(os.path.join(root, pack_file), 'r') as integration_file: integration_yml = yaml.safe_load(integration_file) image_data['display_name'] = integration_yml.get('display', '') return image_data def _get_image_data_from_yml(self, pack_file_path): """ Creates temporary image file and retrieves integration display name. Args: pack_file_path (str): full path to the target yml_path integration yml to search integration image. Returns: dict: path to temporary integration image, display name of the integrations and the basename of the integration in content_pack.zip. """ image_data = {} if pack_file_path.endswith('.yml'): with open(pack_file_path, 'r') as integration_file: integration_yml = yaml.safe_load(integration_file) image_data['display_name'] = integration_yml.get('display', '') # create temporary file of base64 decoded data integration_name = integration_yml.get('name', '') base64_image = integration_yml['image'].split(',')[1] if integration_yml.get('image') else None if not base64_image: logging.warning(f"{integration_name} integration image was not found in {self._pack_name} pack") return {} temp_image_name = f'{integration_name.replace(' ', '')}_image.png' temp_image_path = os.path.join(self._pack_path, temp_image_name) with open(temp_image_path, 'wb') as image_file: image_file.write(base64.b64decode(base64_image)) self._remove_files_list.append(temp_image_name) # add temporary file to tracking list image_data['image_path'] = temp_image_path image_data['integration_path_basename'] = os.path.basename(pack_file_path) logging.info(f"Created temporary integration {image_data["display_name"]} image for {self._pack_name} pack") return image_data def _search_for_images(self, target_folder): """ Searches for png files in targeted folder. Args: target_folder (str): full path to directory to search. Returns: list: list of dictionaries that include image path and display name of integration, example: [{'image_path': image_path, 'display_name': integration_display_name},...] """ target_folder_path = os.path.join(self._pack_path, target_folder) images_list = [] if os.path.exists(target_folder_path): for pack_item in os.scandir(target_folder_path): image_data = self._get_image_data_from_yml(pack_item.path) if image_data and image_data not in images_list: images_list.append(image_data) return images_list def check_if_exists_in_index(self, index_folder_path): """ Checks if pack is sub-folder of downloaded index. Args: index_folder_path (str): index folder full path. Returns: bool: whether the operation succeeded. bool: whether pack exists in index folder. """ task_status, exists_in_index = False, False try: if not os.path.exists(index_folder_path): logging.error(f"{GCPConfig.INDEX_NAME} does not exists.") return task_status, exists_in_index exists_in_index = os.path.exists(os.path.join(index_folder_path, self._pack_name)) task_status = True except Exception: logging.exception(f"Failed searching {self._pack_name} pack in {GCPConfig.INDEX_NAME}") finally: return task_status, exists_in_index @staticmethod def remove_contrib_suffix_from_name(display_name: str) -> str: """ Removes the contribution details suffix from the integration's display name Args: display_name (str): The integration display name. Returns: str: The display name without the contrib details suffix """ contribution_suffixes = ('(Partner Contribution)', '(Developer Contribution)', '(Community Contribution)') for suffix in contribution_suffixes: index = display_name.find(suffix) if index != -1: display_name = display_name[:index].rstrip(' ') break return display_name @staticmethod def need_to_upload_integration_image(image_data: dict, integration_dirs: list, unified_integrations: list): """ Checks whether needs to upload the integration image or not. We upload in one of the two cases: 1. The integration_path_basename is one of the integration dirs detected 2. The integration_path_basename is one of the added/modified unified integrations Args: image_data (dict): path to temporary integration image, display name of the integrations and the basename of the integration in content_pack.zip. integration_dirs (list): The list of integrations to search in for images unified_integrations (list): The list of unified integrations to upload their image Returns: bool: True if we need to upload the image or not """ integration_path_basename = image_data['integration_path_basename'] return any([ re.findall(BucketUploadFlow.INTEGRATION_DIR_REGEX, integration_path_basename)[0] in integration_dirs, integration_path_basename in unified_integrations ]) def upload_integration_images(self, storage_bucket, storage_base_path, diff_files_list=None, detect_changes=False): """ Uploads pack integrations images to gcs. The returned result of integration section are defined in issue #19786. Args: storage_bucket (google.cloud.storage.bucket.Bucket): google storage bucket where image will be uploaded. storage_base_path (str): The target destination of the upload in the target bucket. detect_changes (bool): Whether to detect changes or upload all images in any case. diff_files_list (list): The list of all modified/added files found in the diff Returns: bool: whether the operation succeeded. list: list of dictionaries with uploaded pack integration images. """ task_status = True integration_images = [] integration_dirs = [] unified_integrations = [] try: if detect_changes: # detect added/modified integration images for file in diff_files_list: if self.is_integration_image(file.a_path): # integration dir name will show up in the unified integration file path in content_packs.zip integration_dirs.append(os.path.basename(os.path.dirname(file.a_path))) elif self.is_unified_integration(file.a_path): # if the file found in the diff is a unified integration we upload its image unified_integrations.append(os.path.basename(file.a_path)) pack_local_images = self._search_for_images(target_folder=PackFolders.INTEGRATIONS.value) if not pack_local_images: return True # return empty list if no images were found pack_storage_root_path = os.path.join(storage_base_path, self._pack_name) for image_data in pack_local_images: image_path = image_data.get('image_path') if not image_path: raise Exception(f"{self._pack_name} pack integration image was not found") image_name = os.path.basename(image_path) image_storage_path = os.path.join(pack_storage_root_path, image_name) pack_image_blob = storage_bucket.blob(image_storage_path) if not detect_changes or \ self.need_to_upload_integration_image(image_data, integration_dirs, unified_integrations): # upload the image if needed logging.info(f"Uploading image: {image_name} of integration: {image_data.get("display_name")} " f"from pack: {self._pack_name}") with open(image_path, "rb") as image_file: pack_image_blob.upload_from_file(image_file) self._uploaded_integration_images.append(image_name) if GCPConfig.USE_GCS_RELATIVE_PATH: image_gcs_path = urllib.parse.quote( os.path.join(GCPConfig.IMAGES_BASE_PATH, self._pack_name, image_name)) else: image_gcs_path = pack_image_blob.public_url integration_name = image_data.get('display_name', '') if self.support_type != Metadata.XSOAR_SUPPORT: integration_name = self.remove_contrib_suffix_from_name(integration_name) integration_images.append({ 'name': integration_name, 'imagePath': image_gcs_path }) if self._uploaded_integration_images: logging.info(f"Uploaded {len(self._uploaded_integration_images)} images for {self._pack_name} pack.") except Exception as e: task_status = False logging.exception(f"Failed to upload {self._pack_name} pack integration images. Additional Info: {str(e)}") finally: self._displayed_integration_images = integration_images return task_status def copy_integration_images(self, production_bucket, build_bucket, images_data, storage_base_path, build_bucket_base_path): """ Copies all pack's integration images from the build bucket to the production bucket Args: production_bucket (google.cloud.storage.bucket.Bucket): The production bucket build_bucket (google.cloud.storage.bucket.Bucket): The build bucket images_data (dict): The images data structure from Prepare Content step storage_base_path (str): The target destination of the upload in the target bucket. build_bucket_base_path (str): The path of the build bucket in gcp. Returns: bool: Whether the operation succeeded. """ task_status = True num_copied_images = 0 err_msg = f"Failed copying {self._pack_name} pack integrations images." pc_uploaded_integration_images = images_data.get(self._pack_name, {}).get(BucketUploadFlow.INTEGRATIONS, []) for image_name in pc_uploaded_integration_images: build_bucket_image_path = os.path.join(build_bucket_base_path, self._pack_name, image_name) build_bucket_image_blob = build_bucket.blob(build_bucket_image_path) if not build_bucket_image_blob.exists(): logging.error(f"Found changed/added integration image {image_name} in content repo but " f"{build_bucket_image_path} does not exist in build bucket") task_status = False else: logging.info(f"Copying {self._pack_name} pack integration image: {image_name}") try: copied_blob = build_bucket.copy_blob( blob=build_bucket_image_blob, destination_bucket=production_bucket, new_name=os.path.join(storage_base_path, self._pack_name, image_name) ) if not copied_blob.exists(): logging.error(f"Copy {self._pack_name} integration image: {build_bucket_image_blob.name} " f"blob to {copied_blob.name} blob failed.") task_status = False else: num_copied_images += 1 except Exception as e: logging.exception(f"{err_msg}. Additional Info: {str(e)}") return False if not task_status: logging.error(err_msg) else: if num_copied_images == 0: logging.info(f"No added/modified integration images were detected in {self._pack_name} pack.") else: logging.success(f"Copied {num_copied_images} images for {self._pack_name} pack.") return task_status def upload_author_image(self, storage_bucket, storage_base_path, diff_files_list=None, detect_changes=False): """ Uploads pack author image to gcs. Searches for `Author_image.png` and uploads author image to gcs. In case no such image was found, default Base pack image path is used and it's gcp path is returned. Args: storage_bucket (google.cloud.storage.bucket.Bucket): gcs bucket where author image will be uploaded. storage_base_path (str): the path under the bucket to upload to. diff_files_list (list): The list of all modified/added files found in the diff detect_changes (bool): Whether to detect changes or upload the author image in any case. Returns: bool: whether the operation succeeded. str: public gcp path of author image. """ task_status = True author_image_storage_path = "" try: author_image_path = os.path.join(self._pack_path, Pack.AUTHOR_IMAGE_NAME) # disable-secrets-detection if os.path.exists(author_image_path): image_to_upload_storage_path = os.path.join(storage_base_path, self._pack_name, Pack.AUTHOR_IMAGE_NAME) # disable-secrets-detection pack_author_image_blob = storage_bucket.blob(image_to_upload_storage_path) if not detect_changes or any(self.is_author_image(file.a_path) for file in diff_files_list): # upload the image if needed with open(author_image_path, "rb") as author_image_file: pack_author_image_blob.upload_from_file(author_image_file) self._uploaded_author_image = True logging.success(f"Uploaded successfully {self._pack_name} pack author image") if GCPConfig.USE_GCS_RELATIVE_PATH: author_image_storage_path = urllib.parse.quote( os.path.join(GCPConfig.IMAGES_BASE_PATH, self._pack_name, Pack.AUTHOR_IMAGE_NAME)) else: author_image_storage_path = pack_author_image_blob.public_url elif self.support_type == Metadata.XSOAR_SUPPORT: # use default Base pack image for xsoar supported packs author_image_storage_path = os.path.join(GCPConfig.IMAGES_BASE_PATH, GCPConfig.BASE_PACK, Pack.AUTHOR_IMAGE_NAME) # disable-secrets-detection if not GCPConfig.USE_GCS_RELATIVE_PATH: # disable-secrets-detection-start author_image_storage_path = os.path.join(GCPConfig.GCS_PUBLIC_URL, storage_bucket.name, author_image_storage_path) # disable-secrets-detection-end logging.info((f"Skipping uploading of {self._pack_name} pack author image " f"and use default {GCPConfig.BASE_PACK} pack image")) else: logging.info(f"Skipping uploading of {self._pack_name} pack author image. " f"The pack is defined as {self.support_type} support type") except Exception: logging.exception(f"Failed uploading {self._pack_name} pack author image.") task_status = False author_image_storage_path = "" finally: self._author_image = author_image_storage_path return task_status def copy_author_image(self, production_bucket, build_bucket, images_data, storage_base_path, build_bucket_base_path): """ Copies pack's author image from the build bucket to the production bucket Searches for `Author_image.png`, In case no such image was found, default Base pack image path is used and it's gcp path is returned. Args: production_bucket (google.cloud.storage.bucket.Bucket): The production bucket build_bucket (google.cloud.storage.bucket.Bucket): The build bucket images_data (dict): The images data structure from Prepare Content step storage_base_path (str): The target destination of the upload in the target bucket. build_bucket_base_path (str): The path of the build bucket in gcp. Returns: bool: Whether the operation succeeded. """ if images_data.get(self._pack_name, {}).get(BucketUploadFlow.AUTHOR, False): build_author_image_path = os.path.join(build_bucket_base_path, self._pack_name, Pack.AUTHOR_IMAGE_NAME) build_author_image_blob = build_bucket.blob(build_author_image_path) if build_author_image_blob.exists(): try: copied_blob = build_bucket.copy_blob( blob=build_author_image_blob, destination_bucket=production_bucket, new_name=os.path.join(storage_base_path, self._pack_name, Pack.AUTHOR_IMAGE_NAME)) if not copied_blob.exists(): logging.error(f"Failed copying {self._pack_name} pack author image.") return False else: logging.success(f"Copied successfully {self._pack_name} pack author image.") return True except Exception as e: logging.exception(f"Failed copying {Pack.AUTHOR_IMAGE_NAME} for {self._pack_name} pack. " f"Additional Info: {str(e)}") return False else: logging.error(f"Found changed/added author image in content repo for {self._pack_name} pack but " f"image does not exist in build bucket in path {build_author_image_path}.") return False else: logging.info(f"No added/modified author image was detected in {self._pack_name} pack.") return True def upload_images(self, index_folder_path, storage_bucket, storage_base_path, diff_files_list): """ Upload the images related to the pack. The image is uploaded in the case it was modified, OR if this is the first time the current pack is being uploaded to this current marketplace (#46785). Args: index_folder_path (str): the path to the local index folder storage_bucket (google.cloud.storage.bucket.Bucket): gcs bucket where author image will be uploaded. storage_base_path (str): the path under the bucket to upload to. diff_files_list (list): The list of all modified/added files found in the diff Returns: True if the images were successfully uploaded, false otherwise. """ detect_changes = os.path.exists(os.path.join(index_folder_path, self.name, Pack.METADATA)) or self.hidden # Don't check if the image was modified if this is the first time it is uploaded to this marketplace, meaning it # doesn't exist in the index (and it isn't deprecated) if not detect_changes: logging.info(f'Uploading images of pack {self.name} which did not exist in this marketplace before') task_status = self.upload_integration_images(storage_bucket, storage_base_path, diff_files_list, detect_changes) if not task_status: self._status = PackStatus.FAILED_IMAGES_UPLOAD.name self.cleanup() return False task_status = self.upload_author_image(storage_bucket, storage_base_path, diff_files_list, detect_changes) if not task_status: self._status = PackStatus.FAILED_AUTHOR_IMAGE_UPLOAD.name self.cleanup() return False return True def cleanup(self): """ Finalization action, removes extracted pack folder. """ if os.path.exists(self._pack_path): shutil.rmtree(self._pack_path) logging.info(f"Cleanup {self._pack_name} pack from: {self._pack_path}") def is_changelog_exists(self): """ Indicates whether the local changelog of a given pack exists or not Returns: bool: The answer """ return os.path.isfile(os.path.join(self._pack_path, Pack.CHANGELOG_JSON)) def is_failed_to_upload(self, failed_packs_dict): """ Checks if the pack was failed to upload in Prepare Content step in Create Instances job Args: failed_packs_dict (dict): The failed packs file Returns: bool: Whether the operation succeeded. str: The pack's failing status """ if self._pack_name in failed_packs_dict: return True, failed_packs_dict[self._pack_name].get('status') else: return False, str() def is_integration_image(self, file_path: str): """ Indicates whether a file_path is an integration image or not Args: file_path (str): The file path Returns: bool: True if the file is an integration image or False otherwise """ return all([ file_path.startswith(os.path.join(PACKS_FOLDER, self._pack_name)), file_path.endswith('.png'), 'image' in os.path.basename(file_path.lower()), os.path.basename(file_path) != Pack.AUTHOR_IMAGE_NAME ]) def is_author_image(self, file_path: str): """ Indicates whether a file_path is an author image or not Args: file_path (str): The file path Returns: bool: True if the file is an author image or False otherwise """ return file_path == os.path.join(PACKS_FOLDER, self._pack_name, Pack.AUTHOR_IMAGE_NAME) def is_unified_integration(self, file_path: str): """ Indicates whether a file_path is a unified integration yml file or not Args: file_path (str): The file path Returns: bool: True if the file is a unified integration or False otherwise """ return all([ file_path.startswith(os.path.join(PACKS_FOLDER, self._pack_name, PackFolders.INTEGRATIONS.value)), os.path.basename(os.path.dirname(file_path)) == PackFolders.INTEGRATIONS.value, os.path.basename(file_path).startswith('integration'), os.path.basename(file_path).endswith('.yml') ]) def add_bc_entries_if_needed(self, release_notes_dir: str, changelog: Dict[str, Any]) -> None: """ Receives changelog, checks if there exists a BC version in each changelog entry (as changelog entry might be zipped into few RN versions, check if at least one of the versions is BC). Check if RN is BC is done by doing the following: 1) Check if RN has corresponding config file, e.g 1_0_1.md has corresponding 1_0_1.json file. 2) If it does, check if `isBreakingChanges` field is true If such version exists, adds a true value to 'breakingChanges' field. if JSON file also has breakingChangesNotes configures, adds `breakingChangesNotes` field to changelog file. This function iterates every entry in changelog because it takes into consideration four scenarios: a) Entry without breaking changes, changes to entry with breaking changes (because at least one of the versions in the entry was marked as breaking changes). b) Entry without breaking changes, does not change. c) Entry with breaking changes, changes to entry without breaking changes (because all the BC versions corresponding to the changelog entry were re-marked as not BC). d) Entry with breaking changes, does not change. Args: release_notes_dir (str): RN dir path. changelog (Dict[str, Any]): Changelog data represented as a dict. Returns: (None): Modifies changelog, adds bool value to 'breakingChanges' and `breakingChangesNotes` fields to every changelog entry, according to the logic described above. """ if not os.path.exists(release_notes_dir): return bc_version_to_text: Dict[str, Optional[str]] = self._breaking_changes_versions_to_text(release_notes_dir) loose_versions: List[Version] = [Version(bc_ver) for bc_ver in bc_version_to_text] predecessor_version: Version = Version('0.0.0') for changelog_entry in sorted(changelog.keys(), key=Version): rn_loose_version: Version = Version(changelog_entry) if bc_versions := self._changelog_entry_bc_versions(predecessor_version, rn_loose_version, loose_versions, bc_version_to_text): logging.info(f'Changelog entry {changelog_entry} contains BC versions') changelog[changelog_entry]['breakingChanges'] = True if bc_text := self._calculate_bc_text(release_notes_dir, bc_versions): changelog[changelog_entry]['breakingChangesNotes'] = bc_text else: changelog[changelog_entry].pop('breakingChangesNotes', None) else: changelog[changelog_entry].pop('breakingChanges', None) predecessor_version = rn_loose_version def _calculate_bc_text(self, release_notes_dir: str, bc_version_to_text: Dict[str, Optional[str]]) -> Optional[str]: """ Receives BC versions to text dict for current changelog entry. Calculates text for BC entry. Args: release_notes_dir (str): RN dir path. bc_version_to_text (Dict[str, Optional[str]): {bc version, bc_text} Returns: (Optional[str]): Text for entry if such was added. If none is returned, server will list the full RN as the BC notes instead. """ # Handle cases of one BC version in entry. if len(bc_version_to_text) == 1: return list(bc_version_to_text.values())[0] # Handle cases of two or more BC versions in entry. text_of_bc_versions, bc_without_text = self._split_bc_versions_with_and_without_text(bc_version_to_text) if len(text_of_bc_versions) == 0: # Case 1: Not even one BC version contains breaking text. return None elif len(text_of_bc_versions) < len(bc_version_to_text): # Case 2: Only part of BC versions contains breaking text. return self._handle_many_bc_versions_some_with_text(release_notes_dir, text_of_bc_versions, bc_without_text) else: # Case 3: All BC versions contains text. # Important: Currently, implementation of aggregating BCs was decided to concat between them # In the future this might be needed to re-thought. return '\n'.join(bc_version_to_text.values()) # type: ignore[arg-type] def _handle_many_bc_versions_some_with_text(self, release_notes_dir: str, text_of_bc_versions: List[str], bc_versions_without_text: List[str], ) -> str: """ Calculates text for changelog entry where some BC versions contain text and some don't. Important: Currently, implementation of aggregating BCs was decided to concat between them (and if BC version does not have a BC text - concat the whole RN). In the future this might be needed to re-thought. Args: release_notes_dir (str): RN dir path. text_of_bc_versions ([List[str]): List of text of BC versions with text. bc_versions_without_text ([List[str]): List of BC versions without text. Returns: (str): Text for BC entry. """ bc_with_text_str = '\n'.join(text_of_bc_versions) rn_file_names_without_text = [f'''{bc_version.replace('.', '_')}.md''' for bc_version in bc_versions_without_text] other_rn_text: str = self._get_release_notes_concat_str(release_notes_dir, rn_file_names_without_text) if not other_rn_text: logging.error('No RN text, although text was expected to be found for versions' f' {rn_file_names_without_text}.') return f'{bc_with_text_str}{other_rn_text}' @staticmethod def _get_release_notes_concat_str(release_notes_dir: str, rn_file_names: List[str]) -> str: """ Concat all RN data found in given `rn_file_names`. Args: release_notes_dir (str): RN dir path. rn_file_names (List[str]): List of all RN files to concat their data. Returns: (str): Concat RN data """ concat_str: str = '' for rn_file_name in rn_file_names: rn_file_path = os.path.join(release_notes_dir, rn_file_name) with open(rn_file_path, 'r') as f: # Will make the concat string start with new line on purpose. concat_str = f'{concat_str}\n{f.read()}' return concat_str @staticmethod def _split_bc_versions_with_and_without_text(bc_versions: Dict[str, Optional[str]]) -> Tuple[List[str], List[str]]: """ Splits BCs to tuple of BCs text of BCs containing text, and BCs versions that do not contain BC text. Args: bc_versions (Dict[str, Optional[str]): BC versions mapped to text if exists. Returns: (Tuple[List[str], List[str]]): (text of bc versions with text, bc_versions_without_text). """ text_of_bc_versions_with_tests: List[str] = [] bc_versions_without_text: List[str] = [] for bc_version, bc_text in bc_versions.items(): if bc_text: text_of_bc_versions_with_tests.append(bc_text) else: bc_versions_without_text.append(bc_version) return text_of_bc_versions_with_tests, bc_versions_without_text @staticmethod def _breaking_changes_versions_to_text(release_notes_dir: str) -> Dict[str, Optional[str]]: """ Calculates every BC version in given RN dir and maps it to text if exists. Currently, text from a BC version is calculated in the following way: - If RN has `breakingChangesNotes` entry in its corresponding config file, then use the value of that field as the text of the BC to be represented. - Else, use the whole RN text as BC text. Args: release_notes_dir (str): RN dir path. Returns: (Dict[str, Optional[str]]): {dotted_version, text}. """ bc_version_to_text: Dict[str, Optional[str]] = dict() # Get all config files in RN dir rn_config_file_names = filter_dir_files_by_extension(release_notes_dir, '.json') for file_name in rn_config_file_names: file_data: Dict = load_json(os.path.join(release_notes_dir, file_name)) # Check if version is BC if file_data.get('breakingChanges'): # Processing name for easier calculations later on processed_name: str = underscore_file_name_to_dotted_version(file_name) bc_version_to_text[processed_name] = file_data.get('breakingChangesNotes') return bc_version_to_text @staticmethod def _changelog_entry_bc_versions(predecessor_version: Version, rn_version: Version, breaking_changes_versions: List[Version], bc_version_to_text: Dict[str, Optional[str]]) -> Dict[str, Optional[str]]: """ Gets all BC versions of given changelog entry, every BC s.t predecessor_version < BC version <= rn_version. Args: predecessor_version (Version): Predecessor version in numeric version order. rn_version (Version): RN version of current processed changelog entry. breaking_changes_versions (List[Version]): List of BC versions. bc_version_to_text (Dict[str, Optional[str]): List of all BC to text in the given RN dir. Returns: Dict[str, Optional[str]]: Partial list of `bc_version_to_text`, containing only relevant versions between given versions. """ return {str(bc_ver): bc_version_to_text.get(str(bc_ver)) for bc_ver in breaking_changes_versions if predecessor_version < bc_ver <= rn_version} # HELPER FUNCTIONS def get_upload_data(packs_results_file_path: str, stage: str) -> Tuple[dict, dict, dict, dict]: """ Loads the packs_results.json file to get the successful and failed packs together with uploaded images dicts Args: packs_results_file_path (str): The path to the file stage (str): can be BucketUploadFlow.PREPARE_CONTENT_FOR_TESTING or BucketUploadFlow.UPLOAD_PACKS_TO_MARKETPLACE_STORAGE Returns: dict: The successful packs dict dict: The failed packs dict dict : The successful private packs dict dict: The images data dict """ if os.path.exists(packs_results_file_path): packs_results_file = load_json(packs_results_file_path) stage_data: dict = packs_results_file.get(stage, {}) successful_packs_dict = stage_data.get(BucketUploadFlow.SUCCESSFUL_PACKS, {}) failed_packs_dict = stage_data.get(BucketUploadFlow.FAILED_PACKS, {}) successful_private_packs_dict = stage_data.get(BucketUploadFlow.SUCCESSFUL_PRIVATE_PACKS, {}) images_data_dict = stage_data.get(BucketUploadFlow.IMAGES, {}) return successful_packs_dict, failed_packs_dict, successful_private_packs_dict, images_data_dict return {}, {}, {}, {} def store_successful_and_failed_packs_in_ci_artifacts(packs_results_file_path: str, stage: str, successful_packs: list, failed_packs: list, updated_private_packs: list, images_data: dict = None): """ Write the successful and failed packs to the correct section in the packs_results.json file Args: packs_results_file_path (str): The path to the pack_results.json file stage (str): can be BucketUploadFlow.PREPARE_CONTENT_FOR_TESTING or BucketUploadFlow.UPLOAD_PACKS_TO_MARKETPLACE_STORAGE successful_packs (list): The list of all successful packs failed_packs (list): The list of all failed packs updated_private_packs (list) : The list of all private packs that were updated images_data (dict): A dict containing all images that were uploaded for each pack """ packs_results = load_json(packs_results_file_path) packs_results[stage] = dict() if failed_packs: failed_packs_dict = { BucketUploadFlow.FAILED_PACKS: { pack.name: { BucketUploadFlow.STATUS: pack.status, BucketUploadFlow.AGGREGATED: pack.aggregation_str if pack.aggregated and pack.aggregation_str else "False" } for pack in failed_packs } } packs_results[stage].update(failed_packs_dict) logging.debug(f"Failed packs {failed_packs_dict}") if successful_packs: successful_packs_dict = { BucketUploadFlow.SUCCESSFUL_PACKS: { pack.name: { BucketUploadFlow.STATUS: pack.status, BucketUploadFlow.AGGREGATED: pack.aggregation_str if pack.aggregated and pack.aggregation_str else "False", BucketUploadFlow.LATEST_VERSION: pack.latest_version } for pack in successful_packs } } packs_results[stage].update(successful_packs_dict) logging.debug(f"Successful packs {successful_packs_dict}") if updated_private_packs: successful_private_packs_dict: dict = { BucketUploadFlow.SUCCESSFUL_PRIVATE_PACKS: {pack_name: {} for pack_name in updated_private_packs} } packs_results[stage].update(successful_private_packs_dict) logging.debug(f"Successful private packs {successful_private_packs_dict}") if images_data: packs_results[stage].update({BucketUploadFlow.IMAGES: images_data}) logging.debug(f"Images data {images_data}") if packs_results: json_write(packs_results_file_path, packs_results) def load_json(file_path: str) -> dict: """ Reads and loads json file. Args: file_path (str): full path to json file. Returns: dict: loaded json file. """ try: if file_path and os.path.exists(file_path): with open(file_path, 'r') as json_file: result = json.load(json_file) else: result = {} return result except json.decoder.JSONDecodeError: return {} def json_write(file_path: str, data: Union[list, dict]): """ Writes given data to a json file Args: file_path: The file path data: The data to write """ with open(file_path, "w") as f: f.write(json.dumps(data, indent=4)) def init_storage_client(service_account=None): """Initialize google cloud storage client. In case of local dev usage the client will be initialized with user default credentials. Otherwise, client will be initialized from service account json that is stored in CircleCI. Args: service_account (str): full path to service account json. Return: storage.Client: initialized google cloud storage client. """ if service_account: storage_client = storage.Client.from_service_account_json(service_account) logging.info("Created gcp service account") return storage_client else: # in case of local dev use, ignored the warning of non use of service account. warnings.filterwarnings("ignore", message=google.auth._default._CLOUD_SDK_CREDENTIALS_WARNING) credentials, project = google.auth.default() storage_client = storage.Client(credentials=credentials, project=project) logging.info("Created gcp private account") return storage_client def input_to_list(input_data, capitalize_input=False): """ Helper function for handling input list or str from the user. Args: input_data (list or str): input from the user to handle. capitalize_input (boo): whether to capitalize the input list data or not. Returns: list: returns the original list or list that was split by comma. """ input_data = input_data if input_data else [] input_data = input_data if isinstance(input_data, list) else [s for s in input_data.split(',') if s] if capitalize_input: return [" ".join([w.title() if w.islower() else w for w in i.split()]) for i in input_data] else: return input_data def get_valid_bool(bool_input): """ Converts and returns valid bool. Returns: bool: converted bool input. """ return bool(strtobool(bool_input)) if isinstance(bool_input, str) else bool_input def convert_price(pack_id, price_value_input=None): """ Converts to integer value price input. In case no price input provided, return zero as price. Args: pack_id (str): pack unique identifier. price_value_input (str): price string to convert. Returns: int: converted to int pack price. """ try: if not price_value_input: return 0 # in case no price was supported, return 0 else: return int(price_value_input) # otherwise convert to int and return result except Exception: logging.exception(f"{pack_id} pack price is not valid. The price was set to 0.") return 0 def get_updated_server_version(current_string_version, compared_content_item, pack_name): """ Compares two semantic server versions and returns the higher version between them. Args: current_string_version (str): current string version. compared_content_item (dict): compared content item entity. pack_name (str): the pack name (id). Returns: str: latest version between compared versions. """ lower_version_result = current_string_version try: compared_string_version = compared_content_item.get('fromversion') or compared_content_item.get( 'fromVersion') or "99.99.99" current_version, compared_version = Version(current_string_version), Version(compared_string_version) if current_version > compared_version: lower_version_result = compared_string_version except Exception: content_item_name = compared_content_item.get('name') or compared_content_item.get( 'display') or compared_content_item.get('id') or compared_content_item.get('details', '') logging.exception(f"{pack_name} failed in version comparison of content item {content_item_name}.") finally: return lower_version_result def get_content_git_client(content_repo_path: str): """ Initializes content repo client. Args: content_repo_path (str): content repo full path Returns: git.repo.base.Repo: content repo object. """ return git.Repo(content_repo_path) def get_recent_commits_data(content_repo: Any, index_folder_path: str, is_bucket_upload_flow: bool, is_private_build: bool = False, circle_branch: str = "master"): """ Returns recent commits hashes (of head and remote master) Args: content_repo (git.repo.base.Repo): content repo object. index_folder_path (str): the path to the local index folder is_bucket_upload_flow (bool): indicates whether its a run of bucket upload flow or regular build is_private_build (bool): indicates whether its a run of private build or not circle_branch (str): CircleCi branch of current build Returns: str: last commit hash of head. str: previous commit depending on the flow the script is running """ return content_repo.head.commit.hexsha, get_previous_commit(content_repo, index_folder_path, is_bucket_upload_flow, is_private_build, circle_branch) def get_previous_commit(content_repo, index_folder_path, is_bucket_upload_flow, is_private_build, circle_branch): """ If running in bucket upload workflow we want to get the commit in the index which is the index We've last uploaded to production bucket. Otherwise, we are in a commit workflow and the diff should be from the head of origin/master Args: content_repo (git.repo.base.Repo): content repo object. index_folder_path (str): the path to the local index folder is_bucket_upload_flow (bool): indicates whether its a run of bucket upload flow or regular build is_private_build (bool): indicates whether its a run of private build or not circle_branch (str): CircleCi branch of current build Returns: str: previous commit depending on the flow the script is running """ if is_bucket_upload_flow: return get_last_upload_commit_hash(content_repo, index_folder_path) elif is_private_build: previous_master_head_commit = content_repo.commit('origin/master~1').hexsha logging.info(f"Using origin/master HEAD~1 commit hash {previous_master_head_commit} to diff with.") return previous_master_head_commit else: if circle_branch == 'master': head_str = "HEAD~1" # if circle branch is master than current commit is origin/master HEAD, so we need to diff with HEAD~1 previous_master_head_commit = content_repo.commit('origin/master~1').hexsha else: head_str = "HEAD" # else we are on a regular branch and the diff should be done with origin/master HEAD previous_master_head_commit = content_repo.commit('origin/master').hexsha logging.info(f"Using origin/master {head_str} commit hash {previous_master_head_commit} to diff with.") return previous_master_head_commit def get_last_upload_commit_hash(content_repo, index_folder_path): """ Returns the last origin/master commit hash that was uploaded to the bucket Args: content_repo (git.repo.base.Repo): content repo object. index_folder_path: The path to the index folder Returns: The commit hash """ inner_index_json_path = os.path.join(index_folder_path, f'{GCPConfig.INDEX_NAME}.json') if not os.path.exists(inner_index_json_path): logging.critical(f"{GCPConfig.INDEX_NAME}.json not found in {GCPConfig.INDEX_NAME} folder") sys.exit(1) else: inner_index_json_file = load_json(inner_index_json_path) if 'commit' in inner_index_json_file: last_upload_commit_hash = inner_index_json_file['commit'] logging.info(f"Retrieved the last commit that was uploaded to production: {last_upload_commit_hash}") else: logging.critical(f"No commit field in {GCPConfig.INDEX_NAME}.json, content: {str(inner_index_json_file)}") sys.exit(1) try: last_upload_commit = content_repo.commit(last_upload_commit_hash).hexsha logging.info(f"Using commit hash {last_upload_commit} from index.json to diff with.") return last_upload_commit except Exception as e: logging.critical(f'Commit {last_upload_commit_hash} in {GCPConfig.INDEX_NAME}.json does not exist in content ' f'repo. Additional info:\n {e}') sys.exit(1) def is_ignored_pack_file(modified_file_path_parts): """ Indicates whether a pack file needs to be ignored or not. Args: modified_file_path_parts: The modified file parts, e.g. if file path is "a/b/c" then the parts list is ["a", "b", "c"] Returns: (bool): True if the file should be ignored, False otherwise """ for file_suffix in PackIgnored.ROOT_FILES: if file_suffix in modified_file_path_parts: return True for pack_folder, file_suffixes in PackIgnored.NESTED_FILES.items(): if pack_folder in modified_file_path_parts: if not file_suffixes: # Ignore all pack folder files return True for file_suffix in file_suffixes: if file_suffix in modified_file_path_parts[-1]: return True for pack_folder in PackIgnored.NESTED_DIRS: if pack_folder in modified_file_path_parts: pack_folder_path = os.sep.join(modified_file_path_parts[:modified_file_path_parts.index(pack_folder) + 1]) file_path = os.sep.join(modified_file_path_parts) for folder_path in [f for f in glob.glob(os.path.join(pack_folder_path, '*/*')) if os.path.isdir(f)]: # Checking for all 2nd level directories. e.g. test_data directory if file_path.startswith(folder_path): return True return False def filter_dir_files_by_extension(release_notes_dir: str, extension: str) -> List[str]: """ Receives path to RN dir, filters only files in RN dir corresponding to the extension. Needed because RN directory will be extended to contain JSON files for configurations, see 'release_notes_bc_calculator.py' Args: release_notes_dir (str): Path to RN dir extension (str): Extension to filter by. Returns: (List[str]): List of all of the files in directory corresponding to the extension. """ return [file_name for file_name in os.listdir(release_notes_dir) if file_name.endswith(extension)] def is_the_only_rn_in_block(release_notes_dir: str, version: str, changelog: dict): """ Check if the given version is a key of an aggregated changelog block, as in its value in the changelog doesn't contains other release notes that have been aggregated in previous uploads. If that is the case, the adjacent previous release note in the changelog will be equal to the one in the release notes directory, and false otherwise (meaning there are versions in the release notes directory that are missing in the changelog, therefore they have been aggregated) and this function asserts that. Note: The comparison is done against the release notes directory to avoid cases where there are missing versions in the changelog due to inconsistent versions numbering, such as major version bumps. (For example, if the versions 1.2.7 and 1.3.0 are two consecutive keys in the changelog, we need to determine if 1.3.0 has aggregated the versions 1.2.8-1.3.0, OR 1.3.0 is the consecutive version right after 1.2.7 but is a major bump. in order to check that, we check it against the files in the release notes directory.) Args: release_notes_dir: the path to the release notes dir. version (str): the wanted version. changelog (dict): the changelog from the production bucket. Returns: True if this version's value in the changelog is not an aggregated release notes block. False otherwise. """ if not changelog.get(version): return False all_rn_versions = [] lowest_version = [Version('1.0.0')] for filename in filter_dir_files_by_extension(release_notes_dir, '.md'): current_version = underscore_file_name_to_dotted_version(filename) all_rn_versions.append(Version(current_version)) lower_versions_all_versions = [item for item in all_rn_versions if item < Version(version)] + lowest_version lower_versions_in_changelog = [Version(item) for item in changelog.keys() if Version(item) < Version(version)] + lowest_version return max(lower_versions_all_versions) == max(lower_versions_in_changelog) def underscore_file_name_to_dotted_version(file_name: str) -> str: """ Receives file name with expected format of x_x_x<extension>, and transforms it to dotted string. Examples - underscore_file_name_to_dotted_version(1_2_3.md) --> 1.2.3 - underscore_file_name_to_dotted_version(1_4_2.json) --> 1.4.2 Args: file_name (str): File name. Returns: (str): Dotted version of file name """ return os.path.splitext(file_name)[0].replace('_', '.') def get_last_commit_from_index(service_account): """ Downloading index.json from GCP and extract last upload commit. Args: service_account: service account to connect to GCP Returns: last upload commit. """ storage_client = init_storage_client(service_account) storage_bucket = storage_client.bucket(GCPConfig.PRODUCTION_BUCKET) index_storage_path = os.path.join('content/packs/', f"{GCPConfig.INDEX_NAME}.json") index_blob = storage_bucket.blob(index_storage_path) index_string = index_blob.download_as_string() index_json = json.loads(index_string) return index_json.get('commit')
import base64 import fnmatch import glob import json import os import re import shutil import stat import subprocess import urllib.parse import warnings from datetime import datetime, timedelta from distutils.util import strtobool from packaging.version import Version from pathlib import Path from typing import Tuple, Any, Union, List, Dict, Optional from zipfile import ZipFile, ZIP_DEFLATED import git import google.auth import sys import yaml from google.cloud import storage import Tests.Marketplace.marketplace_statistics as mp_statistics from Tests.Marketplace.marketplace_constants import PackFolders, Metadata, GCPConfig, BucketUploadFlow, PACKS_FOLDER, \ PackTags, PackIgnored, Changelog, BASE_PACK_DEPENDENCY_DICT, SIEM_RULES_OBJECTS, PackStatus from Utils.release_notes_generator import aggregate_release_notes_for_marketplace from Tests.scripts.utils import logging_wrapper as logging class Pack(object): """ Class that manipulates and manages the upload of pack's artifact and metadata to cloud storage. Args: pack_name (str): Pack root folder name. pack_path (str): Full path to pack folder. Attributes: PACK_INITIAL_VERSION (str): pack initial version that will be used as default. CHANGELOG_JSON (str): changelog json full name, may be changed in the future. README (str): pack's readme file name. METADATA (str): pack's metadata file name, the one that will be deployed to cloud storage. USER_METADATA (str); user metadata file name, the one that located in content repo. EXCLUDE_DIRECTORIES (list): list of directories to excluded before uploading pack zip to storage. AUTHOR_IMAGE_NAME (str): author image file name. RELEASE_NOTES (str): release notes folder name. """ PACK_INITIAL_VERSION = "1.0.0" CHANGELOG_JSON = "changelog.json" README = "README.md" USER_METADATA = "pack_metadata.json" METADATA = "metadata.json" AUTHOR_IMAGE_NAME = "Author_image.png" EXCLUDE_DIRECTORIES = [PackFolders.TEST_PLAYBOOKS.value] RELEASE_NOTES = "ReleaseNotes" def __init__(self, pack_name, pack_path): self._pack_name = pack_name self._pack_path = pack_path self._zip_path = None # zip_path will be updated as part of zip_pack self._marketplaces = [] # initialized in load_user_metadata function self._status = None self._public_storage_path = "" self._remove_files_list = [] # tracking temporary files, in order to delete in later step self._server_min_version = "99.99.99" # initialized min version self._latest_version = None # pack latest version found in changelog self._support_type = None # initialized in load_user_metadata function self._current_version = None # initialized in load_user_metadata function self._hidden = False # initialized in load_user_metadata function self._description = None # initialized in load_user_metadata function self._display_name = None # initialized in load_user_metadata function self._user_metadata = {} # initialized in load_user_metadata function self._eula_link = None # initialized in load_user_metadata function self._is_feed = False # a flag that specifies if pack is a feed pack self._downloads_count = 0 # number of pack downloads self._bucket_url = None # URL of where the pack was uploaded. self._aggregated = False # weather the pack's rn was aggregated or not. self._aggregation_str = "" # the aggregation string msg when the pack versions are aggregated self._create_date = None # initialized in enhance_pack_attributes function self._update_date = None # initialized in enhance_pack_attributes function self._uploaded_author_image = False # whether the pack author image was uploaded or not self._uploaded_integration_images = [] # the list of all integration images that were uploaded for the pack self._support_details = None # initialized in enhance_pack_attributes function self._author = None # initialized in enhance_pack_attributes function self._certification = None # initialized in enhance_pack_attributes function self._legacy = None # initialized in enhance_pack_attributes function self._author_image = None # initialized in upload_author_image function self._displayed_integration_images = [] # initialized in upload_integration_images function self._price = 0 # initialized in enhance_pack_attributes function self._is_private_pack = False # initialized in enhance_pack_attributes function self._is_premium = False # initialized in enhance_pack_attributes function self._vendor_id = None # initialized in enhance_pack_attributes function self._partner_id = None # initialized in enhance_pack_attributes function self._partner_name = None # initialized in enhance_pack_attributes function self._content_commit_hash = None # initialized in enhance_pack_attributes function self._preview_only = None # initialized in enhance_pack_attributes function self._tags = None # initialized in enhance_pack_attributes function self._categories = None # initialized in enhance_pack_attributes function self._content_items = None # initialized in collect_content_items function self._search_rank = None # initialized in enhance_pack_attributes function self._related_integration_images = None # initialized in enhance_pack_attributes function self._use_cases = None # initialized in enhance_pack_attributes function self._keywords = None # initialized in enhance_pack_attributes function self._pack_statistics_handler = None # initialized in enhance_pack_attributes function self._contains_transformer = False # initialized in collect_content_items function self._contains_filter = False # initialized in collect_content_items function self._is_missing_dependencies = False # initialized in _load_pack_dependencies function self._is_modified = None # initialized in detect_modified function self._is_siem = False # initialized in collect_content_items function # Dependencies attributes - these contain only packs that are a part of this marketplace self._first_level_dependencies = {} # initialized in set_pack_dependencies function self._all_levels_dependencies = [] # initialized in set_pack_dependencies function self._displayed_images_dependent_on_packs = [] # initialized in set_pack_dependencies function self._parsed_dependencies = None # initialized in enhance_pack_attributes function @property def name(self): """ str: pack root folder name. """ return self._pack_name @property def path(self): """ str: pack folder full path. """ return self._pack_path @property def latest_version(self): """ str: pack latest version from sorted keys of changelog.json file. """ if not self._latest_version: self._latest_version = self._get_latest_version() return self._latest_version else: return self._latest_version @latest_version.setter def latest_version(self, latest_version): self._latest_version = latest_version @property def status(self): """ str: current status of the packs. """ return self._status @property def is_feed(self): """ bool: whether the pack is a feed pack """ return self._is_feed @is_feed.setter def is_feed(self, is_feed): """ setter of is_feed """ self._is_feed = is_feed @property def is_siem(self): """ bool: whether the pack is a siem pack """ return self._is_siem @is_siem.setter def is_siem(self, is_siem): """ setter of is_siem """ self._is_siem = is_siem @status.setter # type: ignore[attr-defined,no-redef] def status(self, status_value): """ setter of pack current status. """ self._status = status_value @property def public_storage_path(self): """ str: public gcs path of uploaded pack. """ return self._public_storage_path @public_storage_path.setter def public_storage_path(self, path_value): """ setter of public gcs path of uploaded pack. """ self._public_storage_path = path_value @property def support_type(self): """ str: support type of the pack. """ return self._support_type @support_type.setter def support_type(self, support_value): """ setter of support type of the pack. """ self._support_type = support_value @property def current_version(self): """ str: current version of the pack (different from latest_version). """ return self._current_version @current_version.setter def current_version(self, current_version_value): """ setter of current version of the pack. """ self._current_version = current_version_value @property def hidden(self): """ bool: internal content field for preventing pack from being displayed. """ return self._hidden @hidden.setter def hidden(self, hidden_value): """ setter of hidden property of the pack. """ self._hidden = hidden_value @property def description(self): """ str: Description of the pack (found in pack_metadata.json). """ return self._description @description.setter def description(self, description_value): """ setter of description property of the pack. """ self._description = description_value @property def display_name(self): """ str: Display name of the pack (found in pack_metadata.json). """ return self._display_name @property def user_metadata(self): """ dict: the pack_metadata. """ return self._user_metadata @display_name.setter # type: ignore[attr-defined,no-redef] def display_name(self, display_name_value): """ setter of display name property of the pack. """ self._display_name = display_name_value @property def server_min_version(self): """ str: server min version according to collected items. """ if not self._server_min_version or self._server_min_version == "99.99.99": return Metadata.SERVER_DEFAULT_MIN_VERSION else: return self._server_min_version @property def downloads_count(self): """ str: packs downloads count. """ return self._downloads_count @downloads_count.setter def downloads_count(self, download_count_value): """ setter of downloads count property of the pack. """ self._downloads_count = download_count_value @property def bucket_url(self): """ str: pack bucket_url. """ return self._bucket_url @bucket_url.setter def bucket_url(self, bucket_url): """ str: pack bucket_url. """ self._bucket_url = bucket_url @property def aggregated(self): """ str: pack aggregated release notes or not. """ return self._aggregated @property def aggregation_str(self): """ str: pack aggregated release notes or not. """ return self._aggregation_str @property def create_date(self): """ str: pack create date. """ return self._create_date @create_date.setter def create_date(self, value): self._create_date = value @property def update_date(self): """ str: pack update date. """ return self._update_date @update_date.setter def update_date(self, value): self._update_date = value @property def uploaded_author_image(self): """ bool: whether the pack author image was uploaded or not. """ return self._uploaded_author_image @uploaded_author_image.setter def uploaded_author_image(self, uploaded_author_image): """ bool: whether the pack author image was uploaded or not. """ self._uploaded_author_image = uploaded_author_image @property def uploaded_integration_images(self): """ str: the list of uploaded integration images """ return self._uploaded_integration_images @property def is_missing_dependencies(self): return self._is_missing_dependencies @property def zip_path(self): return self._zip_path @property def is_modified(self): return self._is_modified @property def marketplaces(self): return self._marketplaces @property def all_levels_dependencies(self): return self._all_levels_dependencies def _get_latest_version(self): """ Return latest semantic version of the pack. In case that changelog.json file was not found, default value of 1.0.0 will be returned. Otherwise, keys of semantic pack versions will be collected and sorted in descending and return latest version. For additional information regarding changelog.json format go to issue #19786 Returns: str: Pack latest version. """ changelog_path = os.path.join(self._pack_path, Pack.CHANGELOG_JSON) if not os.path.exists(changelog_path): return self._current_version with open(changelog_path, "r") as changelog_file: changelog = json.load(changelog_file) pack_versions = [Version(v) for v in changelog.keys()] pack_versions.sort(reverse=True) return str(pack_versions[0]) @staticmethod def organize_integration_images(pack_integration_images: list, pack_dependencies_integration_images_dict: dict, pack_dependencies_by_download_count: list): """ By Issue #32038 1. Sort pack integration images by alphabetical order 2. Sort pack dependencies by download count Pack integration images are shown before pack dependencies integration images Args: pack_integration_images (list): list of pack integration images pack_dependencies_integration_images_dict: a mapping of pack dependency name to its integration images pack_dependencies_by_download_count: a list of pack dependencies sorted by download count Returns: list: list of sorted integration images """ def sort_by_name(integration_image: dict): return integration_image.get('name', '') # sort packs integration images pack_integration_images = sorted(pack_integration_images, key=sort_by_name) # sort pack dependencies integration images all_dep_int_imgs = pack_integration_images for dep_pack_name in pack_dependencies_by_download_count: if dep_pack_name in pack_dependencies_integration_images_dict: logging.info(f'Adding {dep_pack_name} to deps int imgs') dep_int_imgs = sorted(pack_dependencies_integration_images_dict[dep_pack_name], key=sort_by_name) for dep_int_img in dep_int_imgs: if dep_int_img not in all_dep_int_imgs: # avoid duplicates all_dep_int_imgs.append(dep_int_img) return all_dep_int_imgs @staticmethod def _get_all_pack_images(pack_integration_images: List, display_dependencies_images: List, dependencies_metadata: Dict, pack_dependencies_by_download_count): """ Returns data of uploaded pack integration images and it's path in gcs. Pack dependencies integration images are added to that result as well. Args: pack_integration_images (list): list of uploaded to gcs integration images and it paths in gcs. display_dependencies_images (list): list of pack names of additional dependencies images to display. dependencies_metadata (dict): all level dependencies data. pack_dependencies_by_download_count (list): list of pack names that are dependencies of the given pack sorted by download count. Returns: list: collection of integration display name and it's path in gcs. """ dependencies_integration_images_dict: dict = {} additional_dependencies_data = {k: v for k, v in dependencies_metadata.items() if k in display_dependencies_images} for dependency_data in additional_dependencies_data.values(): for dep_int_img in dependency_data.get('integrations', []): dep_int_img_gcs_path = dep_int_img.get('imagePath', '') # image public url dep_int_img['name'] = Pack.remove_contrib_suffix_from_name(dep_int_img.get('name', '')) dep_pack_name = os.path.basename(os.path.dirname(dep_int_img_gcs_path)) if dep_pack_name not in display_dependencies_images: continue # skip if integration image is not part of displayed images of the given pack if dep_int_img not in pack_integration_images: # avoid duplicates in list if dep_pack_name in dependencies_integration_images_dict: dependencies_integration_images_dict[dep_pack_name].append(dep_int_img) else: dependencies_integration_images_dict[dep_pack_name] = [dep_int_img] return Pack.organize_integration_images( pack_integration_images, dependencies_integration_images_dict, pack_dependencies_by_download_count ) def add_pack_type_tags(self, yaml_content, yaml_type): """ Checks if an pack objects is siem or feed object. If so, updates Pack._is_feed or Pack._is_siem Args: yaml_content: The yaml content extracted by yaml.safe_load(). yaml_type: The type of object to check. Returns: Doesn't return """ if yaml_type == 'Integration': if yaml_content.get('script', {}).get('feed', False) is True: self._is_feed = True if yaml_content.get('isfetchevents', False) is True: self._is_siem = True if yaml_type == 'Playbook': if yaml_content.get('name').startswith('TIM '): self._is_feed = True if yaml_type in SIEM_RULES_OBJECTS: self._is_siem = True @staticmethod def _clean_release_notes(release_notes_lines): return re.sub(r'<\!--.*?-->', '', release_notes_lines, flags=re.DOTALL) @staticmethod def _parse_pack_dependencies(first_level_dependencies, dependencies_metadata_dict): """ Parses user defined dependencies and returns dictionary with relevant data about each dependency pack. Args: first_level_dependencies (dict): first lever dependencies that were retrieved from user pack_metadata.json file. dependencies_metadata_dict (dict): dict of pack dependencies data. Returns: dict: parsed dictionary with pack dependency data. """ parsed_result = {} for dependency_id, dependency_data in dependencies_metadata_dict.items(): parsed_result[dependency_id] = { "mandatory": first_level_dependencies.get(dependency_id, {}).get('mandatory', True), "minVersion": dependency_data.get(Metadata.CURRENT_VERSION, Pack.PACK_INITIAL_VERSION), "author": dependency_data.get('author', ''), "name": dependency_data.get('name') if dependency_data.get('name') else dependency_id, "certification": dependency_data.get('certification', 'certified') } return parsed_result @staticmethod def _create_support_section(support_type, support_url=None, support_email=None): """ Creates support dictionary that is part of metadata. In case of support type xsoar, adds default support url. If support is xsoar and support url is defined and doesn't match xsoar default url, warning is raised. Args: support_type (str): support type of pack. support_url (str): support full url. support_email (str): support email address. Returns: dict: supported data dictionary. """ support_details = {} if support_url: # set support url from user input support_details['url'] = support_url elif support_type == Metadata.XSOAR_SUPPORT: # in case support type is xsoar, set default xsoar support url support_details['url'] = Metadata.XSOAR_SUPPORT_URL # add support email if defined if support_email: support_details['email'] = support_email return support_details @staticmethod def _get_author(support_type, author=None): """ Returns pack author. In case support type is xsoar, more additional validation are applied. Args: support_type (str): support type of pack. author (str): author of the pack. Returns: str: returns author from the input. """ if support_type == Metadata.XSOAR_SUPPORT and not author: return Metadata.XSOAR_AUTHOR # returned xsoar default author elif support_type == Metadata.XSOAR_SUPPORT and author != Metadata.XSOAR_AUTHOR: logging.warning(f"{author} author doest not match {Metadata.XSOAR_AUTHOR} default value") return author else: return author @staticmethod def _get_certification(support_type, certification=None): """ Returns pack certification. In case support type is xsoar or partner, CERTIFIED is returned. In case support is not xsoar or partner but pack_metadata has certification field, certification value will be taken from pack_metadata defined value. Otherwise empty certification value (empty string) will be returned Args: support_type (str): support type of pack. certification (str): certification value from pack_metadata, if exists. Returns: str: certification value """ if support_type in [Metadata.XSOAR_SUPPORT, Metadata.PARTNER_SUPPORT]: return Metadata.CERTIFIED elif certification: return certification else: return "" def _get_tags_from_landing_page(self, landing_page_sections: dict) -> set: """ Build the pack's tag list according to the user metadata and the landingPage sections file. Args: landing_page_sections (dict): landingPage sections and the packs in each one of them. Returns: set: Pack's tags. """ tags = set() sections = landing_page_sections.get('sections', []) if landing_page_sections else [] for section in sections: if self._pack_name in landing_page_sections.get(section, []): tags.add(section) return tags def _parse_pack_metadata(self, build_number, commit_hash): """ Parses pack metadata according to issue #19786 and #20091. Part of field may change over the time. Args: build_number (str): circleCI build number. commit_hash (str): current commit hash. Returns: dict: parsed pack metadata. """ pack_metadata = { Metadata.NAME: self._display_name or self._pack_name, Metadata.ID: self._pack_name, Metadata.DESCRIPTION: self._description or self._pack_name, Metadata.CREATED: self._create_date, Metadata.UPDATED: self._update_date, Metadata.LEGACY: self._legacy, Metadata.SUPPORT: self._support_type, Metadata.SUPPORT_DETAILS: self._support_details, Metadata.EULA_LINK: self._eula_link, Metadata.AUTHOR: self._author, Metadata.AUTHOR_IMAGE: self._author_image, Metadata.CERTIFICATION: self._certification, Metadata.PRICE: self._price, Metadata.SERVER_MIN_VERSION: self.user_metadata.get(Metadata.SERVER_MIN_VERSION) or self.server_min_version, Metadata.CURRENT_VERSION: self.user_metadata.get(Metadata.CURRENT_VERSION, ''), Metadata.VERSION_INFO: build_number, Metadata.COMMIT: commit_hash, Metadata.DOWNLOADS: self._downloads_count, Metadata.TAGS: list(self._tags or []), Metadata.CATEGORIES: self._categories, Metadata.CONTENT_ITEMS: self._content_items, Metadata.SEARCH_RANK: self._search_rank, Metadata.INTEGRATIONS: self._related_integration_images, Metadata.USE_CASES: self._use_cases, Metadata.KEY_WORDS: self._keywords, Metadata.DEPENDENCIES: self._parsed_dependencies, Metadata.VIDEOS: self.user_metadata.get(Metadata.VIDEOS) or [], } if self._is_private_pack: pack_metadata.update({ Metadata.PREMIUM: self._is_premium, Metadata.VENDOR_ID: self._vendor_id, Metadata.PARTNER_ID: self._partner_id, Metadata.PARTNER_NAME: self._partner_name, Metadata.CONTENT_COMMIT_HASH: self._content_commit_hash, Metadata.PREVIEW_ONLY: self._preview_only }) return pack_metadata def _load_pack_dependencies_metadata(self, index_folder_path, packs_dict): """ Loads dependencies metadata and returns mapping of pack id and it's loaded data. There are 2 cases: Case 1: The dependency is present in the index.zip. In this case, we add it to the dependencies results. Case 2: The dependency is missing from the index.zip since it is a new pack. In this case, handle missing dependency - This means we mark this pack as 'missing dependency', and once the new index.zip is created, and therefore it contains the new pack, we call this function again, and hitting case 1. Args: index_folder_path (str): full path to download index folder. packs_dict (dict): dict of all packs relevant for current marketplace, as {pack_id: pack_object}. Returns: dict: pack id as key and loaded metadata of packs as value. bool: True if the pack is missing dependencies, False otherwise. """ dependencies_metadata_result = {} dependencies_ids = {dep for dep in self._first_level_dependencies} dependencies_ids.update(self._displayed_images_dependent_on_packs) for dependency_pack_id in dependencies_ids: dependency_metadata_path = os.path.join(index_folder_path, dependency_pack_id, Pack.METADATA) if os.path.exists(dependency_metadata_path): # Case 1: the dependency is found in the index.zip with open(dependency_metadata_path, 'r') as metadata_file: dependency_metadata = json.load(metadata_file) dependencies_metadata_result[dependency_pack_id] = dependency_metadata else: # Case 2: the dependency is not in the index since it is a new pack self._is_missing_dependencies = True logging.warning(f"{self._pack_name} pack dependency with id {dependency_pack_id} " f"was not found in index, marking it as missing dependencies - to be resolved in " f"next iteration over packs") return dependencies_metadata_result, self._is_missing_dependencies @staticmethod def _get_updated_changelog_entry(changelog: dict, version: str, release_notes: str = None, version_display_name: str = None, build_number_with_prefix: str = None, released_time: str = None): """ Args: changelog (dict): The changelog from the production bucket. version (str): The version that is the key in the changelog of the entry wished to be updated. release_notes (str): The release notes lines to update the entry with. version_display_name (str): The version display name to update the entry with. build_number_with_prefix(srt): the build number to modify the entry to, including the prefix R (if present). released_time: The released time to update the entry with. """ changelog_entry = changelog.get(version) if not changelog_entry: raise Exception('The given version is not a key in the changelog') version_display_name = \ version_display_name if version_display_name else changelog_entry[Changelog.DISPLAY_NAME].split('-')[0] build_number_with_prefix = \ build_number_with_prefix if build_number_with_prefix else \ changelog_entry[Changelog.DISPLAY_NAME].split('-')[1] changelog_entry[Changelog.RELEASE_NOTES] = release_notes if release_notes else changelog_entry[ Changelog.RELEASE_NOTES] changelog_entry[Changelog.DISPLAY_NAME] = f'{version_display_name} - {build_number_with_prefix}' changelog_entry[Changelog.RELEASED] = released_time if released_time else changelog_entry[Changelog.RELEASED] return changelog_entry def _create_changelog_entry(self, release_notes, version_display_name, build_number, new_version=True, initial_release=False): """ Creates dictionary entry for changelog. Args: release_notes (str): release notes md. version_display_name (str): display name version. build_number (srt): current build number. new_version (bool): whether the entry is new or not. If not new, R letter will be appended to build number. initial_release (bool): whether the entry is an initial release or not. Returns: dict: release notes entry of changelog """ if new_version: return {Changelog.RELEASE_NOTES: release_notes, Changelog.DISPLAY_NAME: f'{version_display_name} - {build_number}', Changelog.RELEASED: datetime.utcnow().strftime(Metadata.DATE_FORMAT)} elif initial_release: return {Changelog.RELEASE_NOTES: release_notes, Changelog.DISPLAY_NAME: f'{version_display_name} - {build_number}', Changelog.RELEASED: self._create_date} elif self.is_modified: return {Changelog.RELEASE_NOTES: release_notes, Changelog.DISPLAY_NAME: f'{version_display_name} - R{build_number}', Changelog.RELEASED: datetime.utcnow().strftime(Metadata.DATE_FORMAT)} return {} def remove_unwanted_files(self, delete_test_playbooks=True): """ Iterates over pack folder and removes hidden files and unwanted folders. Args: delete_test_playbooks (bool): whether to delete test playbooks folder. Returns: bool: whether the operation succeeded. """ task_status = True try: for directory in Pack.EXCLUDE_DIRECTORIES: if delete_test_playbooks and os.path.isdir(f'{self._pack_path}/{directory}'): shutil.rmtree(f'{self._pack_path}/{directory}') logging.info(f"Deleted {directory} directory from {self._pack_name} pack") for root, dirs, files in os.walk(self._pack_path, topdown=True): for pack_file in files: full_file_path = os.path.join(root, pack_file) # removing unwanted files if pack_file.startswith('.') \ or pack_file in [Pack.AUTHOR_IMAGE_NAME, Pack.USER_METADATA] \ or pack_file in self._remove_files_list: os.remove(full_file_path) logging.info(f"Deleted pack {pack_file} file for {self._pack_name} pack") continue except Exception: task_status = False logging.exception(f"Failed to delete ignored files for pack {self._pack_name}") finally: return task_status def sign_pack(self, signature_string=None): """ Signs pack folder and creates signature file. Args: signature_string (str): Base64 encoded string used to sign the pack. Returns: bool: whether the operation succeeded. """ task_status = False try: if signature_string: with open("keyfile", "wb") as keyfile: keyfile.write(signature_string.encode()) arg = f'./signDirectory {self._pack_path} keyfile base64' signing_process = subprocess.Popen(arg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) output, err = signing_process.communicate() if err: logging.error(f"Failed to sign pack for {self._pack_name} - {str(err)}") return logging.info(f"Signed {self._pack_name} pack successfully") else: logging.info(f"No signature provided. Skipped signing {self._pack_name} pack") task_status = True except Exception: logging.exception(f"Failed to sign pack for {self._pack_name}") finally: return task_status @staticmethod def zip_folder_items(source_path, source_name, zip_pack_path): """ Zips the source_path Args: source_path (str): The source path of the folder the items are in. zip_pack_path (str): The path to the zip folder. source_name (str): The name of the source that should be zipped. """ task_status = False try: with ZipFile(zip_pack_path, 'w', ZIP_DEFLATED) as pack_zip: for root, dirs, files in os.walk(source_path, topdown=True): for f in files: full_file_path = os.path.join(root, f) relative_file_path = os.path.relpath(full_file_path, source_path) pack_zip.write(filename=full_file_path, arcname=relative_file_path) task_status = True logging.success(f"Finished zipping {source_name} folder.") except Exception: logging.exception(f"Failed in zipping {source_name} folder") finally: return task_status @staticmethod def encrypt_pack(zip_pack_path, pack_name, encryption_key, extract_destination_path, private_artifacts_dir, secondary_encryption_key): """ decrypt the pack in order to see that the pack was encrypted in the first place. Args: zip_pack_path (str): The path to the encrypted zip pack. pack_name (str): The name of the pack that should be encrypted. encryption_key (str): The key which we can decrypt the pack with. extract_destination_path (str): The path in which the pack resides. private_artifacts_dir (str): The chosen name for the private artifacts directory. secondary_encryption_key (str) : A second key which we can decrypt the pack with. """ try: current_working_dir = os.getcwd() shutil.copy('./encryptor', os.path.join(extract_destination_path, 'encryptor')) os.chmod(os.path.join(extract_destination_path, 'encryptor'), stat.S_IXOTH) os.chdir(extract_destination_path) subprocess.call('chmod +x ./encryptor', shell=True) output_file = zip_pack_path.replace("_not_encrypted.zip", ".zip") full_command = f'./encryptor ./{pack_name}_not_encrypted.zip {output_file} "{encryption_key}"' subprocess.call(full_command, shell=True) secondary_encryption_key_output_file = zip_pack_path.replace("_not_encrypted.zip", ".enc2.zip") full_command_with_secondary_encryption = f'./encryptor ./{pack_name}_not_encrypted.zip ' \ f'{secondary_encryption_key_output_file}' \ f' "{secondary_encryption_key}"' subprocess.call(full_command_with_secondary_encryption, shell=True) new_artefacts = os.path.join(current_working_dir, private_artifacts_dir) if os.path.exists(new_artefacts): shutil.rmtree(new_artefacts) os.mkdir(path=new_artefacts) shutil.copy(zip_pack_path, os.path.join(new_artefacts, f'{pack_name}_not_encrypted.zip')) shutil.copy(output_file, os.path.join(new_artefacts, f'{pack_name}.zip')) shutil.copy(secondary_encryption_key_output_file, os.path.join(new_artefacts, f'{pack_name}.enc2.zip')) os.chdir(current_working_dir) except (subprocess.CalledProcessError, shutil.Error) as error: print(f"Error while trying to encrypt pack. {error}") def decrypt_pack(self, encrypted_zip_pack_path, decryption_key): """ decrypt the pack in order to see that the pack was encrypted in the first place. Args: encrypted_zip_pack_path (str): The path for the encrypted zip pack. decryption_key (str): The key which we can decrypt the pack with. Returns: bool: whether the decryption succeeded. """ try: current_working_dir = os.getcwd() extract_destination_path = f'{current_working_dir}/decrypt_pack_dir' os.mkdir(extract_destination_path) shutil.copy('./decryptor', os.path.join(extract_destination_path, 'decryptor')) secondary_encrypted_pack_path = os.path.join(extract_destination_path, 'encrypted_zip_pack.zip') shutil.copy(encrypted_zip_pack_path, secondary_encrypted_pack_path) os.chmod(os.path.join(extract_destination_path, 'decryptor'), stat.S_IXOTH) output_decrypt_file_path = f"{extract_destination_path}/decrypt_pack.zip" os.chdir(extract_destination_path) subprocess.call('chmod +x ./decryptor', shell=True) full_command = f'./decryptor {secondary_encrypted_pack_path} {output_decrypt_file_path} "{decryption_key}"' process = subprocess.Popen(full_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdout, stderr = process.communicate() shutil.rmtree(extract_destination_path) os.chdir(current_working_dir) if stdout: logging.info(str(stdout)) if stderr: logging.error(f"Error: Premium pack {self._pack_name} should be encrypted, but isn't.") return False return True except subprocess.CalledProcessError as error: logging.exception(f"Error while trying to decrypt pack. {error}") return False def is_pack_encrypted(self, encrypted_zip_pack_path, decryption_key): """ Checks if the pack is encrypted by trying to decrypt it. Args: encrypted_zip_pack_path (str): The path for the encrypted zip pack. decryption_key (str): The key which we can decrypt the pack with. Returns: bool: whether the pack is encrypted. """ return self.decrypt_pack(encrypted_zip_pack_path, decryption_key) def zip_pack(self, extract_destination_path="", encryption_key="", private_artifacts_dir='private_artifacts', secondary_encryption_key=""): """ Zips pack folder. Returns: bool: whether the operation succeeded. str: full path to created pack zip. """ self._zip_path = f"{self._pack_path}.zip" if not encryption_key else f"{self._pack_path}_not_encrypted.zip" source_path = self._pack_path source_name = self._pack_name task_status = self.zip_folder_items(source_path, source_name, self._zip_path) # if failed to zip, skip encryption if task_status and encryption_key: try: Pack.encrypt_pack(self._zip_path, source_name, encryption_key, extract_destination_path, private_artifacts_dir, secondary_encryption_key) # If the pack needs to be encrypted, it is initially at a different location than this final path except Exception: task_status = False logging.exception(f"Failed in encrypting {source_name} folder") final_path_to_zipped_pack = f"{source_path}.zip" return task_status, final_path_to_zipped_pack def detect_modified(self, content_repo, index_folder_path, current_commit_hash, previous_commit_hash): """ Detects pack modified files. The diff is done between current commit and previous commit that was saved in metadata that was downloaded from index. In case that no commit was found in index (initial run), the default value will be set to previous commit from origin/master. Args: content_repo (git.repo.base.Repo): content repo object. index_folder_path (str): full path to downloaded index folder. current_commit_hash (str): last commit hash of head. previous_commit_hash (str): the previous commit to diff with. Returns: bool: whether the operation succeeded. list: list of RN files that were modified. bool: whether pack was modified and override will be required. """ task_status = False modified_rn_files_paths = [] pack_was_modified = False try: pack_index_metadata_path = os.path.join(index_folder_path, self._pack_name, Pack.METADATA) if not os.path.exists(pack_index_metadata_path): logging.info(f"{self._pack_name} pack was not found in index, skipping detection of modified pack.") task_status = True return with open(pack_index_metadata_path, 'r') as metadata_file: downloaded_metadata = json.load(metadata_file) previous_commit_hash = downloaded_metadata.get(Metadata.COMMIT, previous_commit_hash) # set 2 commits by hash value in order to check the modified files of the diff current_commit = content_repo.commit(current_commit_hash) previous_commit = content_repo.commit(previous_commit_hash) for modified_file in current_commit.diff(previous_commit): if modified_file.a_path.startswith(PACKS_FOLDER): modified_file_path_parts = os.path.normpath(modified_file.a_path).split(os.sep) if modified_file_path_parts[1] and modified_file_path_parts[1] == self._pack_name: if not is_ignored_pack_file(modified_file_path_parts): logging.info(f"Detected modified files in {self._pack_name} pack") task_status, pack_was_modified = True, True modified_rn_files_paths.append(modified_file.a_path) else: logging.debug(f'{modified_file.a_path} is an ignored file') task_status = True if pack_was_modified: # Make sure the modification is not only of release notes files, if so count that as not modified pack_was_modified = not all(self.RELEASE_NOTES in path for path in modified_rn_files_paths) # Filter modifications in release notes config JSON file - they will be handled later on. modified_rn_files_paths = [path_ for path_ in modified_rn_files_paths if path_.endswith('.md')] self._is_modified = pack_was_modified return except Exception: logging.exception(f"Failed in detecting modified files of {self._pack_name} pack") finally: return task_status, modified_rn_files_paths def upload_to_storage(self, zip_pack_path, latest_version, storage_bucket, override_pack, storage_base_path, private_content=False, pack_artifacts_path=None, overridden_upload_path=None): """ Manages the upload of pack zip artifact to correct path in cloud storage. The zip pack will be uploaded by defaualt to following path: /content/packs/pack_name/pack_latest_version. In case that zip pack artifact already exist at constructed path, the upload will be skipped. If flag override_pack is set to True, pack will forced for upload. If item_upload_path is provided it will override said path, and will save the item to that destination. Args: zip_pack_path (str): full path to pack zip artifact. latest_version (str): pack latest version. storage_bucket (google.cloud.storage.bucket.Bucket): google cloud storage bucket. override_pack (bool): whether to override existing pack. private_content (bool): Is being used in a private content build. storage_base_path (str): The upload destination in the target bucket for all packs (in the format of <some_path_in_the_target_bucket>/content/Packs). pack_artifacts_path (str): Path to where we are saving pack artifacts. overridden_upload_path (str): If provided, will override version_pack_path calculation and will use this path instead Returns: bool: whether the operation succeeded. bool: True in case of pack existence at targeted path and upload was skipped, otherwise returned False. str: Path to pack's zip in the bucket after the upload. """ task_status = True try: if overridden_upload_path: if private_content: logging.warning("Private content does not support overridden argument") return task_status, True, None zip_to_upload_full_path = overridden_upload_path else: version_pack_path = os.path.join(storage_base_path, self._pack_name, latest_version) existing_files = [Path(f.name).name for f in storage_bucket.list_blobs(prefix=version_pack_path)] if override_pack: logging.warning(f"Uploading {self._pack_name} pack to storage and overriding the existing pack " f"files already in storage.") elif existing_files: logging.warning(f"The following packs already exist in the storage: {', '.join(existing_files)}") logging.warning(f"Skipping step of uploading {self._pack_name}.zip to storage.") return task_status, True, None zip_to_upload_full_path = os.path.join(version_pack_path, f"{self._pack_name}.zip") blob = storage_bucket.blob(zip_to_upload_full_path) blob.cache_control = "no-cache,max-age=0" # disabling caching for pack blob with open(zip_pack_path, "rb") as pack_zip: blob.upload_from_file(pack_zip) if private_content: secondary_encryption_key_pack_name = f"{self._pack_name}.enc2.zip" secondary_encryption_key_bucket_path = os.path.join(version_pack_path, secondary_encryption_key_pack_name) # In some cases the path given is actually a zip. if isinstance(pack_artifacts_path, str) and pack_artifacts_path.endswith('content_packs.zip'): _pack_artifacts_path = pack_artifacts_path.replace('/content_packs.zip', '') else: _pack_artifacts_path = pack_artifacts_path secondary_encryption_key_artifacts_path = zip_pack_path.replace(f'{self._pack_name}', f'{self._pack_name}.enc2') blob = storage_bucket.blob(secondary_encryption_key_bucket_path) blob.cache_control = "no-cache,max-age=0" # disabling caching for pack blob with open(secondary_encryption_key_artifacts_path, "rb") as pack_zip: blob.upload_from_file(pack_zip) print( f"Copying {secondary_encryption_key_artifacts_path} to {_pack_artifacts_path}/" f"packs/{self._pack_name}.zip") shutil.copy(secondary_encryption_key_artifacts_path, f'{_pack_artifacts_path}/packs/{self._pack_name}.zip') self.public_storage_path = blob.public_url logging.success(f"Uploaded {self._pack_name} pack to {zip_to_upload_full_path} path.") return task_status, False, zip_to_upload_full_path except Exception: task_status = False logging.exception(f"Failed in uploading {self._pack_name} pack to gcs.") return task_status, True, None def copy_and_upload_to_storage(self, production_bucket, build_bucket, successful_packs_dict, storage_base_path, build_bucket_base_path): """ Manages the copy of pack zip artifact from the build bucket to the production bucket. The zip pack will be copied to following path: /content/packs/pack_name/pack_latest_version if the pack exists in the successful_packs_dict from Prepare content step in Create Instances job. Args: production_bucket (google.cloud.storage.bucket.Bucket): google cloud production bucket. build_bucket (google.cloud.storage.bucket.Bucket): google cloud build bucket. successful_packs_dict (dict): the dict of all packs were uploaded in prepare content step storage_base_path (str): The target destination of the upload in the target bucket. build_bucket_base_path (str): The path of the build bucket in gcp. Returns: bool: Status - whether the operation succeeded. bool: Skipped pack - true in case of pack existence at the targeted path and the copy process was skipped, otherwise returned False. """ pack_not_uploaded_in_prepare_content = self._pack_name not in successful_packs_dict if pack_not_uploaded_in_prepare_content: logging.warning("The following packs already exist at storage.") logging.warning(f"Skipping step of uploading {self._pack_name}.zip to storage.") return True, True latest_version = successful_packs_dict[self._pack_name][BucketUploadFlow.LATEST_VERSION] self._latest_version = latest_version build_version_pack_path = os.path.join(build_bucket_base_path, self._pack_name, latest_version) # Verifying that the latest version of the pack has been uploaded to the build bucket existing_bucket_version_files = [f.name for f in build_bucket.list_blobs(prefix=build_version_pack_path)] if not existing_bucket_version_files: logging.error(f"{self._pack_name} latest version ({latest_version}) was not found on build bucket at " f"path {build_version_pack_path}.") return False, False # We upload the pack zip object taken from the build bucket into the production bucket prod_version_pack_path = os.path.join(storage_base_path, self._pack_name, latest_version) prod_pack_zip_path = os.path.join(prod_version_pack_path, f'{self._pack_name}.zip') build_pack_zip_path = os.path.join(build_version_pack_path, f'{self._pack_name}.zip') build_pack_zip_blob = build_bucket.blob(build_pack_zip_path) try: copied_blob = build_bucket.copy_blob( blob=build_pack_zip_blob, destination_bucket=production_bucket, new_name=prod_pack_zip_path ) copied_blob.cache_control = "no-cache,max-age=0" # disabling caching for pack blob self.public_storage_path = copied_blob.public_url task_status = copied_blob.exists() except Exception as e: pack_suffix = os.path.join(self._pack_name, latest_version, f'{self._pack_name}.zip') logging.exception(f"Failed copying {pack_suffix}. Additional Info: {str(e)}") return False, False if not task_status: logging.error(f"Failed in uploading {self._pack_name} pack to production gcs.") else: # Determine if pack versions were aggregated during upload pack_uploaded_in_prepare_content = not pack_not_uploaded_in_prepare_content if pack_uploaded_in_prepare_content: agg_str = successful_packs_dict[self._pack_name].get('aggregated') if agg_str: self._aggregated = True self._aggregation_str = agg_str logging.success(f"Uploaded {self._pack_name} pack to {prod_pack_zip_path} path.") # handle dependenices zip upload when found in build bucket self.copy_and_upload_dependencies_zip_to_storage( build_bucket, build_bucket_base_path, production_bucket, storage_base_path ) return task_status, False def copy_and_upload_dependencies_zip_to_storage(self, build_bucket, build_bucket_base_path, production_bucket, storage_base_path): pack_with_deps_name = f'{self._pack_name}_with_dependencies.zip' build_pack_with_deps_path = os.path.join(build_bucket_base_path, self._pack_name, pack_with_deps_name) existing_bucket_deps_files = [f.name for f in build_bucket.list_blobs(prefix=build_pack_with_deps_path)] if existing_bucket_deps_files: logging.info(f"{self._pack_name} with dependencies was found. path {build_pack_with_deps_path}.") # We upload the pack dependencies zip object taken from the build bucket into the production bucket prod_version_pack_deps_zip_path = os.path.join(storage_base_path, self._pack_name, pack_with_deps_name) build_pack_deps_zip_blob = build_bucket.blob(build_pack_with_deps_path) try: copied_blob = build_bucket.copy_blob( blob=build_pack_deps_zip_blob, destination_bucket=production_bucket, new_name=prod_version_pack_deps_zip_path ) copied_blob.cache_control = "no-cache,max-age=0" # disabling caching for pack blob self.public_storage_path = copied_blob.public_url dep_task_status = copied_blob.exists() if not dep_task_status: logging.error(f"Failed in uploading {self._pack_name} pack with dependencies to production gcs.") except Exception as e: pack_deps_zip_suffix = os.path.join(self._pack_name, pack_with_deps_name) logging.exception(f"Failed copying {pack_deps_zip_suffix}. Additional Info: {str(e)}") def get_changelog_latest_rn(self, changelog_index_path: str) -> Tuple[dict, Version, str]: """ Returns the changelog file contents and the last version of rn in the changelog file Args: changelog_index_path (str): the changelog.json file path in the index Returns: the changelog file contents, the last version, and contents of rn in the changelog file """ logging.info(f"Found Changelog for: {self._pack_name}") if os.path.exists(changelog_index_path): try: with open(changelog_index_path, "r") as changelog_file: changelog = json.load(changelog_file) except json.JSONDecodeError: changelog = {} else: changelog = {} # get the latest rn version in the changelog.json file changelog_rn_versions = [Version(ver) for ver in changelog] # no need to check if changelog_rn_versions isn't empty because changelog file exists changelog_latest_rn_version = max(changelog_rn_versions) changelog_latest_rn = changelog[str(changelog_latest_rn_version)]["releaseNotes"] return changelog, changelog_latest_rn_version, changelog_latest_rn def get_modified_release_notes_lines(self, release_notes_dir: str, new_release_notes_versions: list, changelog: dict, modified_rn_files: list): """ In the case where an rn file was changed, this function returns the new content of the release note in the format suitable for the changelog file. In general, if two rn files are created between two consecutive upload runs (i.e. pack was changed twice), the rn files are being aggregated and the latter version is the one that is being used as a key in the changelog file, and the aggregated rns as the value. Hence, in the case of changing an rn as such, this function re-aggregates all of the rns under the corresponding version key, and returns the aggregated data, in the right format, as value under that key. Args: release_notes_dir (str): the path to the release notes dir new_release_notes_versions (list): a list of the new versions of release notes in the pack since the last upload. This means they were already handled on this upload run (and aggregated if needed). changelog (dict): the changelog from the production bucket. modified_rn_files (list): a list of the rn files that were modified according to the last commit in 'filename.md' format. Returns: A dict of modified version and their release notes contents, for modified in the current index file """ modified_versions_dict = {} for rn_filename in modified_rn_files: version = underscore_file_name_to_dotted_version(rn_filename) # Should only apply on modified files that are not the last rn file if version in new_release_notes_versions: continue # The case where the version is a key in the changelog file, # and the value is not an aggregated release note if is_the_only_rn_in_block(release_notes_dir, version, changelog): logging.info("The version is a key in the changelog file and by itself in the changelog block") with open(os.path.join(release_notes_dir, rn_filename), 'r') as rn_file: rn_lines = rn_file.read() modified_versions_dict[version] = self._clean_release_notes(rn_lines).strip() # The case where the version is not a key in the changelog file or it is a key of aggregated content else: logging.debug(f'The "{version}" version is not a key in the changelog file or it is a key of' f' aggregated content') same_block_versions_dict, higher_nearest_version = self.get_same_block_versions( release_notes_dir, version, changelog) modified_versions_dict[higher_nearest_version] = aggregate_release_notes_for_marketplace( same_block_versions_dict) return modified_versions_dict def get_same_block_versions(self, release_notes_dir: str, version: str, changelog: dict): """ Get a dict of the version as key and rn data as value of all of the versions that are in the same block in the changelog file as the given version (these are the versions that were aggregates together during a single upload priorly). Args: release_notes_dir (str): the path to the release notes dir version (str): the wanted version changelog (dict): the changelog from the production bucket. Returns: A dict of version, rn data for all corresponding versions, and the highest version among those keys as str """ lowest_version = [Version(Pack.PACK_INITIAL_VERSION)] lower_versions: list = [] higher_versions: list = [] same_block_versions_dict: dict = dict() for item in changelog.keys(): # divide the versions into lists of lower and higher than given version (lower_versions if Version(item) < Version(version) else higher_versions).append(Version(item)) higher_nearest_version = min(higher_versions) lower_versions = lower_versions + lowest_version # if the version is 1.0.0, ensure lower_versions is not empty lower_nearest_version = max(lower_versions) for rn_filename in filter_dir_files_by_extension(release_notes_dir, '.md'): current_version = underscore_file_name_to_dotted_version(rn_filename) # Catch all versions that are in the same block if lower_nearest_version < Version(current_version) <= higher_nearest_version: with open(os.path.join(release_notes_dir, rn_filename), 'r') as rn_file: rn_lines = rn_file.read() same_block_versions_dict[current_version] = self._clean_release_notes(rn_lines).strip() return same_block_versions_dict, str(higher_nearest_version) def get_release_notes_lines(self, release_notes_dir: str, changelog_latest_rn_version: Version, changelog_latest_rn: str) -> Tuple[str, str, list]: """ Prepares the release notes contents for the new release notes entry Args: release_notes_dir (str): the path to the release notes dir changelog_latest_rn_version (Version): the last version of release notes in the changelog.json file changelog_latest_rn (str): the last release notes in the changelog.json file Returns: The release notes contents, the latest release notes version (in the release notes directory), and a list of the new rn versions that this is the first time they have been uploaded. """ found_versions: list = list() pack_versions_dict: dict = dict() for filename in sorted(filter_dir_files_by_extension(release_notes_dir, '.md')): version = underscore_file_name_to_dotted_version(filename) # Aggregate all rn files that are bigger than what we have in the changelog file if Version(version) > changelog_latest_rn_version: with open(os.path.join(release_notes_dir, filename), 'r') as rn_file: rn_lines = rn_file.read() pack_versions_dict[version] = self._clean_release_notes(rn_lines).strip() found_versions.append(Version(version)) latest_release_notes_version = max(found_versions) latest_release_notes_version_str = str(latest_release_notes_version) logging.info(f"Latest ReleaseNotes version is: {latest_release_notes_version_str}") if len(pack_versions_dict) > 1: # In case that there is more than 1 new release notes file, wrap all release notes together for one # changelog entry aggregation_str = f"[{', '.join(str(lv) for lv in found_versions if lv > changelog_latest_rn_version)}]"\ f" => {latest_release_notes_version_str}" logging.info(f"Aggregating ReleaseNotes versions: {aggregation_str}") release_notes_lines = aggregate_release_notes_for_marketplace(pack_versions_dict) self._aggregated = True self._aggregation_str = aggregation_str elif len(pack_versions_dict) == 1: # In case where there is only one new release notes file release_notes_lines = pack_versions_dict[latest_release_notes_version_str] else: # In case where the pack is up to date, i.e. latest changelog is latest rn file # We should take the release notes from the index as it has might been aggregated logging.info(f'No new RN file was detected for pack {self._pack_name}, taking latest RN from the index') release_notes_lines = changelog_latest_rn new_release_notes_versions = list(pack_versions_dict.keys()) return release_notes_lines, latest_release_notes_version_str, new_release_notes_versions def assert_upload_bucket_version_matches_release_notes_version(self, changelog: dict, latest_release_notes: str) -> None: """ Sometimes there is a the current bucket is not merged from master there could be another version in the upload bucket, that does not exist in the current branch. This case can cause unpredicted behavior and we want to fail the build. This method validates that this is not the case in the current build, and if it does - fails it with an assertion error. Args: changelog: The changelog from the production bucket. latest_release_notes: The latest release notes version string in the current branch """ changelog_latest_release_notes = max(changelog, key=lambda k: Version(k)) # pylint: disable=W0108 assert Version(latest_release_notes) >= Version(changelog_latest_release_notes), \ f'{self._pack_name}: Version mismatch detected between upload bucket and current branch\n' \ f'Upload bucket version: {changelog_latest_release_notes}\n' \ f'current branch version: {latest_release_notes}\n' \ 'Please Merge from master and rebuild' def get_rn_files_names(self, modified_rn_files_paths): """ Args: modified_rn_files_paths: a list containing all modified files in the current pack, generated by comparing the old and the new commit hash. Returns: The names of the modified release notes files out of the given list only, as in the names of the files that are under ReleaseNotes directory in the format of 'filename.md'. """ modified_rn_files = [] for file_path in modified_rn_files_paths: modified_file_path_parts = os.path.normpath(file_path).split(os.sep) if self.RELEASE_NOTES in modified_file_path_parts: modified_rn_files.append(modified_file_path_parts[-1]) return modified_rn_files def prepare_release_notes(self, index_folder_path, build_number, modified_rn_files_paths=None): """ Handles the creation and update of the changelog.json files. Args: index_folder_path (str): Path to the unzipped index json. build_number (str): circleCI build number. modified_rn_files_paths (list): list of paths of the pack's modified file Returns: bool: whether the operation succeeded. bool: whether running build has not updated pack release notes. """ task_status = False not_updated_build = False release_notes_dir = os.path.join(self._pack_path, Pack.RELEASE_NOTES) modified_rn_files_paths = modified_rn_files_paths if modified_rn_files_paths else [] try: # load changelog from downloaded index logging.info(f"Loading changelog for {self._pack_name} pack") changelog_index_path = os.path.join(index_folder_path, self._pack_name, Pack.CHANGELOG_JSON) if os.path.exists(changelog_index_path): changelog, changelog_latest_rn_version, changelog_latest_rn = \ self.get_changelog_latest_rn(changelog_index_path) if os.path.exists(release_notes_dir): # Handling latest release notes files release_notes_lines, latest_release_notes, new_release_notes_versions = \ self.get_release_notes_lines( release_notes_dir, changelog_latest_rn_version, changelog_latest_rn) self.assert_upload_bucket_version_matches_release_notes_version(changelog, latest_release_notes) # Handling modified old release notes files, if there are any rn_files_names = self.get_rn_files_names(modified_rn_files_paths) modified_release_notes_lines_dict = self.get_modified_release_notes_lines( release_notes_dir, new_release_notes_versions, changelog, rn_files_names) if self._current_version != latest_release_notes: logging.error(f"Version mismatch detected between the pack's current version in " f"pack_metadata.json: {self._current_version} and latest release notes " f"version: {latest_release_notes}.") task_status = False return task_status, not_updated_build else: if latest_release_notes in changelog: logging.debug(f"Found existing release notes for version: {latest_release_notes}") version_changelog = self._create_changelog_entry(release_notes=release_notes_lines, version_display_name=latest_release_notes, build_number=build_number, new_version=False) else: logging.info(f"Created new release notes for version: {latest_release_notes}") version_changelog = self._create_changelog_entry(release_notes=release_notes_lines, version_display_name=latest_release_notes, build_number=build_number, new_version=True) if version_changelog: changelog[latest_release_notes] = version_changelog if modified_release_notes_lines_dict: logging.info("Updating changelog entries for modified release notes") for version, modified_release_notes_lines in modified_release_notes_lines_dict.items(): updated_entry = self._get_updated_changelog_entry( changelog, version, release_notes=modified_release_notes_lines) changelog[version] = updated_entry else: if len(changelog.keys()) > 1: # If there is no release notes dir but the changelog has a few entries in it, # there is a mismatch logging.warning( f"{self._pack_name} pack mismatch between {Pack.CHANGELOG_JSON} and {Pack.RELEASE_NOTES}") task_status, not_updated_build = True, True return task_status, not_updated_build else: # allow changing the initial changelog version first_key_in_changelog = list(changelog.keys())[0] changelog[first_key_in_changelog] = self._create_changelog_entry( release_notes=self.description, version_display_name=first_key_in_changelog, build_number=build_number, initial_release=True, new_version=False) logging.info(f"Found existing release notes in {Pack.CHANGELOG_JSON} for version: " f"{first_key_in_changelog} of pack {self._pack_name}. Modifying this version in " f"{Pack.CHANGELOG_JSON}") elif self._hidden: logging.warning(f"Pack {self._pack_name} is deprecated. Skipping release notes handling.") task_status = True not_updated_build = True return task_status, not_updated_build else: # if there is no changelog file for the pack, this is a new pack, and we start it's changelog at it's # current version version_changelog = self._create_changelog_entry( release_notes=self.description, version_display_name=self._current_version, build_number=build_number, new_version=True, initial_release=True ) changelog = { self._current_version: version_changelog } logging.info(f'Created {Pack.CHANGELOG_JSON} for pack {self._pack_name} starting at version' f' {self._current_version}') # Update change log entries with BC flag. self.add_bc_entries_if_needed(release_notes_dir, changelog) # write back changelog with changes to pack folder with open(os.path.join(self._pack_path, Pack.CHANGELOG_JSON), "w") as pack_changelog: json.dump(changelog, pack_changelog, indent=4) task_status = True logging.success(f"Finished creating {Pack.CHANGELOG_JSON} for {self._pack_name}") except Exception as e: logging.error(f"Failed creating {Pack.CHANGELOG_JSON} file for {self._pack_name}.\n " f"Additional info: {e}") finally: return task_status, not_updated_build def create_local_changelog(self, build_index_folder_path): """ Copies the pack index changelog.json file to the pack path Args: build_index_folder_path: The path to the build index folder Returns: bool: whether the operation succeeded. """ task_status = True build_changelog_index_path = os.path.join(build_index_folder_path, self._pack_name, Pack.CHANGELOG_JSON) pack_changelog_path = os.path.join(self._pack_path, Pack.CHANGELOG_JSON) if os.path.exists(build_changelog_index_path): try: shutil.copyfile(src=build_changelog_index_path, dst=pack_changelog_path) logging.success(f"Successfully copied pack index changelog.json file from {build_changelog_index_path}" f" to {pack_changelog_path}.") except shutil.Error as e: task_status = False logging.error(f"Failed copying changelog.json file from {build_changelog_index_path} to " f"{pack_changelog_path}. Additional info: {str(e)}") return task_status else: task_status = False logging.error( f"{self._pack_name} index changelog file is missing in build bucket path: {build_changelog_index_path}") return task_status and self.is_changelog_exists() def collect_content_items(self): """ Iterates over content items folders inside pack and collects content items data. Returns: dict: Parsed content items . """ task_status = False content_items_result: dict = {} try: # the format is defined in issue #19786, may change in the future content_item_name_mapping = { PackFolders.SCRIPTS.value: "automation", PackFolders.PLAYBOOKS.value: "playbook", PackFolders.INTEGRATIONS.value: "integration", PackFolders.INCIDENT_FIELDS.value: "incidentfield", PackFolders.INCIDENT_TYPES.value: "incidenttype", PackFolders.DASHBOARDS.value: "dashboard", PackFolders.INDICATOR_FIELDS.value: "indicatorfield", PackFolders.REPORTS.value: "report", PackFolders.INDICATOR_TYPES.value: "reputation", PackFolders.LAYOUTS.value: "layoutscontainer", PackFolders.CLASSIFIERS.value: "classifier", PackFolders.WIDGETS.value: "widget", PackFolders.GENERIC_DEFINITIONS.value: "genericdefinition", PackFolders.GENERIC_FIELDS.value: "genericfield", PackFolders.GENERIC_MODULES.value: "genericmodule", PackFolders.GENERIC_TYPES.value: "generictype", PackFolders.LISTS.value: "list", PackFolders.PREPROCESS_RULES.value: "preprocessrule", PackFolders.JOBS.value: "job", PackFolders.PARSING_RULES.value: "parsingrule", PackFolders.MODELING_RULES.value: "modelingrule", PackFolders.CORRELATION_RULES.value: "correlationrule", PackFolders.XSIAM_DASHBOARDS.value: "xsiamdashboard", PackFolders.XSIAM_REPORTS.value: "xsiamreport", PackFolders.TRIGGERS.value: "trigger", PackFolders.WIZARDS.value: "wizard", } for root, pack_dirs, pack_files_names in os.walk(self._pack_path, topdown=False): current_directory = root.split(os.path.sep)[-1] parent_directory = root.split(os.path.sep)[-2] if parent_directory in [PackFolders.GENERIC_TYPES.value, PackFolders.GENERIC_FIELDS.value]: current_directory = parent_directory elif current_directory in [PackFolders.GENERIC_TYPES.value, PackFolders.GENERIC_FIELDS.value]: continue folder_collected_items = [] for pack_file_name in pack_files_names: if not pack_file_name.endswith(('.json', '.yml')): continue pack_file_path = os.path.join(root, pack_file_name) # reputation in old format aren't supported in 6.0.0 server version if current_directory == PackFolders.INDICATOR_TYPES.value \ and not fnmatch.fnmatch(pack_file_name, 'reputation-*.json'): os.remove(pack_file_path) logging.info(f"Deleted pack {pack_file_name} reputation file for {self._pack_name} pack") continue with open(pack_file_path, 'r') as pack_file: if current_directory in PackFolders.yml_supported_folders(): content_item = yaml.safe_load(pack_file) elif current_directory in PackFolders.json_supported_folders(): content_item = json.load(pack_file) else: continue # check if content item has to version to_version = content_item.get('toversion') or content_item.get('toVersion') if to_version and Version(to_version) < Version(Metadata.SERVER_DEFAULT_MIN_VERSION): os.remove(pack_file_path) logging.info( f"{self._pack_name} pack content item {pack_file_name} has to version: {to_version}. " f"{pack_file_name} file was deleted.") continue if current_directory not in PackFolders.pack_displayed_items(): continue # skip content items that are not displayed in contentItems logging.debug( f"Iterating over {pack_file_path} file and collecting items of {self._pack_name} pack") # updated min server version from current content item self._server_min_version = get_updated_server_version(self._server_min_version, content_item, self._pack_name) content_item_tags = content_item.get('tags', []) if current_directory == PackFolders.SCRIPTS.value: folder_collected_items.append({ 'id': content_item.get('commonfields', {}).get('id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('comment', ''), 'tags': content_item_tags, }) if not self._contains_transformer and 'transformer' in content_item_tags: self._contains_transformer = True if not self._contains_filter and 'filter' in content_item_tags: self._contains_filter = True elif current_directory == PackFolders.PLAYBOOKS.value: self.add_pack_type_tags(content_item, 'Playbook') folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('description', ''), }) elif current_directory == PackFolders.INTEGRATIONS.value: integration_commands = content_item.get('script', {}).get('commands', []) self.add_pack_type_tags(content_item, 'Integration') folder_collected_items.append({ 'id': content_item.get('commonfields', {}).get('id', ''), 'name': content_item.get('display', ''), 'description': content_item.get('description', ''), 'category': content_item.get('category', ''), 'commands': [ {'name': c.get('name', ''), 'description': c.get('description', '')} for c in integration_commands], }) elif current_directory == PackFolders.INCIDENT_FIELDS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'type': content_item.get('type', ''), 'description': content_item.get('description', ''), }) elif current_directory == PackFolders.INCIDENT_TYPES.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'playbook': content_item.get('playbookId', ''), 'closureScript': content_item.get('closureScript', ''), 'hours': int(content_item.get('hours', 0)), 'days': int(content_item.get('days', 0)), 'weeks': int(content_item.get('weeks', 0)), }) elif current_directory == PackFolders.DASHBOARDS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), }) elif current_directory == PackFolders.INDICATOR_FIELDS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'type': content_item.get('type', ''), 'description': content_item.get('description', ''), }) elif current_directory == PackFolders.REPORTS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('description', ''), }) elif current_directory == PackFolders.INDICATOR_TYPES.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'details': content_item.get('details', ''), 'reputationScriptName': content_item.get('reputationScriptName', ''), 'enhancementScriptNames': content_item.get('enhancementScriptNames', []), }) elif current_directory == PackFolders.LAYOUTS.value: layout_metadata = { 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), } layout_description = content_item.get('description') if layout_description is not None: layout_metadata['description'] = layout_description folder_collected_items.append(layout_metadata) elif current_directory == PackFolders.CLASSIFIERS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name') or content_item.get('id', ''), 'description': content_item.get('description', ''), }) elif current_directory == PackFolders.WIDGETS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'dataType': content_item.get('dataType', ''), 'widgetType': content_item.get('widgetType', ''), }) elif current_directory == PackFolders.LISTS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', '') }) elif current_directory == PackFolders.GENERIC_DEFINITIONS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('description', ''), }) elif parent_directory == PackFolders.GENERIC_FIELDS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('description', ''), 'type': content_item.get('type', ''), }) elif current_directory == PackFolders.GENERIC_MODULES.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('description', ''), }) elif parent_directory == PackFolders.GENERIC_TYPES.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('description', ''), }) elif current_directory == PackFolders.PREPROCESS_RULES.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('description', ''), }) elif current_directory == PackFolders.JOBS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), # note that `name` may technically be blank, but shouldn't pass validations 'name': content_item.get('name', ''), 'details': content_item.get('details', ''), }) elif current_directory == PackFolders.PARSING_RULES.value: self.add_pack_type_tags(content_item, 'ParsingRule') folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), }) elif current_directory == PackFolders.MODELING_RULES.value: self.add_pack_type_tags(content_item, 'ModelingRule') folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), }) elif current_directory == PackFolders.CORRELATION_RULES.value: self.add_pack_type_tags(content_item, 'CorrelationRule') folder_collected_items.append({ 'id': content_item.get('global_rule_id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('description', ''), }) elif current_directory == PackFolders.XSIAM_DASHBOARDS.value: folder_collected_items.append({ 'id': content_item.get('dashboards_data', [{}])[0].get('global_id', ''), 'name': content_item.get('dashboards_data', [{}])[0].get('name', ''), 'description': content_item.get('dashboards_data', [{}])[0].get('description', ''), }) elif current_directory == PackFolders.XSIAM_REPORTS.value: folder_collected_items.append({ 'id': content_item.get('templates_data', [{}])[0].get('global_id', ''), 'name': content_item.get('templates_data', [{}])[0].get('report_name', ''), 'description': content_item.get('templates_data', [{}])[0].get('report_description', ''), }) elif current_directory == PackFolders.TRIGGERS.value: folder_collected_items.append({ 'id': content_item.get('trigger_id', ''), 'name': content_item.get('trigger_name', ''), 'description': content_item.get('description', ''), }) elif current_directory == PackFolders.WIZARDS.value: folder_collected_items.append({ 'id': content_item.get('id', ''), 'name': content_item.get('name', ''), 'description': content_item.get('description', ''), 'dependency_packs': content_item.get('dependency_packs', {}) }) else: logging.info(f'Failed to collect: {current_directory}') if current_directory in PackFolders.pack_displayed_items(): content_item_key = content_item_name_mapping[current_directory] content_items_result[content_item_key] = \ content_items_result.get(content_item_key, []) + folder_collected_items logging.success(f"Finished collecting content items for {self._pack_name} pack") task_status = True except Exception: logging.exception(f"Failed collecting content items in {self._pack_name} pack") finally: self._content_items = content_items_result return task_status def load_user_metadata(self): """ Loads user defined metadata and stores part of it's data in defined properties fields. Returns: bool: whether the operation succeeded. """ task_status = False user_metadata = {} try: user_metadata_path = os.path.join(self._pack_path, Pack.USER_METADATA) # user metadata path before parsing if not os.path.exists(user_metadata_path): logging.error(f"{self._pack_name} pack is missing {Pack.USER_METADATA} file.") return task_status with open(user_metadata_path, "r") as user_metadata_file: user_metadata = json.load(user_metadata_file) # loading user metadata # part of old packs are initialized with empty list user_metadata = {} if isinstance(user_metadata, list) else user_metadata # store important user metadata fields self.support_type = user_metadata.get(Metadata.SUPPORT, Metadata.XSOAR_SUPPORT) self.current_version = user_metadata.get(Metadata.CURRENT_VERSION, '') self.hidden = user_metadata.get(Metadata.HIDDEN, False) self.description = user_metadata.get(Metadata.DESCRIPTION, False) self.display_name = user_metadata.get(Metadata.NAME, '') # type: ignore[misc] self._user_metadata = user_metadata self._eula_link = user_metadata.get(Metadata.EULA_LINK, Metadata.EULA_URL) self._marketplaces = user_metadata.get('marketplaces', ['xsoar']) logging.info(f"Finished loading {self._pack_name} pack user metadata") task_status = True except Exception: logging.exception(f"Failed in loading {self._pack_name} user metadata.") finally: return task_status def _collect_pack_tags(self, user_metadata, landing_page_sections, trending_packs): tags = set(input_to_list(input_data=user_metadata.get('tags'))) tags |= self._get_tags_from_landing_page(landing_page_sections) tags |= {PackTags.TIM} if self._is_feed else set() tags |= {PackTags.USE_CASE} if self._use_cases else set() tags |= {PackTags.TRANSFORMER} if self._contains_transformer else set() tags |= {PackTags.FILTER} if self._contains_filter else set() tags |= {PackTags.COLLECTION} if self._is_siem else set() if self._create_date: days_since_creation = (datetime.utcnow() - datetime.strptime(self._create_date, Metadata.DATE_FORMAT)).days if days_since_creation <= 30: tags |= {PackTags.NEW} else: tags -= {PackTags.NEW} if trending_packs: if self._pack_name in trending_packs: tags |= {PackTags.TRENDING} else: tags -= {PackTags.TRENDING} return tags def _enhance_pack_attributes(self, index_folder_path, dependencies_metadata_dict, statistics_handler=None, format_dependencies_only=False): """ Enhances the pack object with attributes for the metadata file Args: dependencies_metadata_dict (dict): mapping of pack dependencies metadata, for first level dependencies. format_dependencies_only (bool): Indicates whether the metadata formation is just for formatting the dependencies or not. Returns: dict: parsed pack metadata. """ landing_page_sections = mp_statistics.StatisticsHandler.get_landing_page_sections() trending_packs = None pack_dependencies_by_download_count = self._displayed_images_dependent_on_packs if not format_dependencies_only: # ===== Pack Regular Attributes ===== self._support_type = self.user_metadata.get(Metadata.SUPPORT, Metadata.XSOAR_SUPPORT) self._support_details = self._create_support_section( support_type=self._support_type, support_url=self.user_metadata.get(Metadata.URL), support_email=self.user_metadata.get(Metadata.EMAIL) ) self._author = self._get_author( support_type=self._support_type, author=self.user_metadata.get(Metadata.AUTHOR, '')) self._certification = self._get_certification( support_type=self._support_type, certification=self.user_metadata.get(Metadata.CERTIFICATION) ) self._legacy = self.user_metadata.get(Metadata.LEGACY, True) self._create_date = self._get_pack_creation_date(index_folder_path) self._update_date = self._get_pack_update_date(index_folder_path) self._use_cases = input_to_list(input_data=self.user_metadata.get(Metadata.USE_CASES), capitalize_input=True) self._categories = input_to_list(input_data=self.user_metadata.get(Metadata.CATEGORIES), capitalize_input=True) self._keywords = input_to_list(self.user_metadata.get(Metadata.KEY_WORDS)) self._parsed_dependencies = self._parse_pack_dependencies(self.user_metadata.get(Metadata.DEPENDENCIES, {}), dependencies_metadata_dict) # ===== Pack Private Attributes ===== if not format_dependencies_only: self._is_private_pack = Metadata.PARTNER_ID in self.user_metadata self._is_premium = self._is_private_pack self._preview_only = get_valid_bool(self.user_metadata.get(Metadata.PREVIEW_ONLY, False)) self._price = convert_price(pack_id=self._pack_name, price_value_input=self.user_metadata.get('price')) if self._is_private_pack: self._vendor_id = self.user_metadata.get(Metadata.VENDOR_ID, "") self._partner_id = self.user_metadata.get(Metadata.PARTNER_ID, "") self._partner_name = self.user_metadata.get(Metadata.PARTNER_NAME, "") self._content_commit_hash = self.user_metadata.get(Metadata.CONTENT_COMMIT_HASH, "") # Currently all content packs are legacy. # Since premium packs cannot be legacy, we directly set this attribute to false. self._legacy = False # ===== Pack Statistics Attributes ===== if not self._is_private_pack and statistics_handler: # Public Content case self._pack_statistics_handler = mp_statistics.PackStatisticsHandler( self._pack_name, statistics_handler.packs_statistics_df, statistics_handler.packs_download_count_desc, self._displayed_images_dependent_on_packs ) self._downloads_count = self._pack_statistics_handler.download_count trending_packs = statistics_handler.trending_packs pack_dependencies_by_download_count = self._pack_statistics_handler.displayed_dependencies_sorted self._tags = self._collect_pack_tags(self.user_metadata, landing_page_sections, trending_packs) self._search_rank = mp_statistics.PackStatisticsHandler.calculate_search_rank( tags=self._tags, certification=self._certification, content_items=self._content_items ) self._related_integration_images = self._get_all_pack_images( self._displayed_integration_images, self._displayed_images_dependent_on_packs, dependencies_metadata_dict, pack_dependencies_by_download_count ) def format_metadata(self, index_folder_path, packs_dependencies_mapping, build_number, commit_hash, statistics_handler, packs_dict=None, marketplace='xsoar', format_dependencies_only=False): """ Re-formats metadata according to marketplace metadata format defined in issue #19786 and writes back the result. Args: index_folder_path (str): downloaded index folder directory path. packs_dependencies_mapping (dict): all packs dependencies lookup mapping. build_number (str): circleCI build number. commit_hash (str): current commit hash. statistics_handler (StatisticsHandler): The marketplace statistics handler packs_dict (dict): dict of all packs relevant for current marketplace, as {pack_id: pack_object}. marketplace (str): Marketplace of current upload. format_dependencies_only (bool): Indicates whether the metadata formation is just for formatting the dependencies or not. Returns: bool: True is returned in case metadata file was parsed successfully, otherwise False. bool: True is returned in pack is missing dependencies. """ task_status = False packs_dict = packs_dict if packs_dict else {} is_missing_dependencies = False try: self.set_pack_dependencies(packs_dependencies_mapping, packs_dict, marketplace=marketplace) logging.info(f"Loading pack dependencies metadata for {self._pack_name} pack") dependencies_metadata_dict, is_missing_dependencies = self._load_pack_dependencies_metadata( index_folder_path, packs_dict) self._enhance_pack_attributes(index_folder_path, dependencies_metadata_dict, statistics_handler, format_dependencies_only) formatted_metadata = self._parse_pack_metadata(build_number, commit_hash) metadata_path = os.path.join(self._pack_path, Pack.METADATA) # deployed metadata path after parsing json_write(metadata_path, formatted_metadata) # writing back parsed metadata logging.success(f"Finished formatting {self._pack_name} packs's {Pack.METADATA} {metadata_path} file.") task_status = True except Exception as e: logging.exception(f"Failed in formatting {self._pack_name} pack metadata. Additional Info: {str(e)}") finally: return task_status, is_missing_dependencies @staticmethod def pack_created_in_time_delta(pack_name, time_delta: timedelta, index_folder_path: str) -> bool: """ Checks if pack created before delta specified in the 'time_delta' argument and return boolean according to the result Args: pack_name: the pack name. time_delta: time_delta to check if pack was created before. index_folder_path: downloaded index folder directory path. Returns: True if pack was created before the time_delta from now, and False otherwise. """ pack_creation_time_str = Pack._calculate_pack_creation_date(pack_name, index_folder_path) return datetime.utcnow() - datetime.strptime(pack_creation_time_str, Metadata.DATE_FORMAT) < time_delta def _get_pack_creation_date(self, index_folder_path): return self._calculate_pack_creation_date(self._pack_name, index_folder_path) @staticmethod def _calculate_pack_creation_date(pack_name, index_folder_path): """ Gets the pack created date. Args: index_folder_path (str): downloaded index folder directory path. Returns: datetime: Pack created date. """ created_time = datetime.utcnow().strftime(Metadata.DATE_FORMAT) metadata = load_json(os.path.join(index_folder_path, pack_name, Pack.METADATA)) if metadata: if metadata.get(Metadata.CREATED): created_time = metadata.get(Metadata.CREATED, '') else: raise Exception(f'The metadata file of the {pack_name} pack does not contain "{Metadata.CREATED}" time') return created_time def _get_pack_update_date(self, index_folder_path): """ Gets the pack update date. Args: index_folder_path (str): downloaded index folder directory path. Returns: datetime: Pack update date. """ latest_changelog_released_date = datetime.utcnow().strftime(Metadata.DATE_FORMAT) changelog = load_json(os.path.join(index_folder_path, self._pack_name, Pack.CHANGELOG_JSON)) if changelog and not self.is_modified: packs_latest_release_notes = max(Version(ver) for ver in changelog) latest_changelog_version = changelog.get(str(packs_latest_release_notes), {}) latest_changelog_released_date = latest_changelog_version.get('released') return latest_changelog_released_date def set_pack_dependencies(self, packs_dependencies_mapping, packs_dict, marketplace='xsoar'): """ Retrieve all pack's dependencies by merging the calculated dependencies from pack_dependencies.json file, given as input priorly, and the hard coded dependencies featured in the pack_metadata.json file. This is done for both first level dependencies and the all levels dependencies. Args: packs_dependencies_mapping: the calculated dependencies from pack_dependencies.json file packs_dict (dict): Dict of packs relevant for current marketplace as {pack_name: pack_object} marketplace: the current marketplace this upload is for """ pack_dependencies_mapping = packs_dependencies_mapping.get(self._pack_name, {}) first_level_dependencies = pack_dependencies_mapping.get(Metadata.DEPENDENCIES, {}) all_levels_dependencies = pack_dependencies_mapping.get(Metadata.ALL_LEVELS_DEPENDENCIES, []) displayed_images_dependent_on_packs = pack_dependencies_mapping.get(Metadata.DISPLAYED_IMAGES, []) # filter out packs that are not a part of the marketplace this upload is for first_level_dependencies = {k: v for k, v in first_level_dependencies.items() if k in packs_dict} all_levels_dependencies = [k for k in all_levels_dependencies if k in packs_dict] displayed_images_dependent_on_packs = [k for k in displayed_images_dependent_on_packs if k in packs_dict] if Metadata.DISPLAYED_IMAGES not in self._user_metadata: self._user_metadata[Metadata.DISPLAYED_IMAGES] = displayed_images_dependent_on_packs if Metadata.DEPENDENCIES not in self._user_metadata: self._user_metadata[Metadata.DEPENDENCIES] = {} if self._pack_name != GCPConfig.BASE_PACK: # add base as a mandatory pack dependency, by design for all packs first_level_dependencies.update(BASE_PACK_DEPENDENCY_DICT) # update the calculated dependencies with the hardcoded dependencies first_level_dependencies.update(self.user_metadata[Metadata.DEPENDENCIES]) # If it is a core pack, check that no new mandatory packs (that are not core packs) were added # They can be overridden in the user metadata to be not mandatory so we need to check there as well core_packs = GCPConfig.get_core_packs(marketplace) if self._pack_name in core_packs: mandatory_dependencies = [k for k, v in first_level_dependencies.items() if v.get(Metadata.MANDATORY, False) is True and k not in core_packs and k not in self._user_metadata[Metadata.DEPENDENCIES].keys()] if mandatory_dependencies: raise Exception(f'New mandatory dependencies {mandatory_dependencies} were ' f'found in the core pack {self._pack_name}') self._user_metadata[Metadata.DEPENDENCIES] = first_level_dependencies self._first_level_dependencies = first_level_dependencies self._all_levels_dependencies = all_levels_dependencies self._displayed_images_dependent_on_packs = displayed_images_dependent_on_packs def prepare_for_index_upload(self): """ Removes and leaves only necessary files in pack folder. Returns: bool: whether the operation succeeded. """ task_status = False files_to_leave = [Pack.METADATA, Pack.CHANGELOG_JSON, Pack.README] try: for file_or_folder in os.listdir(self._pack_path): files_or_folder_path = os.path.join(self._pack_path, file_or_folder) if file_or_folder in files_to_leave: continue if os.path.isdir(files_or_folder_path): shutil.rmtree(files_or_folder_path) else: os.remove(files_or_folder_path) task_status = True except Exception: logging.exception(f"Failed in preparing index for upload in {self._pack_name} pack.") finally: return task_status @staticmethod def _get_spitted_yml_image_data(root, target_folder_files): """ Retrieves pack integration image and integration display name and returns binding image data. Args: root (str): full path to the target folder to search integration image. target_folder_files (list): list of files inside the targeted folder. Returns: dict: path to integration image and display name of the integration. """ image_data = {} for pack_file in target_folder_files: if pack_file.startswith('.'): continue if pack_file.endswith('_image.png'): image_data['repo_image_path'] = os.path.join(root, pack_file) elif pack_file.endswith('.yml'): with open(os.path.join(root, pack_file), 'r') as integration_file: integration_yml = yaml.safe_load(integration_file) image_data['display_name'] = integration_yml.get('display', '') return image_data def _get_image_data_from_yml(self, pack_file_path): """ Creates temporary image file and retrieves integration display name. Args: pack_file_path (str): full path to the target yml_path integration yml to search integration image. Returns: dict: path to temporary integration image, display name of the integrations and the basename of the integration in content_pack.zip. """ image_data = {} if pack_file_path.endswith('.yml'): with open(pack_file_path, 'r') as integration_file: integration_yml = yaml.safe_load(integration_file) image_data['display_name'] = integration_yml.get('display', '') # create temporary file of base64 decoded data integration_name = integration_yml.get('name', '') base64_image = integration_yml['image'].split(',')[1] if integration_yml.get('image') else None if not base64_image: logging.warning(f"{integration_name} integration image was not found in {self._pack_name} pack") return {} temp_image_name = f'{integration_name.replace(" ", "")}_image.png' temp_image_path = os.path.join(self._pack_path, temp_image_name) with open(temp_image_path, 'wb') as image_file: image_file.write(base64.b64decode(base64_image)) self._remove_files_list.append(temp_image_name) # add temporary file to tracking list image_data['image_path'] = temp_image_path image_data['integration_path_basename'] = os.path.basename(pack_file_path) logging.info(f"Created temporary integration {image_data['display_name']} image for {self._pack_name} pack") return image_data def _search_for_images(self, target_folder): """ Searches for png files in targeted folder. Args: target_folder (str): full path to directory to search. Returns: list: list of dictionaries that include image path and display name of integration, example: [{'image_path': image_path, 'display_name': integration_display_name},...] """ target_folder_path = os.path.join(self._pack_path, target_folder) images_list = [] if os.path.exists(target_folder_path): for pack_item in os.scandir(target_folder_path): image_data = self._get_image_data_from_yml(pack_item.path) if image_data and image_data not in images_list: images_list.append(image_data) return images_list def check_if_exists_in_index(self, index_folder_path): """ Checks if pack is sub-folder of downloaded index. Args: index_folder_path (str): index folder full path. Returns: bool: whether the operation succeeded. bool: whether pack exists in index folder. """ task_status, exists_in_index = False, False try: if not os.path.exists(index_folder_path): logging.error(f"{GCPConfig.INDEX_NAME} does not exists.") return task_status, exists_in_index exists_in_index = os.path.exists(os.path.join(index_folder_path, self._pack_name)) task_status = True except Exception: logging.exception(f"Failed searching {self._pack_name} pack in {GCPConfig.INDEX_NAME}") finally: return task_status, exists_in_index @staticmethod def remove_contrib_suffix_from_name(display_name: str) -> str: """ Removes the contribution details suffix from the integration's display name Args: display_name (str): The integration display name. Returns: str: The display name without the contrib details suffix """ contribution_suffixes = ('(Partner Contribution)', '(Developer Contribution)', '(Community Contribution)') for suffix in contribution_suffixes: index = display_name.find(suffix) if index != -1: display_name = display_name[:index].rstrip(' ') break return display_name @staticmethod def need_to_upload_integration_image(image_data: dict, integration_dirs: list, unified_integrations: list): """ Checks whether needs to upload the integration image or not. We upload in one of the two cases: 1. The integration_path_basename is one of the integration dirs detected 2. The integration_path_basename is one of the added/modified unified integrations Args: image_data (dict): path to temporary integration image, display name of the integrations and the basename of the integration in content_pack.zip. integration_dirs (list): The list of integrations to search in for images unified_integrations (list): The list of unified integrations to upload their image Returns: bool: True if we need to upload the image or not """ integration_path_basename = image_data['integration_path_basename'] return any([ re.findall(BucketUploadFlow.INTEGRATION_DIR_REGEX, integration_path_basename)[0] in integration_dirs, integration_path_basename in unified_integrations ]) def upload_integration_images(self, storage_bucket, storage_base_path, diff_files_list=None, detect_changes=False): """ Uploads pack integrations images to gcs. The returned result of integration section are defined in issue #19786. Args: storage_bucket (google.cloud.storage.bucket.Bucket): google storage bucket where image will be uploaded. storage_base_path (str): The target destination of the upload in the target bucket. detect_changes (bool): Whether to detect changes or upload all images in any case. diff_files_list (list): The list of all modified/added files found in the diff Returns: bool: whether the operation succeeded. list: list of dictionaries with uploaded pack integration images. """ task_status = True integration_images = [] integration_dirs = [] unified_integrations = [] try: if detect_changes: # detect added/modified integration images for file in diff_files_list: if self.is_integration_image(file.a_path): # integration dir name will show up in the unified integration file path in content_packs.zip integration_dirs.append(os.path.basename(os.path.dirname(file.a_path))) elif self.is_unified_integration(file.a_path): # if the file found in the diff is a unified integration we upload its image unified_integrations.append(os.path.basename(file.a_path)) pack_local_images = self._search_for_images(target_folder=PackFolders.INTEGRATIONS.value) if not pack_local_images: return True # return empty list if no images were found pack_storage_root_path = os.path.join(storage_base_path, self._pack_name) for image_data in pack_local_images: image_path = image_data.get('image_path') if not image_path: raise Exception(f"{self._pack_name} pack integration image was not found") image_name = os.path.basename(image_path) image_storage_path = os.path.join(pack_storage_root_path, image_name) pack_image_blob = storage_bucket.blob(image_storage_path) if not detect_changes or \ self.need_to_upload_integration_image(image_data, integration_dirs, unified_integrations): # upload the image if needed logging.info(f"Uploading image: {image_name} of integration: {image_data.get('display_name')} " f"from pack: {self._pack_name}") with open(image_path, "rb") as image_file: pack_image_blob.upload_from_file(image_file) self._uploaded_integration_images.append(image_name) if GCPConfig.USE_GCS_RELATIVE_PATH: image_gcs_path = urllib.parse.quote( os.path.join(GCPConfig.IMAGES_BASE_PATH, self._pack_name, image_name)) else: image_gcs_path = pack_image_blob.public_url integration_name = image_data.get('display_name', '') if self.support_type != Metadata.XSOAR_SUPPORT: integration_name = self.remove_contrib_suffix_from_name(integration_name) integration_images.append({ 'name': integration_name, 'imagePath': image_gcs_path }) if self._uploaded_integration_images: logging.info(f"Uploaded {len(self._uploaded_integration_images)} images for {self._pack_name} pack.") except Exception as e: task_status = False logging.exception(f"Failed to upload {self._pack_name} pack integration images. Additional Info: {str(e)}") finally: self._displayed_integration_images = integration_images return task_status def copy_integration_images(self, production_bucket, build_bucket, images_data, storage_base_path, build_bucket_base_path): """ Copies all pack's integration images from the build bucket to the production bucket Args: production_bucket (google.cloud.storage.bucket.Bucket): The production bucket build_bucket (google.cloud.storage.bucket.Bucket): The build bucket images_data (dict): The images data structure from Prepare Content step storage_base_path (str): The target destination of the upload in the target bucket. build_bucket_base_path (str): The path of the build bucket in gcp. Returns: bool: Whether the operation succeeded. """ task_status = True num_copied_images = 0 err_msg = f"Failed copying {self._pack_name} pack integrations images." pc_uploaded_integration_images = images_data.get(self._pack_name, {}).get(BucketUploadFlow.INTEGRATIONS, []) for image_name in pc_uploaded_integration_images: build_bucket_image_path = os.path.join(build_bucket_base_path, self._pack_name, image_name) build_bucket_image_blob = build_bucket.blob(build_bucket_image_path) if not build_bucket_image_blob.exists(): logging.error(f"Found changed/added integration image {image_name} in content repo but " f"{build_bucket_image_path} does not exist in build bucket") task_status = False else: logging.info(f"Copying {self._pack_name} pack integration image: {image_name}") try: copied_blob = build_bucket.copy_blob( blob=build_bucket_image_blob, destination_bucket=production_bucket, new_name=os.path.join(storage_base_path, self._pack_name, image_name) ) if not copied_blob.exists(): logging.error(f"Copy {self._pack_name} integration image: {build_bucket_image_blob.name} " f"blob to {copied_blob.name} blob failed.") task_status = False else: num_copied_images += 1 except Exception as e: logging.exception(f"{err_msg}. Additional Info: {str(e)}") return False if not task_status: logging.error(err_msg) else: if num_copied_images == 0: logging.info(f"No added/modified integration images were detected in {self._pack_name} pack.") else: logging.success(f"Copied {num_copied_images} images for {self._pack_name} pack.") return task_status def upload_author_image(self, storage_bucket, storage_base_path, diff_files_list=None, detect_changes=False): """ Uploads pack author image to gcs. Searches for `Author_image.png` and uploads author image to gcs. In case no such image was found, default Base pack image path is used and it's gcp path is returned. Args: storage_bucket (google.cloud.storage.bucket.Bucket): gcs bucket where author image will be uploaded. storage_base_path (str): the path under the bucket to upload to. diff_files_list (list): The list of all modified/added files found in the diff detect_changes (bool): Whether to detect changes or upload the author image in any case. Returns: bool: whether the operation succeeded. str: public gcp path of author image. """ task_status = True author_image_storage_path = "" try: author_image_path = os.path.join(self._pack_path, Pack.AUTHOR_IMAGE_NAME) # disable-secrets-detection if os.path.exists(author_image_path): image_to_upload_storage_path = os.path.join(storage_base_path, self._pack_name, Pack.AUTHOR_IMAGE_NAME) # disable-secrets-detection pack_author_image_blob = storage_bucket.blob(image_to_upload_storage_path) if not detect_changes or any(self.is_author_image(file.a_path) for file in diff_files_list): # upload the image if needed with open(author_image_path, "rb") as author_image_file: pack_author_image_blob.upload_from_file(author_image_file) self._uploaded_author_image = True logging.success(f"Uploaded successfully {self._pack_name} pack author image") if GCPConfig.USE_GCS_RELATIVE_PATH: author_image_storage_path = urllib.parse.quote( os.path.join(GCPConfig.IMAGES_BASE_PATH, self._pack_name, Pack.AUTHOR_IMAGE_NAME)) else: author_image_storage_path = pack_author_image_blob.public_url elif self.support_type == Metadata.XSOAR_SUPPORT: # use default Base pack image for xsoar supported packs author_image_storage_path = os.path.join(GCPConfig.IMAGES_BASE_PATH, GCPConfig.BASE_PACK, Pack.AUTHOR_IMAGE_NAME) # disable-secrets-detection if not GCPConfig.USE_GCS_RELATIVE_PATH: # disable-secrets-detection-start author_image_storage_path = os.path.join(GCPConfig.GCS_PUBLIC_URL, storage_bucket.name, author_image_storage_path) # disable-secrets-detection-end logging.info((f"Skipping uploading of {self._pack_name} pack author image " f"and use default {GCPConfig.BASE_PACK} pack image")) else: logging.info(f"Skipping uploading of {self._pack_name} pack author image. " f"The pack is defined as {self.support_type} support type") except Exception: logging.exception(f"Failed uploading {self._pack_name} pack author image.") task_status = False author_image_storage_path = "" finally: self._author_image = author_image_storage_path return task_status def copy_author_image(self, production_bucket, build_bucket, images_data, storage_base_path, build_bucket_base_path): """ Copies pack's author image from the build bucket to the production bucket Searches for `Author_image.png`, In case no such image was found, default Base pack image path is used and it's gcp path is returned. Args: production_bucket (google.cloud.storage.bucket.Bucket): The production bucket build_bucket (google.cloud.storage.bucket.Bucket): The build bucket images_data (dict): The images data structure from Prepare Content step storage_base_path (str): The target destination of the upload in the target bucket. build_bucket_base_path (str): The path of the build bucket in gcp. Returns: bool: Whether the operation succeeded. """ if images_data.get(self._pack_name, {}).get(BucketUploadFlow.AUTHOR, False): build_author_image_path = os.path.join(build_bucket_base_path, self._pack_name, Pack.AUTHOR_IMAGE_NAME) build_author_image_blob = build_bucket.blob(build_author_image_path) if build_author_image_blob.exists(): try: copied_blob = build_bucket.copy_blob( blob=build_author_image_blob, destination_bucket=production_bucket, new_name=os.path.join(storage_base_path, self._pack_name, Pack.AUTHOR_IMAGE_NAME)) if not copied_blob.exists(): logging.error(f"Failed copying {self._pack_name} pack author image.") return False else: logging.success(f"Copied successfully {self._pack_name} pack author image.") return True except Exception as e: logging.exception(f"Failed copying {Pack.AUTHOR_IMAGE_NAME} for {self._pack_name} pack. " f"Additional Info: {str(e)}") return False else: logging.error(f"Found changed/added author image in content repo for {self._pack_name} pack but " f"image does not exist in build bucket in path {build_author_image_path}.") return False else: logging.info(f"No added/modified author image was detected in {self._pack_name} pack.") return True def upload_images(self, index_folder_path, storage_bucket, storage_base_path, diff_files_list): """ Upload the images related to the pack. The image is uploaded in the case it was modified, OR if this is the first time the current pack is being uploaded to this current marketplace (#46785). Args: index_folder_path (str): the path to the local index folder storage_bucket (google.cloud.storage.bucket.Bucket): gcs bucket where author image will be uploaded. storage_base_path (str): the path under the bucket to upload to. diff_files_list (list): The list of all modified/added files found in the diff Returns: True if the images were successfully uploaded, false otherwise. """ detect_changes = os.path.exists(os.path.join(index_folder_path, self.name, Pack.METADATA)) or self.hidden # Don't check if the image was modified if this is the first time it is uploaded to this marketplace, meaning it # doesn't exist in the index (and it isn't deprecated) if not detect_changes: logging.info(f'Uploading images of pack {self.name} which did not exist in this marketplace before') task_status = self.upload_integration_images(storage_bucket, storage_base_path, diff_files_list, detect_changes) if not task_status: self._status = PackStatus.FAILED_IMAGES_UPLOAD.name self.cleanup() return False task_status = self.upload_author_image(storage_bucket, storage_base_path, diff_files_list, detect_changes) if not task_status: self._status = PackStatus.FAILED_AUTHOR_IMAGE_UPLOAD.name self.cleanup() return False return True def cleanup(self): """ Finalization action, removes extracted pack folder. """ if os.path.exists(self._pack_path): shutil.rmtree(self._pack_path) logging.info(f"Cleanup {self._pack_name} pack from: {self._pack_path}") def is_changelog_exists(self): """ Indicates whether the local changelog of a given pack exists or not Returns: bool: The answer """ return os.path.isfile(os.path.join(self._pack_path, Pack.CHANGELOG_JSON)) def is_failed_to_upload(self, failed_packs_dict): """ Checks if the pack was failed to upload in Prepare Content step in Create Instances job Args: failed_packs_dict (dict): The failed packs file Returns: bool: Whether the operation succeeded. str: The pack's failing status """ if self._pack_name in failed_packs_dict: return True, failed_packs_dict[self._pack_name].get('status') else: return False, str() def is_integration_image(self, file_path: str): """ Indicates whether a file_path is an integration image or not Args: file_path (str): The file path Returns: bool: True if the file is an integration image or False otherwise """ return all([ file_path.startswith(os.path.join(PACKS_FOLDER, self._pack_name)), file_path.endswith('.png'), 'image' in os.path.basename(file_path.lower()), os.path.basename(file_path) != Pack.AUTHOR_IMAGE_NAME ]) def is_author_image(self, file_path: str): """ Indicates whether a file_path is an author image or not Args: file_path (str): The file path Returns: bool: True if the file is an author image or False otherwise """ return file_path == os.path.join(PACKS_FOLDER, self._pack_name, Pack.AUTHOR_IMAGE_NAME) def is_unified_integration(self, file_path: str): """ Indicates whether a file_path is a unified integration yml file or not Args: file_path (str): The file path Returns: bool: True if the file is a unified integration or False otherwise """ return all([ file_path.startswith(os.path.join(PACKS_FOLDER, self._pack_name, PackFolders.INTEGRATIONS.value)), os.path.basename(os.path.dirname(file_path)) == PackFolders.INTEGRATIONS.value, os.path.basename(file_path).startswith('integration'), os.path.basename(file_path).endswith('.yml') ]) def add_bc_entries_if_needed(self, release_notes_dir: str, changelog: Dict[str, Any]) -> None: """ Receives changelog, checks if there exists a BC version in each changelog entry (as changelog entry might be zipped into few RN versions, check if at least one of the versions is BC). Check if RN is BC is done by doing the following: 1) Check if RN has corresponding config file, e.g 1_0_1.md has corresponding 1_0_1.json file. 2) If it does, check if `isBreakingChanges` field is true If such version exists, adds a true value to 'breakingChanges' field. if JSON file also has breakingChangesNotes configures, adds `breakingChangesNotes` field to changelog file. This function iterates every entry in changelog because it takes into consideration four scenarios: a) Entry without breaking changes, changes to entry with breaking changes (because at least one of the versions in the entry was marked as breaking changes). b) Entry without breaking changes, does not change. c) Entry with breaking changes, changes to entry without breaking changes (because all the BC versions corresponding to the changelog entry were re-marked as not BC). d) Entry with breaking changes, does not change. Args: release_notes_dir (str): RN dir path. changelog (Dict[str, Any]): Changelog data represented as a dict. Returns: (None): Modifies changelog, adds bool value to 'breakingChanges' and `breakingChangesNotes` fields to every changelog entry, according to the logic described above. """ if not os.path.exists(release_notes_dir): return bc_version_to_text: Dict[str, Optional[str]] = self._breaking_changes_versions_to_text(release_notes_dir) loose_versions: List[Version] = [Version(bc_ver) for bc_ver in bc_version_to_text] predecessor_version: Version = Version('0.0.0') for changelog_entry in sorted(changelog.keys(), key=Version): rn_loose_version: Version = Version(changelog_entry) if bc_versions := self._changelog_entry_bc_versions(predecessor_version, rn_loose_version, loose_versions, bc_version_to_text): logging.info(f'Changelog entry {changelog_entry} contains BC versions') changelog[changelog_entry]['breakingChanges'] = True if bc_text := self._calculate_bc_text(release_notes_dir, bc_versions): changelog[changelog_entry]['breakingChangesNotes'] = bc_text else: changelog[changelog_entry].pop('breakingChangesNotes', None) else: changelog[changelog_entry].pop('breakingChanges', None) predecessor_version = rn_loose_version def _calculate_bc_text(self, release_notes_dir: str, bc_version_to_text: Dict[str, Optional[str]]) -> Optional[str]: """ Receives BC versions to text dict for current changelog entry. Calculates text for BC entry. Args: release_notes_dir (str): RN dir path. bc_version_to_text (Dict[str, Optional[str]): {bc version, bc_text} Returns: (Optional[str]): Text for entry if such was added. If none is returned, server will list the full RN as the BC notes instead. """ # Handle cases of one BC version in entry. if len(bc_version_to_text) == 1: return list(bc_version_to_text.values())[0] # Handle cases of two or more BC versions in entry. text_of_bc_versions, bc_without_text = self._split_bc_versions_with_and_without_text(bc_version_to_text) if len(text_of_bc_versions) == 0: # Case 1: Not even one BC version contains breaking text. return None elif len(text_of_bc_versions) < len(bc_version_to_text): # Case 2: Only part of BC versions contains breaking text. return self._handle_many_bc_versions_some_with_text(release_notes_dir, text_of_bc_versions, bc_without_text) else: # Case 3: All BC versions contains text. # Important: Currently, implementation of aggregating BCs was decided to concat between them # In the future this might be needed to re-thought. return '\n'.join(bc_version_to_text.values()) # type: ignore[arg-type] def _handle_many_bc_versions_some_with_text(self, release_notes_dir: str, text_of_bc_versions: List[str], bc_versions_without_text: List[str], ) -> str: """ Calculates text for changelog entry where some BC versions contain text and some don't. Important: Currently, implementation of aggregating BCs was decided to concat between them (and if BC version does not have a BC text - concat the whole RN). In the future this might be needed to re-thought. Args: release_notes_dir (str): RN dir path. text_of_bc_versions ([List[str]): List of text of BC versions with text. bc_versions_without_text ([List[str]): List of BC versions without text. Returns: (str): Text for BC entry. """ bc_with_text_str = '\n'.join(text_of_bc_versions) rn_file_names_without_text = [f'''{bc_version.replace('.', '_')}.md''' for bc_version in bc_versions_without_text] other_rn_text: str = self._get_release_notes_concat_str(release_notes_dir, rn_file_names_without_text) if not other_rn_text: logging.error('No RN text, although text was expected to be found for versions' f' {rn_file_names_without_text}.') return f'{bc_with_text_str}{other_rn_text}' @staticmethod def _get_release_notes_concat_str(release_notes_dir: str, rn_file_names: List[str]) -> str: """ Concat all RN data found in given `rn_file_names`. Args: release_notes_dir (str): RN dir path. rn_file_names (List[str]): List of all RN files to concat their data. Returns: (str): Concat RN data """ concat_str: str = '' for rn_file_name in rn_file_names: rn_file_path = os.path.join(release_notes_dir, rn_file_name) with open(rn_file_path, 'r') as f: # Will make the concat string start with new line on purpose. concat_str = f'{concat_str}\n{f.read()}' return concat_str @staticmethod def _split_bc_versions_with_and_without_text(bc_versions: Dict[str, Optional[str]]) -> Tuple[List[str], List[str]]: """ Splits BCs to tuple of BCs text of BCs containing text, and BCs versions that do not contain BC text. Args: bc_versions (Dict[str, Optional[str]): BC versions mapped to text if exists. Returns: (Tuple[List[str], List[str]]): (text of bc versions with text, bc_versions_without_text). """ text_of_bc_versions_with_tests: List[str] = [] bc_versions_without_text: List[str] = [] for bc_version, bc_text in bc_versions.items(): if bc_text: text_of_bc_versions_with_tests.append(bc_text) else: bc_versions_without_text.append(bc_version) return text_of_bc_versions_with_tests, bc_versions_without_text @staticmethod def _breaking_changes_versions_to_text(release_notes_dir: str) -> Dict[str, Optional[str]]: """ Calculates every BC version in given RN dir and maps it to text if exists. Currently, text from a BC version is calculated in the following way: - If RN has `breakingChangesNotes` entry in its corresponding config file, then use the value of that field as the text of the BC to be represented. - Else, use the whole RN text as BC text. Args: release_notes_dir (str): RN dir path. Returns: (Dict[str, Optional[str]]): {dotted_version, text}. """ bc_version_to_text: Dict[str, Optional[str]] = dict() # Get all config files in RN dir rn_config_file_names = filter_dir_files_by_extension(release_notes_dir, '.json') for file_name in rn_config_file_names: file_data: Dict = load_json(os.path.join(release_notes_dir, file_name)) # Check if version is BC if file_data.get('breakingChanges'): # Processing name for easier calculations later on processed_name: str = underscore_file_name_to_dotted_version(file_name) bc_version_to_text[processed_name] = file_data.get('breakingChangesNotes') return bc_version_to_text @staticmethod def _changelog_entry_bc_versions(predecessor_version: Version, rn_version: Version, breaking_changes_versions: List[Version], bc_version_to_text: Dict[str, Optional[str]]) -> Dict[str, Optional[str]]: """ Gets all BC versions of given changelog entry, every BC s.t predecessor_version < BC version <= rn_version. Args: predecessor_version (Version): Predecessor version in numeric version order. rn_version (Version): RN version of current processed changelog entry. breaking_changes_versions (List[Version]): List of BC versions. bc_version_to_text (Dict[str, Optional[str]): List of all BC to text in the given RN dir. Returns: Dict[str, Optional[str]]: Partial list of `bc_version_to_text`, containing only relevant versions between given versions. """ return {str(bc_ver): bc_version_to_text.get(str(bc_ver)) for bc_ver in breaking_changes_versions if predecessor_version < bc_ver <= rn_version} # HELPER FUNCTIONS def get_upload_data(packs_results_file_path: str, stage: str) -> Tuple[dict, dict, dict, dict]: """ Loads the packs_results.json file to get the successful and failed packs together with uploaded images dicts Args: packs_results_file_path (str): The path to the file stage (str): can be BucketUploadFlow.PREPARE_CONTENT_FOR_TESTING or BucketUploadFlow.UPLOAD_PACKS_TO_MARKETPLACE_STORAGE Returns: dict: The successful packs dict dict: The failed packs dict dict : The successful private packs dict dict: The images data dict """ if os.path.exists(packs_results_file_path): packs_results_file = load_json(packs_results_file_path) stage_data: dict = packs_results_file.get(stage, {}) successful_packs_dict = stage_data.get(BucketUploadFlow.SUCCESSFUL_PACKS, {}) failed_packs_dict = stage_data.get(BucketUploadFlow.FAILED_PACKS, {}) successful_private_packs_dict = stage_data.get(BucketUploadFlow.SUCCESSFUL_PRIVATE_PACKS, {}) images_data_dict = stage_data.get(BucketUploadFlow.IMAGES, {}) return successful_packs_dict, failed_packs_dict, successful_private_packs_dict, images_data_dict return {}, {}, {}, {} def store_successful_and_failed_packs_in_ci_artifacts(packs_results_file_path: str, stage: str, successful_packs: list, failed_packs: list, updated_private_packs: list, images_data: dict = None): """ Write the successful and failed packs to the correct section in the packs_results.json file Args: packs_results_file_path (str): The path to the pack_results.json file stage (str): can be BucketUploadFlow.PREPARE_CONTENT_FOR_TESTING or BucketUploadFlow.UPLOAD_PACKS_TO_MARKETPLACE_STORAGE successful_packs (list): The list of all successful packs failed_packs (list): The list of all failed packs updated_private_packs (list) : The list of all private packs that were updated images_data (dict): A dict containing all images that were uploaded for each pack """ packs_results = load_json(packs_results_file_path) packs_results[stage] = dict() if failed_packs: failed_packs_dict = { BucketUploadFlow.FAILED_PACKS: { pack.name: { BucketUploadFlow.STATUS: pack.status, BucketUploadFlow.AGGREGATED: pack.aggregation_str if pack.aggregated and pack.aggregation_str else "False" } for pack in failed_packs } } packs_results[stage].update(failed_packs_dict) logging.debug(f"Failed packs {failed_packs_dict}") if successful_packs: successful_packs_dict = { BucketUploadFlow.SUCCESSFUL_PACKS: { pack.name: { BucketUploadFlow.STATUS: pack.status, BucketUploadFlow.AGGREGATED: pack.aggregation_str if pack.aggregated and pack.aggregation_str else "False", BucketUploadFlow.LATEST_VERSION: pack.latest_version } for pack in successful_packs } } packs_results[stage].update(successful_packs_dict) logging.debug(f"Successful packs {successful_packs_dict}") if updated_private_packs: successful_private_packs_dict: dict = { BucketUploadFlow.SUCCESSFUL_PRIVATE_PACKS: {pack_name: {} for pack_name in updated_private_packs} } packs_results[stage].update(successful_private_packs_dict) logging.debug(f"Successful private packs {successful_private_packs_dict}") if images_data: packs_results[stage].update({BucketUploadFlow.IMAGES: images_data}) logging.debug(f"Images data {images_data}") if packs_results: json_write(packs_results_file_path, packs_results) def load_json(file_path: str) -> dict: """ Reads and loads json file. Args: file_path (str): full path to json file. Returns: dict: loaded json file. """ try: if file_path and os.path.exists(file_path): with open(file_path, 'r') as json_file: result = json.load(json_file) else: result = {} return result except json.decoder.JSONDecodeError: return {} def json_write(file_path: str, data: Union[list, dict]): """ Writes given data to a json file Args: file_path: The file path data: The data to write """ with open(file_path, "w") as f: f.write(json.dumps(data, indent=4)) def init_storage_client(service_account=None): """Initialize google cloud storage client. In case of local dev usage the client will be initialized with user default credentials. Otherwise, client will be initialized from service account json that is stored in CircleCI. Args: service_account (str): full path to service account json. Return: storage.Client: initialized google cloud storage client. """ if service_account: storage_client = storage.Client.from_service_account_json(service_account) logging.info("Created gcp service account") return storage_client else: # in case of local dev use, ignored the warning of non use of service account. warnings.filterwarnings("ignore", message=google.auth._default._CLOUD_SDK_CREDENTIALS_WARNING) credentials, project = google.auth.default() storage_client = storage.Client(credentials=credentials, project=project) logging.info("Created gcp private account") return storage_client def input_to_list(input_data, capitalize_input=False): """ Helper function for handling input list or str from the user. Args: input_data (list or str): input from the user to handle. capitalize_input (boo): whether to capitalize the input list data or not. Returns: list: returns the original list or list that was split by comma. """ input_data = input_data if input_data else [] input_data = input_data if isinstance(input_data, list) else [s for s in input_data.split(',') if s] if capitalize_input: return [" ".join([w.title() if w.islower() else w for w in i.split()]) for i in input_data] else: return input_data def get_valid_bool(bool_input): """ Converts and returns valid bool. Returns: bool: converted bool input. """ return bool(strtobool(bool_input)) if isinstance(bool_input, str) else bool_input def convert_price(pack_id, price_value_input=None): """ Converts to integer value price input. In case no price input provided, return zero as price. Args: pack_id (str): pack unique identifier. price_value_input (str): price string to convert. Returns: int: converted to int pack price. """ try: if not price_value_input: return 0 # in case no price was supported, return 0 else: return int(price_value_input) # otherwise convert to int and return result except Exception: logging.exception(f"{pack_id} pack price is not valid. The price was set to 0.") return 0 def get_updated_server_version(current_string_version, compared_content_item, pack_name): """ Compares two semantic server versions and returns the higher version between them. Args: current_string_version (str): current string version. compared_content_item (dict): compared content item entity. pack_name (str): the pack name (id). Returns: str: latest version between compared versions. """ lower_version_result = current_string_version try: compared_string_version = compared_content_item.get('fromversion') or compared_content_item.get( 'fromVersion') or "99.99.99" current_version, compared_version = Version(current_string_version), Version(compared_string_version) if current_version > compared_version: lower_version_result = compared_string_version except Exception: content_item_name = compared_content_item.get('name') or compared_content_item.get( 'display') or compared_content_item.get('id') or compared_content_item.get('details', '') logging.exception(f"{pack_name} failed in version comparison of content item {content_item_name}.") finally: return lower_version_result def get_content_git_client(content_repo_path: str): """ Initializes content repo client. Args: content_repo_path (str): content repo full path Returns: git.repo.base.Repo: content repo object. """ return git.Repo(content_repo_path) def get_recent_commits_data(content_repo: Any, index_folder_path: str, is_bucket_upload_flow: bool, is_private_build: bool = False, circle_branch: str = "master"): """ Returns recent commits hashes (of head and remote master) Args: content_repo (git.repo.base.Repo): content repo object. index_folder_path (str): the path to the local index folder is_bucket_upload_flow (bool): indicates whether its a run of bucket upload flow or regular build is_private_build (bool): indicates whether its a run of private build or not circle_branch (str): CircleCi branch of current build Returns: str: last commit hash of head. str: previous commit depending on the flow the script is running """ return content_repo.head.commit.hexsha, get_previous_commit(content_repo, index_folder_path, is_bucket_upload_flow, is_private_build, circle_branch) def get_previous_commit(content_repo, index_folder_path, is_bucket_upload_flow, is_private_build, circle_branch): """ If running in bucket upload workflow we want to get the commit in the index which is the index We've last uploaded to production bucket. Otherwise, we are in a commit workflow and the diff should be from the head of origin/master Args: content_repo (git.repo.base.Repo): content repo object. index_folder_path (str): the path to the local index folder is_bucket_upload_flow (bool): indicates whether its a run of bucket upload flow or regular build is_private_build (bool): indicates whether its a run of private build or not circle_branch (str): CircleCi branch of current build Returns: str: previous commit depending on the flow the script is running """ if is_bucket_upload_flow: return get_last_upload_commit_hash(content_repo, index_folder_path) elif is_private_build: previous_master_head_commit = content_repo.commit('origin/master~1').hexsha logging.info(f"Using origin/master HEAD~1 commit hash {previous_master_head_commit} to diff with.") return previous_master_head_commit else: if circle_branch == 'master': head_str = "HEAD~1" # if circle branch is master than current commit is origin/master HEAD, so we need to diff with HEAD~1 previous_master_head_commit = content_repo.commit('origin/master~1').hexsha else: head_str = "HEAD" # else we are on a regular branch and the diff should be done with origin/master HEAD previous_master_head_commit = content_repo.commit('origin/master').hexsha logging.info(f"Using origin/master {head_str} commit hash {previous_master_head_commit} to diff with.") return previous_master_head_commit def get_last_upload_commit_hash(content_repo, index_folder_path): """ Returns the last origin/master commit hash that was uploaded to the bucket Args: content_repo (git.repo.base.Repo): content repo object. index_folder_path: The path to the index folder Returns: The commit hash """ inner_index_json_path = os.path.join(index_folder_path, f'{GCPConfig.INDEX_NAME}.json') if not os.path.exists(inner_index_json_path): logging.critical(f"{GCPConfig.INDEX_NAME}.json not found in {GCPConfig.INDEX_NAME} folder") sys.exit(1) else: inner_index_json_file = load_json(inner_index_json_path) if 'commit' in inner_index_json_file: last_upload_commit_hash = inner_index_json_file['commit'] logging.info(f"Retrieved the last commit that was uploaded to production: {last_upload_commit_hash}") else: logging.critical(f"No commit field in {GCPConfig.INDEX_NAME}.json, content: {str(inner_index_json_file)}") sys.exit(1) try: last_upload_commit = content_repo.commit(last_upload_commit_hash).hexsha logging.info(f"Using commit hash {last_upload_commit} from index.json to diff with.") return last_upload_commit except Exception as e: logging.critical(f'Commit {last_upload_commit_hash} in {GCPConfig.INDEX_NAME}.json does not exist in content ' f'repo. Additional info:\n {e}') sys.exit(1) def is_ignored_pack_file(modified_file_path_parts): """ Indicates whether a pack file needs to be ignored or not. Args: modified_file_path_parts: The modified file parts, e.g. if file path is "a/b/c" then the parts list is ["a", "b", "c"] Returns: (bool): True if the file should be ignored, False otherwise """ for file_suffix in PackIgnored.ROOT_FILES: if file_suffix in modified_file_path_parts: return True for pack_folder, file_suffixes in PackIgnored.NESTED_FILES.items(): if pack_folder in modified_file_path_parts: if not file_suffixes: # Ignore all pack folder files return True for file_suffix in file_suffixes: if file_suffix in modified_file_path_parts[-1]: return True for pack_folder in PackIgnored.NESTED_DIRS: if pack_folder in modified_file_path_parts: pack_folder_path = os.sep.join(modified_file_path_parts[:modified_file_path_parts.index(pack_folder) + 1]) file_path = os.sep.join(modified_file_path_parts) for folder_path in [f for f in glob.glob(os.path.join(pack_folder_path, '*/*')) if os.path.isdir(f)]: # Checking for all 2nd level directories. e.g. test_data directory if file_path.startswith(folder_path): return True return False def filter_dir_files_by_extension(release_notes_dir: str, extension: str) -> List[str]: """ Receives path to RN dir, filters only files in RN dir corresponding to the extension. Needed because RN directory will be extended to contain JSON files for configurations, see 'release_notes_bc_calculator.py' Args: release_notes_dir (str): Path to RN dir extension (str): Extension to filter by. Returns: (List[str]): List of all of the files in directory corresponding to the extension. """ return [file_name for file_name in os.listdir(release_notes_dir) if file_name.endswith(extension)] def is_the_only_rn_in_block(release_notes_dir: str, version: str, changelog: dict): """ Check if the given version is a key of an aggregated changelog block, as in its value in the changelog doesn't contains other release notes that have been aggregated in previous uploads. If that is the case, the adjacent previous release note in the changelog will be equal to the one in the release notes directory, and false otherwise (meaning there are versions in the release notes directory that are missing in the changelog, therefore they have been aggregated) and this function asserts that. Note: The comparison is done against the release notes directory to avoid cases where there are missing versions in the changelog due to inconsistent versions numbering, such as major version bumps. (For example, if the versions 1.2.7 and 1.3.0 are two consecutive keys in the changelog, we need to determine if 1.3.0 has aggregated the versions 1.2.8-1.3.0, OR 1.3.0 is the consecutive version right after 1.2.7 but is a major bump. in order to check that, we check it against the files in the release notes directory.) Args: release_notes_dir: the path to the release notes dir. version (str): the wanted version. changelog (dict): the changelog from the production bucket. Returns: True if this version's value in the changelog is not an aggregated release notes block. False otherwise. """ if not changelog.get(version): return False all_rn_versions = [] lowest_version = [Version('1.0.0')] for filename in filter_dir_files_by_extension(release_notes_dir, '.md'): current_version = underscore_file_name_to_dotted_version(filename) all_rn_versions.append(Version(current_version)) lower_versions_all_versions = [item for item in all_rn_versions if item < Version(version)] + lowest_version lower_versions_in_changelog = [Version(item) for item in changelog.keys() if Version(item) < Version(version)] + lowest_version return max(lower_versions_all_versions) == max(lower_versions_in_changelog) def underscore_file_name_to_dotted_version(file_name: str) -> str: """ Receives file name with expected format of x_x_x<extension>, and transforms it to dotted string. Examples - underscore_file_name_to_dotted_version(1_2_3.md) --> 1.2.3 - underscore_file_name_to_dotted_version(1_4_2.json) --> 1.4.2 Args: file_name (str): File name. Returns: (str): Dotted version of file name """ return os.path.splitext(file_name)[0].replace('_', '.') def get_last_commit_from_index(service_account): """ Downloading index.json from GCP and extract last upload commit. Args: service_account: service account to connect to GCP Returns: last upload commit. """ storage_client = init_storage_client(service_account) storage_bucket = storage_client.bucket(GCPConfig.PRODUCTION_BUCKET) index_storage_path = os.path.join('content/packs/', f"{GCPConfig.INDEX_NAME}.json") index_blob = storage_bucket.blob(index_storage_path) index_string = index_blob.download_as_string() index_json = json.loads(index_string) return index_json.get('commit')
#!/usr/bin/env python3 import os from slack_sdk import WebClient from slack_sdk.errors import SlackApiError import sys import requests import json import time import datetime if __name__ == "__main__": # state_name = str(input("Enter the state name: ")) # district_name = str(input("Enter the district name: ")) # no_of_days = int(input("Enter the number of days to get appointments: ")) client = WebClient(token=os.environ["SLACK_BOT_TOKEN"]) state_name = "Maharashtra" district_name = "Pune" pincode_list = [ 411038, 411001, 411002, 411006, 411026, 411011, 412409, ] # 411026, 412409 no_of_days = 7 start_date = datetime.datetime.today().strftime("%d-%m-%Y") date_list = [] for i in range(no_of_days): date_list.append( (datetime.datetime.today() + datetime.timedelta(days=i + 1)).strftime( "%d-%m-%Y" ) ) get_states = requests.get("https://cdn-api.co-vin.in/api/v2/admin/location/states") states = get_states.json() state_id = -1 for state_dict in states["states"]: if state_dict["state_name"] == state_name: state_id = state_dict["state_id"] break if state_id == -1: print("Did not find state! Exiting! Check the spelling!") sys.exit() print("State id of {} is {}".format(state_name, state_id)) get_districts = requests.get( "https://cdn-api.co-vin.in/api/v2/admin/location/districts/" + str(state_id) ) districts = get_districts.json() district_id = -1 for district_dict in districts["districts"]: if district_dict["district_name"] == district_name: district_id = district_dict["district_id"] if district_id == -1: print("Did not find district! Exiting! Check the spelling!") sys.exit() print("District id of {} is {}".format(district_name, district_id)) appoint_payload = {"district_id": str(district_id), "date": start_date} # calender_url = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByDistrict?district_id={}&date={}".format(district_id, start_date) # print(calender_url) while 1: time_now = datetime.datetime.now() time_now = time_now.strftime("%H:%M:%S") print("Current Time: ", time_now) get_appointments = requests.get( "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByDistrict", params=appoint_payload, ) centers_list = get_appointments.json()["centers"] # temp_centers = [] # for center in centers_list: # if center["pincode"] in pincode_list: # temp_centers.append(center["name"]) # temp_centers.sort() # print(temp_centers) available_centers = [] for center in centers_list: if ( center["sessions"][0]["min_age_limit"] < 45 and center["pincode"] in pincode_list ): available_centers.append(center) # print("available_centers: ", available_centers) message_list = [] message_str = "" for center in available_centers: for session in center["sessions"]: if session["available_capacity"] > 0: message_str = ( "Center Name: " + center["name"] + "\nPincode: " + str(center["pincode"]) + "\nAvailable Capacity: " + str(session["available_capacity"]) + "\nDate: " + session["date"] + "\nVaccine: " + session["vaccine"] ) message_list.append(message_str) for message in message_list: try: response = client.chat_postMessage(channel="#cowin", text=message) except SlackApiError as e: print(f"Got an error: {e.response["error"]}") # print(message_list) time.sleep(10)
#!/usr/bin/env python3 import os from slack_sdk import WebClient from slack_sdk.errors import SlackApiError import sys import requests import json import time import datetime if __name__ == "__main__": # state_name = str(input("Enter the state name: ")) # district_name = str(input("Enter the district name: ")) # no_of_days = int(input("Enter the number of days to get appointments: ")) client = WebClient(token=os.environ["SLACK_BOT_TOKEN"]) state_name = "Maharashtra" district_name = "Pune" pincode_list = [ 411038, 411001, 411002, 411006, 411026, 411011, 412409, ] # 411026, 412409 no_of_days = 7 start_date = datetime.datetime.today().strftime("%d-%m-%Y") date_list = [] for i in range(no_of_days): date_list.append( (datetime.datetime.today() + datetime.timedelta(days=i + 1)).strftime( "%d-%m-%Y" ) ) get_states = requests.get("https://cdn-api.co-vin.in/api/v2/admin/location/states") states = get_states.json() state_id = -1 for state_dict in states["states"]: if state_dict["state_name"] == state_name: state_id = state_dict["state_id"] break if state_id == -1: print("Did not find state! Exiting! Check the spelling!") sys.exit() print("State id of {} is {}".format(state_name, state_id)) get_districts = requests.get( "https://cdn-api.co-vin.in/api/v2/admin/location/districts/" + str(state_id) ) districts = get_districts.json() district_id = -1 for district_dict in districts["districts"]: if district_dict["district_name"] == district_name: district_id = district_dict["district_id"] if district_id == -1: print("Did not find district! Exiting! Check the spelling!") sys.exit() print("District id of {} is {}".format(district_name, district_id)) appoint_payload = {"district_id": str(district_id), "date": start_date} # calender_url = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByDistrict?district_id={}&date={}".format(district_id, start_date) # print(calender_url) while 1: time_now = datetime.datetime.now() time_now = time_now.strftime("%H:%M:%S") print("Current Time: ", time_now) get_appointments = requests.get( "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByDistrict", params=appoint_payload, ) centers_list = get_appointments.json()["centers"] # temp_centers = [] # for center in centers_list: # if center["pincode"] in pincode_list: # temp_centers.append(center["name"]) # temp_centers.sort() # print(temp_centers) available_centers = [] for center in centers_list: if ( center["sessions"][0]["min_age_limit"] < 45 and center["pincode"] in pincode_list ): available_centers.append(center) # print("available_centers: ", available_centers) message_list = [] message_str = "" for center in available_centers: for session in center["sessions"]: if session["available_capacity"] > 0: message_str = ( "Center Name: " + center["name"] + "\nPincode: " + str(center["pincode"]) + "\nAvailable Capacity: " + str(session["available_capacity"]) + "\nDate: " + session["date"] + "\nVaccine: " + session["vaccine"] ) message_list.append(message_str) for message in message_list: try: response = client.chat_postMessage(channel="#cowin", text=message) except SlackApiError as e: print(f"Got an error: {e.response['error']}") # print(message_list) time.sleep(10)
import sys from awsglue.transforms import * from awsglue.utils import getResolvedOptions from pyspark.context import SparkContext from awsglue.context import GlueContext from awsglue.job import Job sc = SparkContext() glueContext = GlueContext(sc) spark = glueContext.spark_session job = Job(glueContext) job.commit() # -------------------------Glue Job housekeeping section ----------------------- import boto3 from botocore.errorfactory import ClientError from urllib.parse import urlparse import pandas as pd import pandera as pa import datetime as dt from dateutil import parser import pyarrow import pyarrow.parquet as pq import time import logging import json import copy # --------------------End of Script imports--------------------------- def setLog(e,check): """add success/fail logs to the file_list. Parameters ---------- e :[str] An exception or the string value of an exception check:[str] DQ check for which logs are being added """ log_msg = f"{check} -> {e}" file_status.append(log_msg) def setTaskVal(source,file,status,error_loc=""): """Append file status to a global df exit_status Parameters ---------- source:[str] Source file for which DQ logs are being added status:[str] Status of File DQ check (success/fail) error_loc:[str] Location of error file, if DQ check failed, blank otherwise. """ ts=dt.datetime.now() logs=copy.deepcopy(file_status) exit_status.loc[len(exit_status.index)] = [ts,layer,source,file,status,error_loc,logs] file_status.clear() return def extractBotoParams(config_path): """Extract bucket name and key from s3 path. Parameters ---------- config_path : str path of application configuration file Returns ------- pair pair with bucket name and path key. """ parsed_url = urlparse(config_path) bucket_name = parsed_url.hostname s3_path = parsed_url.path[1:] return bucket_name,s3_path def getConfig(config_path: str): """Read application configuration file into json Parameters ---------- config_path : str path of application configuration file Returns ------- dict return a json dictionary contain application configuration """ try: logger.info(f'Reading config from {config_path}') bucket_name,s3_path = extractBotoParams(config_path) obj = s3_connect.get_object(Bucket=bucket_name, Key=s3_path) config = obj['Body'].read().decode("utf-8") logger.info("Config file read successfully!") return json.loads(config) except FileNotFoundError as e: logger.exception('CONFIGURATION ERROR: Couldnt find the configuration file : ' + str(e)) raise FileNotFoundError('CONFIGURATION ERROR: Couldnt find the configuration file : ' + str(e)) except ValueError as e: if not config_path: logger.exception('CONFIGURATION ERROR: Null config path : ' + str(e)) raise ValueError('CONFIGURATION ERROR: Null config path : ' + str(e)) else: logger.exception( 'CONFIGURATION ERROR: Invalid json. Error occurred while loading configuration file : ' + str(e)) raise ValueError( 'CONFIGURATION ERROR: Invalid json. Error occurred while loading configuration file : ' + str(e)) except Exception as e: logger.exception('CONFIGURATION ERROR: Error occurred while loading configuration file : ' + str(e)) err_msg = f"{type(e).__name__} : CONFIGURATION ERROR: Error occurred while loading configuration file : {str(e)}" raise Exception(err_msg) from e def move_file(src,dest): """Method to move file between directories. If path is not a file -> return, do nothing. Args: src (str): Source path with filename dest (str): Destination path with file name """ try: s3 = boto3.resource('s3') src_bucket,src_key=extractBotoParams(src) dest_bucket,dest_key=extractBotoParams(dest) copy_source = { 'Bucket': src_bucket, 'Key': src_key } bucket = s3.Bucket(dest_bucket) obj = bucket.Object(dest_key) obj.copy(copy_source) s3.Object(src_bucket, src_key).delete() logger.info(f"{src.split("/")[-1]} moved to : {dest}") except Exception as e: msg=f"Failed to move file to {dest} due to -> {e}" logger.error(msg) raise msg #try block in main for will catch this exception and push file status to df then continue with next file. def create_dir(path): """Create a new directory, do nothing if directory exists. Args: path (string): directory path """ try: if directoryExists(path): return else: bucketname,key=extractBotoParams(path) s3_connect.put_object(Bucket=bucketname,Key=key) logger.info(f"Directory created at: {path}") except Exception as e: msg=f"Failed to create directory {path} due to -> {e}" logger.error(msg) raise msg #try block in main for will catch this exception and push file status to df then continue with next file. def directoryExists(path): """Check if directory/file exists. Note: Folder paths must end with '/' Args: path (string): directory path Returns: bool """ bucket,key = extractBotoParams(path) try: s3_connect.head_object(Bucket=bucket, Key=key) except ClientError: return False return True def emptyDir(path): file_list=listDir(path) s3 = boto3.resource('s3') bucket,key=extractBotoParams(path) print("--------------") for file in file_list: s3.Object(bucket, file).delete() msg=f"Partition {curr_dt} cleaned." logger.info(msg) def listDir(path): """List all files present in dir and return list. Args: path (string): directory path Returns: list: List of file keys. """ try: files=[] s3 = boto3.resource('s3') bucket,key=extractBotoParams(path) my_bucket = s3.Bucket(bucket) for object_summary in my_bucket.objects.filter(Prefix=key): file_key=object_summary.key if file_key[-1]!='/': files.append(file_key) return files except Exception as e: msg=f"Failed to list dir {path} due to -> {e}" logger.error(msg) raise e def perform_generic_checks(file_path): """The method performs generic file checks on the file. These include - - Csv extension check - Check is file is empty Args: file_path (str): File path on which dq checks are performed. """ try: status=True file=file_path.split("/")[-1] logger.info(f"Starting generic DQ Checks for: {file}") #DQ1: File extension check ext=file_path[-3:] if ext!=config["source_ext"]: msg=f"CSV format check failed for: {file}" logger.warning(msg) setLog(msg,"File extension check") status=False return status else: msg=f"CSV format check passed for: {file}" logger.info(msg) # setLog(msg,"File extension check") #DQ2: File Not Empty check try: df=pd.read_csv(file_path) if df.shape[0] == 0: msg=f"File Not Empty check failed for: {file}" logger.warning(msg) setLog(msg,"File Not Empty") status=False return status else: msg=f"File Not empty check passed for: {file}" logger.info(msg) # setLog(msg,"File Not Empty check") except pd.errors.EmptyDataError as e: msg=f"File Not Empty check failed for: {file}" logger.warning(msg) setLog(msg,"File Not Empty") status=False return status return status except Exception as e: print(type(e)) print(e) msg=f"Error:{e} while performing Generic DQ checks for file {file}" logger.error(msg) setLog(msg,"Generic DQ") return False def clean_schema(lst): """This method cleans the list items so that they can be compared. - Strips space - Remove trailing/leading spaces - convert to lower case Args: lst (list): List to be cleaned Returns: list : Cleaned list """ schema=[] for col in lst: col=col.lower().strip() col=" ".join(col.split()) schema.append(col) return schema def validate_ts(ts): """Check if the pandas column has all timestamp values. Args: ts: Pandas Series (col) Returns: bool """ try: for i in ts: if i == "": continue parser.parse(i) return True except ValueError as e: logger.warning(f"Not a timestamp->{e}") return False def write_to_parquet(df,path,mode): """Write file to parquet. Args: df: dataframe to write path: Path to write to mode: overwrite/append Returns: bool """ try: table_name=path.split('/')[-2] table_name=table_name+".parquet" if mode=="append": if len(listDir(path+"date_partition="+curr_dt+"/"))>0: emptyDir(path+"date_partition="+curr_dt+"/") df['date_partition'] = curr_dt df.to_parquet(path,partition_cols=['date_partition']) msg=f"Parquet data written to -> {path}" logger.info(msg) if mode=="overwrite": df.to_parquet(path+table_name) msg=f"Parquet data written to -> {path}" logger.info(msg) except Exception as e: logger.error(f"Error writing as parquet ->{e}") def perform_business_checks(source,file_path): """The method performs DQ checks based on specific business rules. These include - - File name check - Column check - Schema check (data type) - Special char check Args: source (str): Source system name. file_path (str): File path on which dq checks are performed. """ try: status=True file=file_path.split("/")[-1] logger.info(f"Starting Business rule DQ Checks for: {file}") #ADD -> Check if filename in source: col_map -> if not just return False, file will be moved to error location. if file not in list(config["sources"][source]["col_map"].keys()): msg=f"{file} not in config list of files for {source}" logger.warning(msg) setLog(msg,"File Name Check") return False # DQ3: File Column Check df=pd.read_csv(file_path) control_schema=list(config["sources"][source]["col_map"][file].keys()) curr_schema=list(df.columns) if set(clean_schema(control_schema)) != set(clean_schema(curr_schema)): msg=f"Column check failed for: {file}" logger.warning(msg) setLog(msg,"Column Check") status=False return status else: msg=f"Column check passed for: {file}" logger.info(msg) # setLog(msg,"Schema Check") #DQ4: Schema check - data type # DQ3: File Column Check df.columns=clean_schema(df.columns) col_map={} file_name=file_path.split('/')[-1] for k,v in config["sources"][source]["col_map"][file_name].items(): col_map[k]=eval(v) schema = pa.DataFrameSchema(columns=col_map,strict=True) try: schema.validate(df) msg=f"Schema data type check passed for: {file_name}" logger.info(msg) except pa.errors.SchemaError as e: msg=f"Data type schema check failed for: {file_name} due to ->{e}" logger.warning(msg) setLog(msg,"Schema - Data Type Check") status=False return status return status except Exception as e: print(type(e)) print(e) msg=f"Error:{e} while performing Business DQ checks for file {file}" logger.error(msg) setLog(msg,"Business Rule DQ") return False def main(): """_summary_: Driver function for the DQ script. """ try: #Read all sources from config as a list source_list=list(config["sources"].keys()) for source in source_list: # -- this try : -> isRequired? msg=f"------Starting DQ checks for Source System: {source} ------" logger.info(msg) s3_uri=config['s3_base_uri'] root_dir=f"{s3_uri}{config["sources"][source]["root_dir"]}" dated_dir=eval(f'''f"{config['dated_folder']}"''') dated_dir=s3_uri+dated_dir create_dir(dated_dir) # except -> this will loop through all files in source and add failed message for all files in source folder # because dated folder creation failed #Move all files to dated folder for file in listDir(root_dir): file_path=f"{s3_uri}/{file}" file=file.split('/')[-1] # #move file to dated folder move_file(file_path,f"{dated_dir}{file}") logger.info(f"All files moved to dated folder for:{source}") for file in listDir(dated_dir): #Add try catch here failure of one file shouldnt stop the process. file_path=f"{s3_uri}/{file}" generic_dq_status=perform_generic_checks(file_path) if generic_dq_status == False: logger.warning(f"One or more generic DQ checks failed for file: {file}") err_path=eval(f'''f"{config['error_folder']}"''') err_path=s3_uri+err_path file_name=file.split('/')[-1] file_name=file_name.split('.') curr_ts=dt.datetime.today().strftime("%Y-%m-%d_%H:%M:%S") file_name[0]=file_name[0]+'_'+curr_ts file_name=".".join(file_name) create_dir(err_path) err_file_path=err_path+file_name move_file(file_path,err_file_path) setTaskVal(source,file_path.split('/')[-1],config["fail_flag"],err_file_path) else: msg=f"All Generic DQ checks passed for {file}" logger.info(msg) business_dq_status=perform_business_checks(source,file_path) if business_dq_status == True: msg=f"Business Rule DQ checks passed for {file}" logger.info(msg) df=pd.read_csv(file_path) table_path=eval(f'''f"{config['landing_dir']}"''') file_name=file_path.split('/')[-1] table_name=file_name.split('.')[0] table_path=s3_uri+table_path+table_name+'/' write_to_parquet(df,table_path,"append") setTaskVal(source,file,config["success_flag"],"")#write external table... else: logger.warning(f"One or more business rule DQ checks failed for file: {file}") err_path=eval(f'''f"{config['error_folder']}"''') err_path=s3_uri+err_path file_name=file.split('/')[-1] file_name=file_name.split('.') curr_ts=dt.datetime.today().strftime("%Y-%m-%d_%H:%M:%S") file_name[0]=file_name[0]+'_'+curr_ts file_name=".".join(file_name) create_dir(err_path) err_file_path=err_path+file_name move_file(file_path,err_file_path) setTaskVal(source,file,config["fail_flag"],err_path) except Exception as e: logger.error(e) raise e finally: exit_status["DQ Logs"] = exit_status["DQ Logs"].map(str) write_to_parquet(exit_status,"s3://cte-project/landing/dq/job_result/","overwrite") # --------------------Global declarations--------------------- logger=logging.getLogger("DQ Script") logging.basicConfig(format='%(name)s:%(levelname)s: %(message)s', level=logging.DEBUG) logging.getLogger('boto3').setLevel(logging.CRITICAL) logging.getLogger('botocore').setLevel(logging.CRITICAL) logging.getLogger('urllib3').setLevel(logging.CRITICAL) logging.getLogger('s3transfer').setLevel(logging.CRITICAL) logging.getLogger('aiobotocore').setLevel(logging.CRITICAL) logging.getLogger('charset_normalizer').setLevel(logging.CRITICAL) logging.getLogger('s3fs').setLevel(logging.CRITICAL) logging.getLogger('fsspec').setLevel(logging.CRITICAL) logging.getLogger('asyncio').setLevel(logging.CRITICAL) config_path="s3://cte-project/config/config.json" global err_msgs,config,exit_status,curr_dt,layer,s3_connect s3_connect = boto3.client('s3') config=getConfig(config_path) curr_dt=dt.date.today().strftime("%Y-%m") layer="DQ Script" print(type(config)) #Instantiate logging vars file_status=[] exit_status=pd.DataFrame(columns=config["status_dict_cols"]) main()
import sys from awsglue.transforms import * from awsglue.utils import getResolvedOptions from pyspark.context import SparkContext from awsglue.context import GlueContext from awsglue.job import Job sc = SparkContext() glueContext = GlueContext(sc) spark = glueContext.spark_session job = Job(glueContext) job.commit() # -------------------------Glue Job housekeeping section ----------------------- import boto3 from botocore.errorfactory import ClientError from urllib.parse import urlparse import pandas as pd import pandera as pa import datetime as dt from dateutil import parser import pyarrow import pyarrow.parquet as pq import time import logging import json import copy # --------------------End of Script imports--------------------------- def setLog(e,check): """add success/fail logs to the file_list. Parameters ---------- e :[str] An exception or the string value of an exception check:[str] DQ check for which logs are being added """ log_msg = f"{check} -> {e}" file_status.append(log_msg) def setTaskVal(source,file,status,error_loc=""): """Append file status to a global df exit_status Parameters ---------- source:[str] Source file for which DQ logs are being added status:[str] Status of File DQ check (success/fail) error_loc:[str] Location of error file, if DQ check failed, blank otherwise. """ ts=dt.datetime.now() logs=copy.deepcopy(file_status) exit_status.loc[len(exit_status.index)] = [ts,layer,source,file,status,error_loc,logs] file_status.clear() return def extractBotoParams(config_path): """Extract bucket name and key from s3 path. Parameters ---------- config_path : str path of application configuration file Returns ------- pair pair with bucket name and path key. """ parsed_url = urlparse(config_path) bucket_name = parsed_url.hostname s3_path = parsed_url.path[1:] return bucket_name,s3_path def getConfig(config_path: str): """Read application configuration file into json Parameters ---------- config_path : str path of application configuration file Returns ------- dict return a json dictionary contain application configuration """ try: logger.info(f'Reading config from {config_path}') bucket_name,s3_path = extractBotoParams(config_path) obj = s3_connect.get_object(Bucket=bucket_name, Key=s3_path) config = obj['Body'].read().decode("utf-8") logger.info("Config file read successfully!") return json.loads(config) except FileNotFoundError as e: logger.exception('CONFIGURATION ERROR: Couldnt find the configuration file : ' + str(e)) raise FileNotFoundError('CONFIGURATION ERROR: Couldnt find the configuration file : ' + str(e)) except ValueError as e: if not config_path: logger.exception('CONFIGURATION ERROR: Null config path : ' + str(e)) raise ValueError('CONFIGURATION ERROR: Null config path : ' + str(e)) else: logger.exception( 'CONFIGURATION ERROR: Invalid json. Error occurred while loading configuration file : ' + str(e)) raise ValueError( 'CONFIGURATION ERROR: Invalid json. Error occurred while loading configuration file : ' + str(e)) except Exception as e: logger.exception('CONFIGURATION ERROR: Error occurred while loading configuration file : ' + str(e)) err_msg = f"{type(e).__name__} : CONFIGURATION ERROR: Error occurred while loading configuration file : {str(e)}" raise Exception(err_msg) from e def move_file(src,dest): """Method to move file between directories. If path is not a file -> return, do nothing. Args: src (str): Source path with filename dest (str): Destination path with file name """ try: s3 = boto3.resource('s3') src_bucket,src_key=extractBotoParams(src) dest_bucket,dest_key=extractBotoParams(dest) copy_source = { 'Bucket': src_bucket, 'Key': src_key } bucket = s3.Bucket(dest_bucket) obj = bucket.Object(dest_key) obj.copy(copy_source) s3.Object(src_bucket, src_key).delete() logger.info(f"{src.split('/')[-1]} moved to : {dest}") except Exception as e: msg=f"Failed to move file to {dest} due to -> {e}" logger.error(msg) raise msg #try block in main for will catch this exception and push file status to df then continue with next file. def create_dir(path): """Create a new directory, do nothing if directory exists. Args: path (string): directory path """ try: if directoryExists(path): return else: bucketname,key=extractBotoParams(path) s3_connect.put_object(Bucket=bucketname,Key=key) logger.info(f"Directory created at: {path}") except Exception as e: msg=f"Failed to create directory {path} due to -> {e}" logger.error(msg) raise msg #try block in main for will catch this exception and push file status to df then continue with next file. def directoryExists(path): """Check if directory/file exists. Note: Folder paths must end with '/' Args: path (string): directory path Returns: bool """ bucket,key = extractBotoParams(path) try: s3_connect.head_object(Bucket=bucket, Key=key) except ClientError: return False return True def emptyDir(path): file_list=listDir(path) s3 = boto3.resource('s3') bucket,key=extractBotoParams(path) print("--------------") for file in file_list: s3.Object(bucket, file).delete() msg=f"Partition {curr_dt} cleaned." logger.info(msg) def listDir(path): """List all files present in dir and return list. Args: path (string): directory path Returns: list: List of file keys. """ try: files=[] s3 = boto3.resource('s3') bucket,key=extractBotoParams(path) my_bucket = s3.Bucket(bucket) for object_summary in my_bucket.objects.filter(Prefix=key): file_key=object_summary.key if file_key[-1]!='/': files.append(file_key) return files except Exception as e: msg=f"Failed to list dir {path} due to -> {e}" logger.error(msg) raise e def perform_generic_checks(file_path): """The method performs generic file checks on the file. These include - - Csv extension check - Check is file is empty Args: file_path (str): File path on which dq checks are performed. """ try: status=True file=file_path.split("/")[-1] logger.info(f"Starting generic DQ Checks for: {file}") #DQ1: File extension check ext=file_path[-3:] if ext!=config["source_ext"]: msg=f"CSV format check failed for: {file}" logger.warning(msg) setLog(msg,"File extension check") status=False return status else: msg=f"CSV format check passed for: {file}" logger.info(msg) # setLog(msg,"File extension check") #DQ2: File Not Empty check try: df=pd.read_csv(file_path) if df.shape[0] == 0: msg=f"File Not Empty check failed for: {file}" logger.warning(msg) setLog(msg,"File Not Empty") status=False return status else: msg=f"File Not empty check passed for: {file}" logger.info(msg) # setLog(msg,"File Not Empty check") except pd.errors.EmptyDataError as e: msg=f"File Not Empty check failed for: {file}" logger.warning(msg) setLog(msg,"File Not Empty") status=False return status return status except Exception as e: print(type(e)) print(e) msg=f"Error:{e} while performing Generic DQ checks for file {file}" logger.error(msg) setLog(msg,"Generic DQ") return False def clean_schema(lst): """This method cleans the list items so that they can be compared. - Strips space - Remove trailing/leading spaces - convert to lower case Args: lst (list): List to be cleaned Returns: list : Cleaned list """ schema=[] for col in lst: col=col.lower().strip() col=" ".join(col.split()) schema.append(col) return schema def validate_ts(ts): """Check if the pandas column has all timestamp values. Args: ts: Pandas Series (col) Returns: bool """ try: for i in ts: if i == "": continue parser.parse(i) return True except ValueError as e: logger.warning(f"Not a timestamp->{e}") return False def write_to_parquet(df,path,mode): """Write file to parquet. Args: df: dataframe to write path: Path to write to mode: overwrite/append Returns: bool """ try: table_name=path.split('/')[-2] table_name=table_name+".parquet" if mode=="append": if len(listDir(path+"date_partition="+curr_dt+"/"))>0: emptyDir(path+"date_partition="+curr_dt+"/") df['date_partition'] = curr_dt df.to_parquet(path,partition_cols=['date_partition']) msg=f"Parquet data written to -> {path}" logger.info(msg) if mode=="overwrite": df.to_parquet(path+table_name) msg=f"Parquet data written to -> {path}" logger.info(msg) except Exception as e: logger.error(f"Error writing as parquet ->{e}") def perform_business_checks(source,file_path): """The method performs DQ checks based on specific business rules. These include - - File name check - Column check - Schema check (data type) - Special char check Args: source (str): Source system name. file_path (str): File path on which dq checks are performed. """ try: status=True file=file_path.split("/")[-1] logger.info(f"Starting Business rule DQ Checks for: {file}") #ADD -> Check if filename in source: col_map -> if not just return False, file will be moved to error location. if file not in list(config["sources"][source]["col_map"].keys()): msg=f"{file} not in config list of files for {source}" logger.warning(msg) setLog(msg,"File Name Check") return False # DQ3: File Column Check df=pd.read_csv(file_path) control_schema=list(config["sources"][source]["col_map"][file].keys()) curr_schema=list(df.columns) if set(clean_schema(control_schema)) != set(clean_schema(curr_schema)): msg=f"Column check failed for: {file}" logger.warning(msg) setLog(msg,"Column Check") status=False return status else: msg=f"Column check passed for: {file}" logger.info(msg) # setLog(msg,"Schema Check") #DQ4: Schema check - data type # DQ3: File Column Check df.columns=clean_schema(df.columns) col_map={} file_name=file_path.split('/')[-1] for k,v in config["sources"][source]["col_map"][file_name].items(): col_map[k]=eval(v) schema = pa.DataFrameSchema(columns=col_map,strict=True) try: schema.validate(df) msg=f"Schema data type check passed for: {file_name}" logger.info(msg) except pa.errors.SchemaError as e: msg=f"Data type schema check failed for: {file_name} due to ->{e}" logger.warning(msg) setLog(msg,"Schema - Data Type Check") status=False return status return status except Exception as e: print(type(e)) print(e) msg=f"Error:{e} while performing Business DQ checks for file {file}" logger.error(msg) setLog(msg,"Business Rule DQ") return False def main(): """_summary_: Driver function for the DQ script. """ try: #Read all sources from config as a list source_list=list(config["sources"].keys()) for source in source_list: # -- this try : -> isRequired? msg=f"------Starting DQ checks for Source System: {source} ------" logger.info(msg) s3_uri=config['s3_base_uri'] root_dir=f"{s3_uri}{config['sources'][source]['root_dir']}" dated_dir=eval(f'''f"{config['dated_folder']}"''') dated_dir=s3_uri+dated_dir create_dir(dated_dir) # except -> this will loop through all files in source and add failed message for all files in source folder # because dated folder creation failed #Move all files to dated folder for file in listDir(root_dir): file_path=f"{s3_uri}/{file}" file=file.split('/')[-1] # #move file to dated folder move_file(file_path,f"{dated_dir}{file}") logger.info(f"All files moved to dated folder for:{source}") for file in listDir(dated_dir): #Add try catch here failure of one file shouldnt stop the process. file_path=f"{s3_uri}/{file}" generic_dq_status=perform_generic_checks(file_path) if generic_dq_status == False: logger.warning(f"One or more generic DQ checks failed for file: {file}") err_path=eval(f'''f"{config['error_folder']}"''') err_path=s3_uri+err_path file_name=file.split('/')[-1] file_name=file_name.split('.') curr_ts=dt.datetime.today().strftime("%Y-%m-%d_%H:%M:%S") file_name[0]=file_name[0]+'_'+curr_ts file_name=".".join(file_name) create_dir(err_path) err_file_path=err_path+file_name move_file(file_path,err_file_path) setTaskVal(source,file_path.split('/')[-1],config["fail_flag"],err_file_path) else: msg=f"All Generic DQ checks passed for {file}" logger.info(msg) business_dq_status=perform_business_checks(source,file_path) if business_dq_status == True: msg=f"Business Rule DQ checks passed for {file}" logger.info(msg) df=pd.read_csv(file_path) table_path=eval(f'''f"{config['landing_dir']}"''') file_name=file_path.split('/')[-1] table_name=file_name.split('.')[0] table_path=s3_uri+table_path+table_name+'/' write_to_parquet(df,table_path,"append") setTaskVal(source,file,config["success_flag"],"")#write external table... else: logger.warning(f"One or more business rule DQ checks failed for file: {file}") err_path=eval(f'''f"{config['error_folder']}"''') err_path=s3_uri+err_path file_name=file.split('/')[-1] file_name=file_name.split('.') curr_ts=dt.datetime.today().strftime("%Y-%m-%d_%H:%M:%S") file_name[0]=file_name[0]+'_'+curr_ts file_name=".".join(file_name) create_dir(err_path) err_file_path=err_path+file_name move_file(file_path,err_file_path) setTaskVal(source,file,config["fail_flag"],err_path) except Exception as e: logger.error(e) raise e finally: exit_status["DQ Logs"] = exit_status["DQ Logs"].map(str) write_to_parquet(exit_status,"s3://cte-project/landing/dq/job_result/","overwrite") # --------------------Global declarations--------------------- logger=logging.getLogger("DQ Script") logging.basicConfig(format='%(name)s:%(levelname)s: %(message)s', level=logging.DEBUG) logging.getLogger('boto3').setLevel(logging.CRITICAL) logging.getLogger('botocore').setLevel(logging.CRITICAL) logging.getLogger('urllib3').setLevel(logging.CRITICAL) logging.getLogger('s3transfer').setLevel(logging.CRITICAL) logging.getLogger('aiobotocore').setLevel(logging.CRITICAL) logging.getLogger('charset_normalizer').setLevel(logging.CRITICAL) logging.getLogger('s3fs').setLevel(logging.CRITICAL) logging.getLogger('fsspec').setLevel(logging.CRITICAL) logging.getLogger('asyncio').setLevel(logging.CRITICAL) config_path="s3://cte-project/config/config.json" global err_msgs,config,exit_status,curr_dt,layer,s3_connect s3_connect = boto3.client('s3') config=getConfig(config_path) curr_dt=dt.date.today().strftime("%Y-%m") layer="DQ Script" print(type(config)) #Instantiate logging vars file_status=[] exit_status=pd.DataFrame(columns=config["status_dict_cols"]) main()
from flask import Flask, request, jsonify from cloudevents.http import from_http import logging, json from vcenter import Session from datetime import date logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s') app = Flask(__name__) @app.route('/', methods=['GET','POST']) def echo(): if request.method == 'GET': sc = 200 msg = 'POST to this endpoint to apply custom attributes to a VM object within a cloudEvent message' message = { 'status': sc, 'message': msg, } resp = jsonify(message) resp.status_code = sc return resp if request.method == 'POST': try: event = from_http(request.headers, request.get_data(),None) data = event.data # hack to handle non JSON payload, e.g. xml if not isinstance(data,dict): data = str(event.data) cevent = { "attributes": event._attributes, "data": data } app.logger.debug(f'"***cloud event*** {json.dumps(cevent)}') # CloudEvent - simple validation ref_vm = cevent['data']['Vm']['Vm'] ref_user = cevent['data']['UserName'] subject = cevent['attributes']['subject'] vc_s = Session() attr_owner, attr_creation_date, attr_last_poweredon = vc_s.get_vm_attributes() vm_obj = vc_s.get_vm(ref_vm['Value']) if not vm_obj: sc = 404 msg = f"could not find vm with moRef: {ref_vm["Value"]}" app.logger.error(msg) message = { 'status': sc, 'error': msg, } resp = jsonify(message) resp.status_code = sc return resp if subject in ["DrsVmPoweredOnEvent", "VmPoweredOnEvent"]: app.logger.info(f"Apply attribute > {attr_last_poweredon.name}") vc_s.set_custom_attr( entity=vm_obj, key=attr_last_poweredon.key, value=date.today().strftime("%d/%m/%Y") ) if subject in ["VmCreatedEvent", "VmClonedEvent", "VmRegisteredEvent"]: app.logger.debug(f"Apply attribute > {attr_owner.name}") vc_s.set_custom_attr( entity=vm_obj, key=attr_owner.key, value=ref_user ) app.logger.debug(f"Apply attribute > {attr_creation_date.name}") vc_s.set_custom_attr( entity=vm_obj, key=attr_creation_date.key, value=date.today().strftime("%d/%m/%Y") ) vc_s.close() app.logger.debug(f"End of event") return {}, 204 except Exception as e: sc = 500 msg = f'could not decode cloud event: {e}' app.logger.error(msg) message = { 'status': sc, 'error': msg, } resp = jsonify(message) resp.status_code = sc return resp # hint: run with FLASK_ENV=development FLASK_APP=handler.py flask run if __name__ == "__main__": app.run()
from flask import Flask, request, jsonify from cloudevents.http import from_http import logging, json from vcenter import Session from datetime import date logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s') app = Flask(__name__) @app.route('/', methods=['GET','POST']) def echo(): if request.method == 'GET': sc = 200 msg = 'POST to this endpoint to apply custom attributes to a VM object within a cloudEvent message' message = { 'status': sc, 'message': msg, } resp = jsonify(message) resp.status_code = sc return resp if request.method == 'POST': try: event = from_http(request.headers, request.get_data(),None) data = event.data # hack to handle non JSON payload, e.g. xml if not isinstance(data,dict): data = str(event.data) cevent = { "attributes": event._attributes, "data": data } app.logger.debug(f'"***cloud event*** {json.dumps(cevent)}') # CloudEvent - simple validation ref_vm = cevent['data']['Vm']['Vm'] ref_user = cevent['data']['UserName'] subject = cevent['attributes']['subject'] vc_s = Session() attr_owner, attr_creation_date, attr_last_poweredon = vc_s.get_vm_attributes() vm_obj = vc_s.get_vm(ref_vm['Value']) if not vm_obj: sc = 404 msg = f"could not find vm with moRef: {ref_vm['Value']}" app.logger.error(msg) message = { 'status': sc, 'error': msg, } resp = jsonify(message) resp.status_code = sc return resp if subject in ["DrsVmPoweredOnEvent", "VmPoweredOnEvent"]: app.logger.info(f"Apply attribute > {attr_last_poweredon.name}") vc_s.set_custom_attr( entity=vm_obj, key=attr_last_poweredon.key, value=date.today().strftime("%d/%m/%Y") ) if subject in ["VmCreatedEvent", "VmClonedEvent", "VmRegisteredEvent"]: app.logger.debug(f"Apply attribute > {attr_owner.name}") vc_s.set_custom_attr( entity=vm_obj, key=attr_owner.key, value=ref_user ) app.logger.debug(f"Apply attribute > {attr_creation_date.name}") vc_s.set_custom_attr( entity=vm_obj, key=attr_creation_date.key, value=date.today().strftime("%d/%m/%Y") ) vc_s.close() app.logger.debug(f"End of event") return {}, 204 except Exception as e: sc = 500 msg = f'could not decode cloud event: {e}' app.logger.error(msg) message = { 'status': sc, 'error': msg, } resp = jsonify(message) resp.status_code = sc return resp # hint: run with FLASK_ENV=development FLASK_APP=handler.py flask run if __name__ == "__main__": app.run()
import logging import os from abc import ABC, abstractmethod from typing import Optional from checkov.terraform.module_loading.content import ModuleContent from checkov.terraform.module_loading.registry import module_loader_registry # ModuleContent allows access to a directory containing module file via the `path()` # function. Instances may be used in a `with` context to ensure temporary directories # are removed, if applicable. class ModuleLoader(ABC): def __init__(self) -> None: module_loader_registry.register(self) self.logger = logging.getLogger(__name__) self.module_source: str = "" self.current_dir: str = "" self.dest_dir: str = "" self.external_modules_folder_name: str = "" self.version = "latest" self.is_external = True self.inner_module: Optional[str] = None self.root_dir = "" # root dir for storing external modules @abstractmethod def discover(self): """ discover parameters from execution context of checkov. usually from env variable """ pass def load( self, root_dir: str, current_dir: str, source: str, source_version: Optional[str], dest_dir: str, external_modules_folder_name: str, inner_module: Optional[str] = None, ) -> ModuleContent: """ This function provides an opportunity for the loader to load a module's content if it chooses to do so. There are three resulting states that can occur when calling this function: 1) the loader can't handle the source type, in which case a ModuleContent is returned for which the `loaded()` method will return False. 2) the loader can handle the source type and loading is successful, in which case a ModuleContent object is returned for which `loaded()` returns True and which provides the directory containing the module files 3) the loader tried to load the module content but and error occurred, in which case an exception is raised. :param current_dir: Directory containing the reference to the module. :param source: the raw source string from the module's `source` attribute (e.g., "hashicorp/consul/aws" or "git::https://example.com/vpc.git?ref=v1.2.0") :param source_version: contains content from the module's `version` attribute, if provided :param dest_dir: where to save the downloaded module :return: A ModuleContent object which may or may not being loaded. """ self.root_dir = root_dir self.module_source = source self.current_dir = current_dir self.version = str(source_version) self.dest_dir = dest_dir self.external_modules_folder_name = external_modules_folder_name self.inner_module = inner_module if not self._is_matching_loader(): return ModuleContent(dir=None) module_path = self._find_module_path() if os.path.exists(module_path): return ModuleContent(dir=module_path) self.logger.debug(f"Using {self.__class__.__name__} attempting to get module " f"{self.module_source if "@" not in self.module_source else self.module_source.split("@")[1]} " f"version: {self.version}") return self._load_module() @abstractmethod def _is_matching_loader(self) -> bool: raise NotImplementedError() @abstractmethod def _load_module(self) -> ModuleContent: raise NotImplementedError() @abstractmethod def _find_module_path(self) -> str: raise NotImplementedError()
import logging import os from abc import ABC, abstractmethod from typing import Optional from checkov.terraform.module_loading.content import ModuleContent from checkov.terraform.module_loading.registry import module_loader_registry # ModuleContent allows access to a directory containing module file via the `path()` # function. Instances may be used in a `with` context to ensure temporary directories # are removed, if applicable. class ModuleLoader(ABC): def __init__(self) -> None: module_loader_registry.register(self) self.logger = logging.getLogger(__name__) self.module_source: str = "" self.current_dir: str = "" self.dest_dir: str = "" self.external_modules_folder_name: str = "" self.version = "latest" self.is_external = True self.inner_module: Optional[str] = None self.root_dir = "" # root dir for storing external modules @abstractmethod def discover(self): """ discover parameters from execution context of checkov. usually from env variable """ pass def load( self, root_dir: str, current_dir: str, source: str, source_version: Optional[str], dest_dir: str, external_modules_folder_name: str, inner_module: Optional[str] = None, ) -> ModuleContent: """ This function provides an opportunity for the loader to load a module's content if it chooses to do so. There are three resulting states that can occur when calling this function: 1) the loader can't handle the source type, in which case a ModuleContent is returned for which the `loaded()` method will return False. 2) the loader can handle the source type and loading is successful, in which case a ModuleContent object is returned for which `loaded()` returns True and which provides the directory containing the module files 3) the loader tried to load the module content but and error occurred, in which case an exception is raised. :param current_dir: Directory containing the reference to the module. :param source: the raw source string from the module's `source` attribute (e.g., "hashicorp/consul/aws" or "git::https://example.com/vpc.git?ref=v1.2.0") :param source_version: contains content from the module's `version` attribute, if provided :param dest_dir: where to save the downloaded module :return: A ModuleContent object which may or may not being loaded. """ self.root_dir = root_dir self.module_source = source self.current_dir = current_dir self.version = str(source_version) self.dest_dir = dest_dir self.external_modules_folder_name = external_modules_folder_name self.inner_module = inner_module if not self._is_matching_loader(): return ModuleContent(dir=None) module_path = self._find_module_path() if os.path.exists(module_path): return ModuleContent(dir=module_path) self.logger.debug(f"Using {self.__class__.__name__} attempting to get module " f"{self.module_source if '@' not in self.module_source else self.module_source.split('@')[1]} " f"version: {self.version}") return self._load_module() @abstractmethod def _is_matching_loader(self) -> bool: raise NotImplementedError() @abstractmethod def _load_module(self) -> ModuleContent: raise NotImplementedError() @abstractmethod def _find_module_path(self) -> str: raise NotImplementedError()
#!/usr/bin/env python3 import os # os.path() features a lot of functionalities. # 1. os.path.basename() prints the end leaf name print(os.path.basename("/tmp/test.txt")) # 2. os.path.dirname() prints the directory part print(os.path.dirname("/tmp/test.txt")) # 3. os.path.exists() check for the existence of paths print(f'Checking /tmp/test.txt exists: {os.path.exists('/tmp/test.txt')}') # 4. os.path.isdir() and os.path.isfile() if os.path.isdir("/tmp/test.txt"): print("/tmp/test.txt is not a folder") elif os.path.isfile("/tmp/test.txt"): print("/tmp/test.txt is a file") # 5. os.path.join() joins two paths # It adds `/` if it's Unix, and `\` # if it's Windows versions # NOTE: This doesn't check if the path exists. print(os.path.join("/tmp", "test.txt")) # 6. os.path.split() splits a path to a dir and file print(os.path.split("/tmp/test.txt"))
#!/usr/bin/env python3 import os # os.path() features a lot of functionalities. # 1. os.path.basename() prints the end leaf name print(os.path.basename("/tmp/test.txt")) # 2. os.path.dirname() prints the directory part print(os.path.dirname("/tmp/test.txt")) # 3. os.path.exists() check for the existence of paths print(f'Checking /tmp/test.txt exists: {os.path.exists("/tmp/test.txt")}') # 4. os.path.isdir() and os.path.isfile() if os.path.isdir("/tmp/test.txt"): print("/tmp/test.txt is not a folder") elif os.path.isfile("/tmp/test.txt"): print("/tmp/test.txt is a file") # 5. os.path.join() joins two paths # It adds `/` if it's Unix, and `\` # if it's Windows versions # NOTE: This doesn't check if the path exists. print(os.path.join("/tmp", "test.txt")) # 6. os.path.split() splits a path to a dir and file print(os.path.split("/tmp/test.txt"))
""" Probabilistic Detectron Inference Script """ import json import os import sys from shutil import copyfile import torch import tqdm import core # This is very ugly. Essential for now but should be fixed. sys.path.append(os.path.join(core.top_dir(), "src", "detr")) from detectron2.data import MetadataCatalog, build_detection_test_loader # Detectron imports from detectron2.engine import launch # Project imports from core.evaluation_tools.evaluation_utils import ( get_train_contiguous_id_to_test_thing_dataset_id_dict, ) from core.setup import setup_arg_parser, setup_config from offline_evaluation import ( compute_average_precision, compute_calibration_errors, compute_ood_probabilistic_metrics, compute_probabilistic_metrics, ) from probabilistic_inference.inference_utils import ( build_predictor, get_inference_output_dir, instances_to_json, ) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def main(args): # Setup config cfg = setup_config(args, random_seed=args.random_seed, is_testing=True) # Make sure only 1 data point is processed at a time. This simulates # deployment. cfg.defrost() cfg.DATALOADER.NUM_WORKERS = 32 cfg.SOLVER.IMS_PER_BATCH = 1 cfg.MODEL.DEVICE = device.type # Set up number of cpu threads# torch.set_num_threads(cfg.DATALOADER.NUM_WORKERS) # Create inference output directory and copy inference config file to keep # track of experimental settings if args.inference_dir == "": inference_output_dir = get_inference_output_dir( cfg["OUTPUT_DIR"], args.test_dataset, args.inference_config, args.image_corruption_level, ) else: inference_output_dir = args.inference_dir if not os.path.isdir(inference_output_dir): os.makedirs(inference_output_dir, exist_ok=True) os.makedirs(inference_output_dir, exist_ok=True) copyfile( args.inference_config, os.path.join(inference_output_dir, os.path.split(args.inference_config)[-1]), ) # Get category mapping dictionary: train_thing_dataset_id_to_contiguous_id = MetadataCatalog.get( cfg.DATASETS.TRAIN[0] ).thing_dataset_id_to_contiguous_id test_thing_dataset_id_to_contiguous_id = MetadataCatalog.get( args.test_dataset ).thing_dataset_id_to_contiguous_id # If both dicts are equal or if we are performing out of distribution # detection, just flip the test dict. cat_mapping_dict = get_train_contiguous_id_to_test_thing_dataset_id_dict( cfg, args, train_thing_dataset_id_to_contiguous_id, test_thing_dataset_id_to_contiguous_id, ) # Build predictor predictor = build_predictor(cfg) test_data_loader = build_detection_test_loader(cfg, dataset_name=args.test_dataset) final_output_list = [] if not args.eval_only: with torch.no_grad(): with tqdm.tqdm(total=len(test_data_loader)) as pbar: for idx, input_im in enumerate(test_data_loader): # Apply corruption outputs = predictor(input_im) # print(f'Image id {input_im[0]['image_id']}') # predictor.visualize_inference(input_im, outputs) final_output_list.extend( instances_to_json( outputs, input_im[0]["image_id"], cat_mapping_dict ) ) pbar.update(1) with open( os.path.join(inference_output_dir, "coco_instances_results.json"), "w" ) as fp: json.dump(final_output_list, fp, indent=4, separators=(",", ": ")) if "ood" in args.test_dataset: compute_ood_probabilistic_metrics.main(args, cfg) else: compute_average_precision.main(args, cfg, inference_output_dir) compute_probabilistic_metrics.main( args, cfg, inference_output_dir=inference_output_dir ) compute_calibration_errors.main( args, cfg, inference_output_dir=inference_output_dir ) if __name__ == "__main__": # Create arg parser arg_parser = setup_arg_parser() args = arg_parser.parse_args() # Support single gpu inference only. args.num_gpus = 1 print("Command Line Args:", args) launch( main, args.num_gpus, num_machines=args.num_machines, machine_rank=args.machine_rank, dist_url=args.dist_url, args=(args,), )
""" Probabilistic Detectron Inference Script """ import json import os import sys from shutil import copyfile import torch import tqdm import core # This is very ugly. Essential for now but should be fixed. sys.path.append(os.path.join(core.top_dir(), "src", "detr")) from detectron2.data import MetadataCatalog, build_detection_test_loader # Detectron imports from detectron2.engine import launch # Project imports from core.evaluation_tools.evaluation_utils import ( get_train_contiguous_id_to_test_thing_dataset_id_dict, ) from core.setup import setup_arg_parser, setup_config from offline_evaluation import ( compute_average_precision, compute_calibration_errors, compute_ood_probabilistic_metrics, compute_probabilistic_metrics, ) from probabilistic_inference.inference_utils import ( build_predictor, get_inference_output_dir, instances_to_json, ) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def main(args): # Setup config cfg = setup_config(args, random_seed=args.random_seed, is_testing=True) # Make sure only 1 data point is processed at a time. This simulates # deployment. cfg.defrost() cfg.DATALOADER.NUM_WORKERS = 32 cfg.SOLVER.IMS_PER_BATCH = 1 cfg.MODEL.DEVICE = device.type # Set up number of cpu threads# torch.set_num_threads(cfg.DATALOADER.NUM_WORKERS) # Create inference output directory and copy inference config file to keep # track of experimental settings if args.inference_dir == "": inference_output_dir = get_inference_output_dir( cfg["OUTPUT_DIR"], args.test_dataset, args.inference_config, args.image_corruption_level, ) else: inference_output_dir = args.inference_dir if not os.path.isdir(inference_output_dir): os.makedirs(inference_output_dir, exist_ok=True) os.makedirs(inference_output_dir, exist_ok=True) copyfile( args.inference_config, os.path.join(inference_output_dir, os.path.split(args.inference_config)[-1]), ) # Get category mapping dictionary: train_thing_dataset_id_to_contiguous_id = MetadataCatalog.get( cfg.DATASETS.TRAIN[0] ).thing_dataset_id_to_contiguous_id test_thing_dataset_id_to_contiguous_id = MetadataCatalog.get( args.test_dataset ).thing_dataset_id_to_contiguous_id # If both dicts are equal or if we are performing out of distribution # detection, just flip the test dict. cat_mapping_dict = get_train_contiguous_id_to_test_thing_dataset_id_dict( cfg, args, train_thing_dataset_id_to_contiguous_id, test_thing_dataset_id_to_contiguous_id, ) # Build predictor predictor = build_predictor(cfg) test_data_loader = build_detection_test_loader(cfg, dataset_name=args.test_dataset) final_output_list = [] if not args.eval_only: with torch.no_grad(): with tqdm.tqdm(total=len(test_data_loader)) as pbar: for idx, input_im in enumerate(test_data_loader): # Apply corruption outputs = predictor(input_im) # print(f'Image id {input_im[0]["image_id"]}') # predictor.visualize_inference(input_im, outputs) final_output_list.extend( instances_to_json( outputs, input_im[0]["image_id"], cat_mapping_dict ) ) pbar.update(1) with open( os.path.join(inference_output_dir, "coco_instances_results.json"), "w" ) as fp: json.dump(final_output_list, fp, indent=4, separators=(",", ": ")) if "ood" in args.test_dataset: compute_ood_probabilistic_metrics.main(args, cfg) else: compute_average_precision.main(args, cfg, inference_output_dir) compute_probabilistic_metrics.main( args, cfg, inference_output_dir=inference_output_dir ) compute_calibration_errors.main( args, cfg, inference_output_dir=inference_output_dir ) if __name__ == "__main__": # Create arg parser arg_parser = setup_arg_parser() args = arg_parser.parse_args() # Support single gpu inference only. args.num_gpus = 1 print("Command Line Args:", args) launch( main, args.num_gpus, num_machines=args.num_machines, machine_rank=args.machine_rank, dist_url=args.dist_url, args=(args,), )
import scrapy import logging from scrapy.loader import ItemLoader from scrapy.http import FormRequest from scrapy.exceptions import CloseSpider from datetime import datetime from fbposts.items import FbPostItem, parse_date class FacebookSpider(scrapy.Spider): """ Parse FB pages (needs credentials) """ name = "fb" def __init__(self, *args, **kwargs): # turn off annoying logging, set LOG_LEVEL=DEBUG in settings.py to see more logs logger = logging.getLogger("scrapy.middleware") logger.setLevel(logging.WARNING) super().__init__(*args, **kwargs) # email & pass need to be passed as attributes! if "email" not in kwargs or "password" not in kwargs: raise AttributeError( "You need to provide valid email and password:\n" 'scrapy fb -a email="EMAIL" -a password="PASSWORD"' ) else: self.logger.info("Email and password provided, will be used to log in") # page name parsing (added support for full urls) if "page" in kwargs: if self.page.find("/groups/") != -1: self.group = 1 else: self.group = 0 if self.page.find("https://www.facebook.com/") != -1: self.page = self.page[25:] elif self.page.find("https://mbasic.facebook.com/") != -1: self.page = self.page[28:] elif self.page.find("https://m.facebook.com/") != -1: self.page = self.page[23:] # parse date if "date" not in kwargs: self.date = datetime.today() self.logger.info( f"Date attribute not provided, scraping date set to {self.date.strftime("%Y-%M-%D")} (fb launch date)" ) else: self.date = datetime.strptime(kwargs["date"], "%Y-%m-%d") self.logger.info( "Date attribute provided, fbcrawl will start crawling at {}".format( kwargs["date"] ) ) self.year = self.date.year # parse lang, if not provided (but is supported) it will be guessed in parse_home self.lang = "pt" # max num of posts to crawl if "max" not in kwargs: self.max = int(10e5) else: self.max = int(kwargs["max"]) # current year, this variable is needed for proper parse_page recursion self.k = datetime.now().year # count number of posts, used to enforce DFS and insert posts orderly in the csv self.count = 0 self.start_urls = ["https://mbasic.facebook.com"] def parse(self, response): """ Handle login with provided credentials """ return FormRequest.from_response( response, formxpath='//form[contains(@action, "login")]', formdata={"email": self.email, "pass": self.password}, callback=self.parse_home, ) def parse_home(self, response): """ This method has multiple purposes: 1) Handle failed logins due to facebook 'save-device' redirection 2) Set language interface, if not already provided 3) Navigate to given page """ # handle 'save-device' redirection if response.xpath("//div/a[contains(@href,'save-device')]"): self.logger.info('Going through the "save-device" checkpoint') return FormRequest.from_response( response, formdata={"name_action_selected": "dont_save"}, callback=self.parse_home, ) # navigate to provided page href = response.urljoin(self.page) self.logger.info("Scraping facebook page {}".format(href)) return scrapy.Request(url=href, callback=self.parse_page, meta={"index": 1}) def parse_page(self, response): """ Parse the given page selecting the posts. Then ask recursively for another page. """ #open page in browser for debug # from scrapy.utils.response import open_in_browser # open_in_browser(response) # select all posts for post in response.xpath("//article[contains(@data-ft,'top_level_post_id')]"): many_features = post.xpath("./@data-ft").get() post_date = parse_date([many_features], {"lang": self.lang}) post_date = ( datetime.strptime(post_date, "%Y-%m-%d %H:%M:%S") if post_date is not None else post_date ) if post_date is None: post_date = datetime(self.date.year, self.date.month, 1) # if 'date' argument is reached stop crawling if post_date < self.date: raise CloseSpider( "Reached date: {} - post_date: {}".format(self.date, post_date) ) new = ItemLoader(item=FbPostItem(), selector=post) if abs(self.count) + 1 > self.max: raise CloseSpider( "Reached max num of post: {}. Crawling finished".format( abs(self.count) ) ) self.logger.info( "Parsing post n = {}, post_date = {}".format( abs(self.count) + 1, post_date ) ) new.add_value("date", post_date) new.add_xpath('post_id','./@data-ft') new.add_xpath('url', ".//a[contains(@href,'footer')]/@href") # returns full post-link in a list post = post.xpath(".//a[contains(@href,'footer')]/@href").extract() temp_post = response.urljoin(post[0]) self.count -= 1 yield scrapy.Request( temp_post, self.parse_post, priority=self.count, meta={"item": new} ) # load following page, try to click on "more" # after few pages have been scraped, the "more" link might disappears # if not present look for the highest year not parsed yet # click once on the year and go back to clicking "more" # new_page is different for groups if self.group == 1: new_page = response.xpath( "//div[contains(@id,'stories_container')]/div[2]/a/@href" ).extract() else: new_page = response.xpath( "//div[2]/a[contains(@href,'timestart=') and not(contains(text(),'ent')) and not(contains(text(),number()))]/@href" ).extract() # this is why lang is needed ^^^^^^^^^^^^^^^^^^^^^^^^^^ if not new_page: self.logger.info('[!] "more" link not found, will look for a "year" link') # self.k is the year link that we look for if response.meta["flag"] == self.k and self.k >= self.year: xpath = ( "//div/a[contains(@href,'time') and contains(text(),'" + str(self.k) + "')]/@href" ) new_page = response.xpath(xpath).extract() if new_page: new_page = response.urljoin(new_page[0]) self.k -= 1 self.logger.info( 'Found a link for year "{}", new_page = {}'.format( self.k, new_page ) ) yield scrapy.Request( new_page, callback=self.parse_page, meta={"flag": self.k} ) else: while ( not new_page ): # sometimes the years are skipped this handles small year gaps self.logger.info( "Link not found for year {}, trying with previous year {}".format( self.k, self.k - 1 ) ) self.k -= 1 if self.k < self.year: raise CloseSpider( "Reached date: {}. Crawling finished".format(self.date) ) xpath = ( "//div/a[contains(@href,'time') and contains(text(),'" + str(self.k) + "')]/@href" ) new_page = response.xpath(xpath).extract() self.logger.info( 'Found a link for year "{}", new_page = {}'.format( self.k, new_page ) ) new_page = response.urljoin(new_page[0]) self.k -= 1 yield scrapy.Request( new_page, callback=self.parse_page, meta={"flag": self.k} ) else: self.logger.info("Crawling has finished with no errors!") else: new_page = response.urljoin(new_page[0]) if "flag" in response.meta: self.logger.info( 'Page scraped, clicking on "more"! new_page = {}'.format(new_page) ) yield scrapy.Request( new_page, callback=self.parse_page, meta={"flag": response.meta["flag"]}, ) else: self.logger.info( 'First page scraped, clicking on "more"! new_page = {}'.format( new_page ) ) yield scrapy.Request( new_page, callback=self.parse_page, meta={"flag": self.k} ) def parse_post(self, response): new = ItemLoader( item=FbPostItem(), response=response, parent=response.meta["item"] ) new.context["lang"] = self.lang new.add_xpath( "source", "//td/div/h3/strong/a/text() | //span/strong/a/text() | //div/div/div/a[contains(@href,'post_id')]/strong/text()", ) new.add_xpath("image", "//a/img[contains(@src,'content')]/@src") new.add_xpath( "text", "//div[@data-ft]//p//text() | //div[@data-ft]/div[@class]/div[@class]/text()", ) yield new.load_item()
import scrapy import logging from scrapy.loader import ItemLoader from scrapy.http import FormRequest from scrapy.exceptions import CloseSpider from datetime import datetime from fbposts.items import FbPostItem, parse_date class FacebookSpider(scrapy.Spider): """ Parse FB pages (needs credentials) """ name = "fb" def __init__(self, *args, **kwargs): # turn off annoying logging, set LOG_LEVEL=DEBUG in settings.py to see more logs logger = logging.getLogger("scrapy.middleware") logger.setLevel(logging.WARNING) super().__init__(*args, **kwargs) # email & pass need to be passed as attributes! if "email" not in kwargs or "password" not in kwargs: raise AttributeError( "You need to provide valid email and password:\n" 'scrapy fb -a email="EMAIL" -a password="PASSWORD"' ) else: self.logger.info("Email and password provided, will be used to log in") # page name parsing (added support for full urls) if "page" in kwargs: if self.page.find("/groups/") != -1: self.group = 1 else: self.group = 0 if self.page.find("https://www.facebook.com/") != -1: self.page = self.page[25:] elif self.page.find("https://mbasic.facebook.com/") != -1: self.page = self.page[28:] elif self.page.find("https://m.facebook.com/") != -1: self.page = self.page[23:] # parse date if "date" not in kwargs: self.date = datetime.today() self.logger.info( f"Date attribute not provided, scraping date set to {self.date.strftime('%Y-%M-%D')} (fb launch date)" ) else: self.date = datetime.strptime(kwargs["date"], "%Y-%m-%d") self.logger.info( "Date attribute provided, fbcrawl will start crawling at {}".format( kwargs["date"] ) ) self.year = self.date.year # parse lang, if not provided (but is supported) it will be guessed in parse_home self.lang = "pt" # max num of posts to crawl if "max" not in kwargs: self.max = int(10e5) else: self.max = int(kwargs["max"]) # current year, this variable is needed for proper parse_page recursion self.k = datetime.now().year # count number of posts, used to enforce DFS and insert posts orderly in the csv self.count = 0 self.start_urls = ["https://mbasic.facebook.com"] def parse(self, response): """ Handle login with provided credentials """ return FormRequest.from_response( response, formxpath='//form[contains(@action, "login")]', formdata={"email": self.email, "pass": self.password}, callback=self.parse_home, ) def parse_home(self, response): """ This method has multiple purposes: 1) Handle failed logins due to facebook 'save-device' redirection 2) Set language interface, if not already provided 3) Navigate to given page """ # handle 'save-device' redirection if response.xpath("//div/a[contains(@href,'save-device')]"): self.logger.info('Going through the "save-device" checkpoint') return FormRequest.from_response( response, formdata={"name_action_selected": "dont_save"}, callback=self.parse_home, ) # navigate to provided page href = response.urljoin(self.page) self.logger.info("Scraping facebook page {}".format(href)) return scrapy.Request(url=href, callback=self.parse_page, meta={"index": 1}) def parse_page(self, response): """ Parse the given page selecting the posts. Then ask recursively for another page. """ #open page in browser for debug # from scrapy.utils.response import open_in_browser # open_in_browser(response) # select all posts for post in response.xpath("//article[contains(@data-ft,'top_level_post_id')]"): many_features = post.xpath("./@data-ft").get() post_date = parse_date([many_features], {"lang": self.lang}) post_date = ( datetime.strptime(post_date, "%Y-%m-%d %H:%M:%S") if post_date is not None else post_date ) if post_date is None: post_date = datetime(self.date.year, self.date.month, 1) # if 'date' argument is reached stop crawling if post_date < self.date: raise CloseSpider( "Reached date: {} - post_date: {}".format(self.date, post_date) ) new = ItemLoader(item=FbPostItem(), selector=post) if abs(self.count) + 1 > self.max: raise CloseSpider( "Reached max num of post: {}. Crawling finished".format( abs(self.count) ) ) self.logger.info( "Parsing post n = {}, post_date = {}".format( abs(self.count) + 1, post_date ) ) new.add_value("date", post_date) new.add_xpath('post_id','./@data-ft') new.add_xpath('url', ".//a[contains(@href,'footer')]/@href") # returns full post-link in a list post = post.xpath(".//a[contains(@href,'footer')]/@href").extract() temp_post = response.urljoin(post[0]) self.count -= 1 yield scrapy.Request( temp_post, self.parse_post, priority=self.count, meta={"item": new} ) # load following page, try to click on "more" # after few pages have been scraped, the "more" link might disappears # if not present look for the highest year not parsed yet # click once on the year and go back to clicking "more" # new_page is different for groups if self.group == 1: new_page = response.xpath( "//div[contains(@id,'stories_container')]/div[2]/a/@href" ).extract() else: new_page = response.xpath( "//div[2]/a[contains(@href,'timestart=') and not(contains(text(),'ent')) and not(contains(text(),number()))]/@href" ).extract() # this is why lang is needed ^^^^^^^^^^^^^^^^^^^^^^^^^^ if not new_page: self.logger.info('[!] "more" link not found, will look for a "year" link') # self.k is the year link that we look for if response.meta["flag"] == self.k and self.k >= self.year: xpath = ( "//div/a[contains(@href,'time') and contains(text(),'" + str(self.k) + "')]/@href" ) new_page = response.xpath(xpath).extract() if new_page: new_page = response.urljoin(new_page[0]) self.k -= 1 self.logger.info( 'Found a link for year "{}", new_page = {}'.format( self.k, new_page ) ) yield scrapy.Request( new_page, callback=self.parse_page, meta={"flag": self.k} ) else: while ( not new_page ): # sometimes the years are skipped this handles small year gaps self.logger.info( "Link not found for year {}, trying with previous year {}".format( self.k, self.k - 1 ) ) self.k -= 1 if self.k < self.year: raise CloseSpider( "Reached date: {}. Crawling finished".format(self.date) ) xpath = ( "//div/a[contains(@href,'time') and contains(text(),'" + str(self.k) + "')]/@href" ) new_page = response.xpath(xpath).extract() self.logger.info( 'Found a link for year "{}", new_page = {}'.format( self.k, new_page ) ) new_page = response.urljoin(new_page[0]) self.k -= 1 yield scrapy.Request( new_page, callback=self.parse_page, meta={"flag": self.k} ) else: self.logger.info("Crawling has finished with no errors!") else: new_page = response.urljoin(new_page[0]) if "flag" in response.meta: self.logger.info( 'Page scraped, clicking on "more"! new_page = {}'.format(new_page) ) yield scrapy.Request( new_page, callback=self.parse_page, meta={"flag": response.meta["flag"]}, ) else: self.logger.info( 'First page scraped, clicking on "more"! new_page = {}'.format( new_page ) ) yield scrapy.Request( new_page, callback=self.parse_page, meta={"flag": self.k} ) def parse_post(self, response): new = ItemLoader( item=FbPostItem(), response=response, parent=response.meta["item"] ) new.context["lang"] = self.lang new.add_xpath( "source", "//td/div/h3/strong/a/text() | //span/strong/a/text() | //div/div/div/a[contains(@href,'post_id')]/strong/text()", ) new.add_xpath("image", "//a/img[contains(@src,'content')]/@src") new.add_xpath( "text", "//div[@data-ft]//p//text() | //div[@data-ft]/div[@class]/div[@class]/text()", ) yield new.load_item()
import os import shutil from io import StringIO from types import SimpleNamespace import pkg_resources # from colt import Colt # from .qm.qm import QM, implemented_qm_software from .molecule.terms import Terms from .dihedral_scan import DihedralScan from .misc import LOGO class Initialize(Colt): _user_input = """ [ff] # Number of n equivalent neighbors needed to consider two atoms equivalent # Negative values turns off equivalence, 0 makes same elements equivalent n_equiv = 4 :: int # Number of first n neighbors to exclude in the forcefield n_excl = 2 :: int :: [2, 3] # Lennard jones method for the forcefield lennard_jones = opls_auto :: str :: [gromos_auto, gromos, opls_auto, opls, gaff, gaff2, ext] # Use externally provided point charges in the file "ext_q" in the job directyory ext_charges = no :: bool # Scale QM charges to account for condensed phase polarization (should be set to 1 for gas phase) charge_scaling = 1.2 :: float # If user chooses ext_charges=True, by default fragments will still use the chosen QM method for # determining fragment charges. This is to avoid spuriously high charges on capping hydrogens. # However, using QM charges for fragments and ext_charges for the molecule can also result in # inaccuracies if these two charges are very different. use_ext_charges_for_frags = no :: bool # Additional exclusions (GROMACS format) exclusions = :: literal # Switch standard non-bonded interactions between two atoms to pair interactions # (provide atom pairs in each row) pairs = :: literal # Path for the external FF library for Lennard-Jones parameters (GROMACS format). ext_lj_lib = :: folder, optional # Lennard-Jones fudge parameter for 1-4 interactions for when "lennard_jones" is set to "ext". ext_lj_fudge = :: float, optional # Coulomb fudge parameter for 1-4 interactions for when "lennard_jones" is set to "ext". ext_q_fudge = :: float, optional # Lennard-Jones combinations rules for when "lennard_jones" is set to "ext" (GROMACS numbering). ext_comb_rule = :: int, optional :: [1, 2, 3] # Name of the atom type for capping hydrogens for when "lennard_jones" is set to "ext" ext_h_cap = :: str, optional # Set all dihedrals as rigid (no dihedral scans) all_rigid = no :: bool # Use D4 method _d4 = no :: bool # Residue name printed on the force field file (Max 5 characters) res_name = MOL :: str # Polarize a coordinate file and quit (requires itp_file) _polarize = no :: bool # Name of itp file (only needed for polarize option) _itp_file = itp_file_missing :: str # Make a polarizable FF _polar = no :: bool # Scale the C6 dispersion interactions in the polarizable version of the FF _polar_c6_scale = 0.8 :: float # Specifically not scale some of the atoms _polar_not_scale_c6 = :: literal # Manual polarizabilities in the file ext_alpha _ext_alpha = no :: bool """ @staticmethod def _set_config(config): config['qm'].update(config['qm']['software']) config['qm'].update({'software': config['qm']['software'].value}) config.update({key: SimpleNamespace(**val) for key, val in config.items()}) return SimpleNamespace(**config) @classmethod def _extend_user_input(cls, questions): questions.generate_block("qm", QM.colt_user_input) questions.generate_block("scan", DihedralScan.colt_user_input) questions.generate_cases("software", {key: software.colt_user_input for key, software in implemented_qm_software.items()}, block='qm') questions.generate_block("terms", Terms.get_questions()) @classmethod def from_config(cls, config): return cls._set_config(config) @staticmethod def set_basis(value): if value.endswith('**'): return f'{value[:-2]}(D,P)'.upper() if value.endswith('*'): return f'{value[:-1]}(D)'.upper() return value.upper() @staticmethod def set_dispersion(value): if value.lower() in ["no", "false", "n", "f"]: return False return value.upper() def _get_job_info(filename): job = {} filename = filename.rstrip('/') base = os.path.basename(filename) path = os.path.dirname(filename) if path != '': path = f'{path}/' if os.path.isfile(filename): job['coord_file'] = filename job['name'] = base.split('.')[0] else: job['coord_file'] = False job['name'] = base.split('_qforce')[0] job['dir'] = f'{path}{job['name']}_qforce' job['frag_dir'] = f'{job['dir']}/fragments' job['md_data'] = pkg_resources.resource_filename('qforce', 'data') os.makedirs(job['dir'], exist_ok=True) return SimpleNamespace(**job) def _check_and_copy_settings_file(job_dir, config_file): """ If options are provided as a file, copy that to job directory. If options are provided as StringIO, write that to job directory. """ settings_file = os.path.join(job_dir, 'settings.ini') if config_file is not None: if isinstance(config_file, StringIO): with open(settings_file, 'w') as fh: config_file.seek(0) fh.write(config_file.read()) else: shutil.copy2(config_file, settings_file) return settings_file def initialize(filename, config_file, presets=None): print(LOGO) job_info = _get_job_info(filename) settings_file = _check_and_copy_settings_file(job_info.dir, config_file) config = Initialize.from_questions(config=settings_file, presets=presets, check_only=True) return config, job_info
import os import shutil from io import StringIO from types import SimpleNamespace import pkg_resources # from colt import Colt # from .qm.qm import QM, implemented_qm_software from .molecule.terms import Terms from .dihedral_scan import DihedralScan from .misc import LOGO class Initialize(Colt): _user_input = """ [ff] # Number of n equivalent neighbors needed to consider two atoms equivalent # Negative values turns off equivalence, 0 makes same elements equivalent n_equiv = 4 :: int # Number of first n neighbors to exclude in the forcefield n_excl = 2 :: int :: [2, 3] # Lennard jones method for the forcefield lennard_jones = opls_auto :: str :: [gromos_auto, gromos, opls_auto, opls, gaff, gaff2, ext] # Use externally provided point charges in the file "ext_q" in the job directyory ext_charges = no :: bool # Scale QM charges to account for condensed phase polarization (should be set to 1 for gas phase) charge_scaling = 1.2 :: float # If user chooses ext_charges=True, by default fragments will still use the chosen QM method for # determining fragment charges. This is to avoid spuriously high charges on capping hydrogens. # However, using QM charges for fragments and ext_charges for the molecule can also result in # inaccuracies if these two charges are very different. use_ext_charges_for_frags = no :: bool # Additional exclusions (GROMACS format) exclusions = :: literal # Switch standard non-bonded interactions between two atoms to pair interactions # (provide atom pairs in each row) pairs = :: literal # Path for the external FF library for Lennard-Jones parameters (GROMACS format). ext_lj_lib = :: folder, optional # Lennard-Jones fudge parameter for 1-4 interactions for when "lennard_jones" is set to "ext". ext_lj_fudge = :: float, optional # Coulomb fudge parameter for 1-4 interactions for when "lennard_jones" is set to "ext". ext_q_fudge = :: float, optional # Lennard-Jones combinations rules for when "lennard_jones" is set to "ext" (GROMACS numbering). ext_comb_rule = :: int, optional :: [1, 2, 3] # Name of the atom type for capping hydrogens for when "lennard_jones" is set to "ext" ext_h_cap = :: str, optional # Set all dihedrals as rigid (no dihedral scans) all_rigid = no :: bool # Use D4 method _d4 = no :: bool # Residue name printed on the force field file (Max 5 characters) res_name = MOL :: str # Polarize a coordinate file and quit (requires itp_file) _polarize = no :: bool # Name of itp file (only needed for polarize option) _itp_file = itp_file_missing :: str # Make a polarizable FF _polar = no :: bool # Scale the C6 dispersion interactions in the polarizable version of the FF _polar_c6_scale = 0.8 :: float # Specifically not scale some of the atoms _polar_not_scale_c6 = :: literal # Manual polarizabilities in the file ext_alpha _ext_alpha = no :: bool """ @staticmethod def _set_config(config): config['qm'].update(config['qm']['software']) config['qm'].update({'software': config['qm']['software'].value}) config.update({key: SimpleNamespace(**val) for key, val in config.items()}) return SimpleNamespace(**config) @classmethod def _extend_user_input(cls, questions): questions.generate_block("qm", QM.colt_user_input) questions.generate_block("scan", DihedralScan.colt_user_input) questions.generate_cases("software", {key: software.colt_user_input for key, software in implemented_qm_software.items()}, block='qm') questions.generate_block("terms", Terms.get_questions()) @classmethod def from_config(cls, config): return cls._set_config(config) @staticmethod def set_basis(value): if value.endswith('**'): return f'{value[:-2]}(D,P)'.upper() if value.endswith('*'): return f'{value[:-1]}(D)'.upper() return value.upper() @staticmethod def set_dispersion(value): if value.lower() in ["no", "false", "n", "f"]: return False return value.upper() def _get_job_info(filename): job = {} filename = filename.rstrip('/') base = os.path.basename(filename) path = os.path.dirname(filename) if path != '': path = f'{path}/' if os.path.isfile(filename): job['coord_file'] = filename job['name'] = base.split('.')[0] else: job['coord_file'] = False job['name'] = base.split('_qforce')[0] job['dir'] = f'{path}{job["name"]}_qforce' job['frag_dir'] = f'{job["dir"]}/fragments' job['md_data'] = pkg_resources.resource_filename('qforce', 'data') os.makedirs(job['dir'], exist_ok=True) return SimpleNamespace(**job) def _check_and_copy_settings_file(job_dir, config_file): """ If options are provided as a file, copy that to job directory. If options are provided as StringIO, write that to job directory. """ settings_file = os.path.join(job_dir, 'settings.ini') if config_file is not None: if isinstance(config_file, StringIO): with open(settings_file, 'w') as fh: config_file.seek(0) fh.write(config_file.read()) else: shutil.copy2(config_file, settings_file) return settings_file def initialize(filename, config_file, presets=None): print(LOGO) job_info = _get_job_info(filename) settings_file = _check_and_copy_settings_file(job_info.dir, config_file) config = Initialize.from_questions(config=settings_file, presets=presets, check_only=True) return config, job_info
import os import re import sys # Read arguments if len(sys.argv) != 2: raise ValueError('Please provide a filename input') filename = sys.argv[1] # Read file file_data = open(os.getcwd() + '/' + filename, 'r') # Parse file tiles = [] for line in file_data.readlines(): line = line.replace('\n', '') line = re.sub(r'(e|w|se|sw|nw|ne)', r'\1|', line) dirs = line.split('|') dirs.remove('') tiles.append(dirs) # Get answer pos = [{'e': 0, 'w': 0, 'se': 0, 'sw': 0, 'nw': 0, 'ne': 0} for i in range(len(tiles))] for i, t in enumerate(tiles): for m in t: pos[i][m] += 1 pos_p = [] for p in pos: # Remove unecessary moves se = p['se'] - p['nw'] ne = p['ne'] - p['sw'] e = p['e'] - p['w'] # Transform to only two coords x = e y = se x += ne y -= ne pos_p.append({ 'x': x, 'y': y, }) counts = {} for p in pos_p: t = f'{p['x']}|{p['y']}' if t in counts: counts[t] += 1 else: counts[t] = 1 answer = 0 for c in counts: if counts[c] % 2 != 0: answer += 1 print(answer)
import os import re import sys # Read arguments if len(sys.argv) != 2: raise ValueError('Please provide a filename input') filename = sys.argv[1] # Read file file_data = open(os.getcwd() + '/' + filename, 'r') # Parse file tiles = [] for line in file_data.readlines(): line = line.replace('\n', '') line = re.sub(r'(e|w|se|sw|nw|ne)', r'\1|', line) dirs = line.split('|') dirs.remove('') tiles.append(dirs) # Get answer pos = [{'e': 0, 'w': 0, 'se': 0, 'sw': 0, 'nw': 0, 'ne': 0} for i in range(len(tiles))] for i, t in enumerate(tiles): for m in t: pos[i][m] += 1 pos_p = [] for p in pos: # Remove unecessary moves se = p['se'] - p['nw'] ne = p['ne'] - p['sw'] e = p['e'] - p['w'] # Transform to only two coords x = e y = se x += ne y -= ne pos_p.append({ 'x': x, 'y': y, }) counts = {} for p in pos_p: t = f'{p["x"]}|{p["y"]}' if t in counts: counts[t] += 1 else: counts[t] = 1 answer = 0 for c in counts: if counts[c] % 2 != 0: answer += 1 print(answer)
#!/usr/bin/env python # Notes on formulas # ----------------- # # There are four output types of formulas: # # 1. string # 2. number # 3. date — never a date range, unlike date properties # 4. boolean # Notes on rollups # ---------------- # # There are four signatures of rollup functions: # # 1. any -> array[any] # * show_original # * show_unique # 2. any -> number # * count / count_all # * count_values # * unique / count_unique_values # * empty / count_empty # * not_empty / count_not_empty # * percent_empty # * percent_not_empty # 3. number -> number # * sum # * average # * median # * min # * max # * range # 4. date -> date # * earliest_date # * latest_date # * date_range # # Rollups returning arrays aren't implemented. Tables containing such rollups # can stil be imported but these rollups will be ignored. # # Some functions have different names in the API / documentation. This is # probably a documentation bug. We use the name that we get from the API. import argparse import datetime import json import logging import os import re import time import unicodedata import httpx import psycopg logging.basicConfig( format="%(asctime)s %(message)s", level=logging.INFO, ) DATE_RE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}") def maybe_date(value): """Fix date values when Notion returns them as datetimes.""" if value is None: return None # Switch to str.removesuffix when dropping Python 3.8. if value.endswith("T00:00:00.000+00:00"): return value[:-19] return value INVALID_IN_NAME_RE = re.compile("[^a-z0-9_]") # Maximum total delay for a single call is 2047 seconds which should let Notion # recover from most temporary issues. DELAY = 1 # before HTTP requests when reading databases, for throttling RETRIES = 10 # retry queries up to RETRIES times BACKOFF = 2 # multiply DELAY by BACKOFF between retries PAGE_SIZE = 64 # lower than the default of 100 to prevent timeouts TIMEOUT = 120 # seconds :-( Notion's API isn't all that fast def get_database(database_id, token): """Get properties of a Notion database.""" t0 = time.perf_counter() data = httpx.get( f"https://api.notion.com/v1/databases/{database_id}", headers={ "Authorization": f"Bearer {token}", "Notion-Version": "2021-08-16", }, ).json() t1 = time.perf_counter() if data["object"] == "error": logging.error( "Failed to fetch the next pages: Notion API error: HTTP %s: %s", data["status"], data["message"], ) raise RuntimeError(f"HTTP {data["status"]}: {data["message"]}") logging.info( "Fetched Notion database %s in %.1f seconds", database_id, t1 - t0, ) return data def iter_database(database_id, token): """Iterate over the pages of a Notion database.""" has_more = True query = { "sorts": [{"timestamp": "created_time", "direction": "descending"}], "page_size": PAGE_SIZE, } while has_more: t0 = time.perf_counter() delay = DELAY for retry in range(RETRIES): try: time.sleep(delay) data = httpx.post( f"https://api.notion.com/v1/databases/{database_id}/query", headers={ "Authorization": f"Bearer {token}", "Notion-Version": "2021-08-16", }, json=query, timeout=TIMEOUT, ).json() except httpx.RequestError as exc: logging.warning( "Failed to fetch the next pages: HTTP request error: %s", exc, ) if retry == RETRIES - 1: raise else: delay *= BACKOFF continue except json.JSONDecodeError as exc: logging.warning( "Failed to parse response: JSON decode error: %s", exc, ) if retry == RETRIES - 1: raise else: delay *= BACKOFF continue if data["object"] == "error": logging.error( "Failed to fetch the next pages: Notion API error: HTTP %s: %s", data["status"], data["message"], ) if retry == RETRIES - 1: raise RuntimeError(f"HTTP {data["status"]}: {data["message"]}") else: delay *= BACKOFF continue break t1 = time.perf_counter() assert data["object"] == "list" logging.info( "Fetched %d Notion pages in %.1f seconds", len(data["results"]), t1 - t0, ) has_more = data["has_more"] query["start_cursor"] = data["next_cursor"] yield from data["results"] def get_value(property): """Convert a Notion property value to a Python value.""" type_ = property["type"] if type_ == "title": # Optional[str] return "".join(t["plain_text"] for t in property["title"]) or None # Basic properties elif type_ == "rich_text": # Optional[str] return "".join(t["plain_text"] for t in property["rich_text"]) or None elif type_ == "number": # Optional[Number] return property["number"] elif type_ == "select": # Optional[str] if property["select"] is None: return None return property["select"]["name"] elif type_ == "multi_select": # List[str] return [ms["name"] for ms in property["multi_select"]] elif type_ == "date": # Tuple[Optional[str], Optional[str]] - start and end date or datetime if property["date"] is None: return None, None # "The public API will always return the time_zone field as null when # rendering dates and time zone will be displayed as a UTC offset in # the start and end date fields." assert property["date"]["time_zone"] is None return property["date"]["start"], property["date"]["end"] elif type_ == "people": # List[str] - UUID of person return [p["id"] for p in property["people"]] elif type_ == "files": # List[str] - URL of the file files = [] for f in property["files"]: url = f["file"]["url"] # Remove authentication information from files uploaded to Notion; # it is too short lived to be worth storing in a database. if "/secure.notion-static.com/" in url: url = url.partition("?")[0] files.append(url) return files elif type_ == "checkbox": # bool return property["checkbox"] elif type_ == "url": # Optional[str] return property["url"] elif type_ == "email": # Optional[str] return property["email"] elif type_ == "phone_number": # Optional[str] return property["phone_number"] # Advanced properties elif type_ == "formula": formula = property["formula"] subtype = formula["type"] if subtype == "string": # str return ("string", formula["string"]) elif subtype == "number": # Optional[Number] return ("number", formula["number"]) elif subtype == "date": # Tuple[Optional[str], NoneType] - start date or datetime if formula["date"] is None: return ("date", (None, None)) assert formula["date"]["time_zone"] is None assert formula["date"]["end"] is None # Return the same format for consistency, even if end date is never set. start_date = maybe_date(formula["date"]["start"]) return ("date", (start_date, None)) elif subtype == "boolean": # bool return ("boolean", formula["boolean"]) raise NotImplementedError(f"unsupported formula: {json.dumps(formula)}") elif type_ == "relation": # List[str] - UUID of related object return [r["id"] for r in property["relation"]] elif type_ == "rollup": rollup = property["rollup"] subtype = rollup["type"] if subtype == "array": # Skip rollups returning arrays return ("array", []) elif subtype == "number": # Optional[Number] return ("number", rollup["number"]) elif subtype == "date": # Tuple[Optional[str], Optional[str]] - start and end date or datetime if rollup["date"] is None: return ("date", (None, None)) assert rollup["date"]["time_zone"] is None start_date = maybe_date(rollup["date"]["start"]) end_date = maybe_date(rollup["date"]["end"]) return ("date", (start_date, end_date)) raise NotImplementedError(f"unsupported rollup: {json.dumps(rollup)}") elif type_ == "created_time": return property["created_time"] elif type_ == "created_by": return property["created_by"]["id"] elif type_ == "last_edited_time": return property["last_edited_time"] elif type_ == "last_edited_by": return property["last_edited_by"]["id"] raise NotImplementedError(f"unsupported property: {json.dumps(property)}") def convert(property, values): """Convert a Notion property to a PostgreSQL column.""" type_ = property["type"] if type_ == "title": return "text", values # Basic properties elif type_ == "rich_text": return "text", values elif type_ == "number": if all(isinstance(value, int) for value in values if value is not None): return "integer", values else: return "double precision", values elif type_ == "select": return "text", values elif type_ == "multi_select": return "text[]", values elif type_ == "date": if any(value[1] is not None for value in values): # This is a range of dates or datetimes. if all( DATE_RE.fullmatch(value[0]) for value in values if value[0] is not None ) and all( DATE_RE.fullmatch(value[1]) for value in values if value[1] is not None ): return "daterange", values else: return "tstzrange", values else: # This is a date or datetime. values = [value[0] for value in values] if all(DATE_RE.fullmatch(value) for value in values if value is not None): return "date", values else: return "timestamp with time zone", values elif type_ == "people": if all(len(value) <= 1 for value in values): return "uuid", [value[0] if value else None for value in values] else: return "uuid[]", values elif type_ == "files": if all(len(value) <= 1 for value in values): return "text", [value[0] if value else None for value in values] else: return "text[]", values elif type_ == "checkbox": return "boolean", values elif type_ == "url": return "text", values elif type_ == "email": return "text", values elif type_ == "phone_number": return "text", values # Advanced properties elif type_ == "formula": (subtype,) = set(value[0] for value in values) values = list(value[1] for value in values) if subtype == "string": return "text", values elif subtype == "number": return convert({"type": "number"}, values) elif subtype == "date": return convert({"type": "date"}, values) elif subtype == "boolean": return "boolean", values formula = property["formula"] raise NotImplementedError(f"unsupported formula: {json.dumps(formula)}") elif type_ == "relation": if all(len(value) <= 1 for value in values): return "uuid", [value[0] if value else None for value in values] else: return "uuid[]", values elif type_ == "rollup": (subtype,) = set(value[0] for value in values) values = list(value[1] for value in values) if subtype == "array": # Skip rollups returning arrays return None, values elif subtype == "number": return convert({"type": "number"}, values) elif subtype == "date": return convert({"type": "date"}, values) rollup = property["rollup"] raise NotImplementedError(f"unsupported rollup: {json.dumps(rollup)}") elif type_ == "created_time": return "timestamp with time zone", values elif type_ == "created_by": return "uuid", values elif type_ == "last_edited_time": return "timestamp with time zone", values elif type_ == "last_edited_by": return "uuid", values raise NotImplementedError(f"unsupported property: {json.dumps(property)}") def sanitize_name(name): """Convert a Notion property name to a PostgreSQL column name.""" name = unicodedata.normalize("NFKD", name) name = name.encode("ascii", "ignore").decode() name = name.lower().strip().replace(" ", "_") name = INVALID_IN_NAME_RE.sub("", name) return name def create_table(dsn, table_name, field_names, field_types, rows, drop, timestamp): """Create a PostgreSQL table.""" with psycopg.connect(dsn) as connection: with connection.cursor() as cursor: if timestamp is not None: view_name, table_name = table_name, table_name + timestamp if drop: cursor.execute(f"DROP TABLE IF EXISTS {table_name}") logging.info("Dropped PostgreSQL table %s", table_name) columns = ", ".join( f"{name} {type}" for name, type in zip(field_names, field_types) ) cursor.execute(f"CREATE TABLE {table_name} ({columns})") logging.info("Created PostgreSQL table %s", table_name) columns = ", ".join(field_names) with cursor.copy(f"COPY {table_name} ({columns}) FROM STDIN") as copy: for row in rows: copy.write_row(row) logging.info("Wrote %d rows to PostgreSQL", len(rows)) if timestamp is not None: cursor.execute( f"CREATE OR REPLACE VIEW {view_name} AS " f"SELECT * from {table_name}" ) logging.info("Created PostgreSQL view %s", view_name) connection.commit() def sync_database(database_id, table_name, drop_existing=False, versioned=False): """Sync a database from Notion to PostgreSQL.""" # Validate env vars. try: # Integration needs access to tables that will be synced and to every # table referenced by a relation or a rollup. token = os.environ["NOTION_TOKEN"] except KeyError: raise RuntimeError("missing environment variable NOTION_TOKEN") from None try: dsn = os.environ["POSTGRESQL_DSN"] except KeyError: raise RuntimeError("missing environment variable POSTGRESQL_DSN") from None # Validate arguments. DATABASE_ID_RE = re.compile(r"[0-9a-f]{32}") if not DATABASE_ID_RE.fullmatch(database_id): raise ValueError( f"invalid Notion database ID: {database_id}; " f"must match {DATABASE_ID_RE.pattern}" ) # PostgreSQL supports 31 characters in a name. We need 14 for the timestamp. TABLE_NAME_RE = re.compile(r"[a-z_][a-z0-9_]+") if not TABLE_NAME_RE.fullmatch(table_name): raise ValueError( f"invalid PostgreSQL table name: {table_name}; " f"must match {TABLE_NAME_RE.pattern}" ) TABLE_NAME_MAX_LENGTH = 17 if versioned else 31 if len(table_name) > TABLE_NAME_MAX_LENGTH: raise ValueError( f"invalid PostgreSQL table name: {table_name}; " f"must contain no more than {TABLE_NAME_MAX_LENGTH} characters" ) timestamp = datetime.datetime.utcnow().strftime("_%y%m%d_%H%M%S") # Read the Notion database structure and content in memory. database = get_database(database_id, token) pages = list(iter_database(database_id, token)) # Convert to PostgreSQL field types and corresponding column values. field_names = ["id"] field_types = ["uuid"] columns = [[page["id"] for page in pages]] # Notion returns properties ordered by the opaque "id" attribute. # Sort them alphabetically to get a more predictable result. for name, property in sorted(database["properties"].items()): assert name == property["name"] # Notion duplicates this info values = [get_value(page["properties"][name]) for page in pages] field_type, column = convert(property, values) if field_type is None: logging.info('Skipping unsupported property "%s"', name) continue logging.info('Converted property "%s" to %s', name, field_type) field_names.append(sanitize_name(name)) field_types.append(field_type) columns.append(column) rows = list(zip(*columns)) # Write PostgreSQL table. create_table( dsn, table_name, field_names, field_types, rows, drop=drop_existing, timestamp=timestamp if versioned else None, ) def main(): parser = argparse.ArgumentParser( description="Import a Notion database to a PostgreSQL table" ) parser.add_argument("database_id", help="Notion database ID") parser.add_argument("table_name", help="PostgreSQL table name") parser.add_argument( "--drop-existing", action="store_true", help="Drop table if it exists" ) parser.add_argument( "--versioned", action="store_true", help="Import into a timestamped table" ) sync_database(**vars(parser.parse_args())) if __name__ == "__main__": main()
#!/usr/bin/env python # Notes on formulas # ----------------- # # There are four output types of formulas: # # 1. string # 2. number # 3. date — never a date range, unlike date properties # 4. boolean # Notes on rollups # ---------------- # # There are four signatures of rollup functions: # # 1. any -> array[any] # * show_original # * show_unique # 2. any -> number # * count / count_all # * count_values # * unique / count_unique_values # * empty / count_empty # * not_empty / count_not_empty # * percent_empty # * percent_not_empty # 3. number -> number # * sum # * average # * median # * min # * max # * range # 4. date -> date # * earliest_date # * latest_date # * date_range # # Rollups returning arrays aren't implemented. Tables containing such rollups # can stil be imported but these rollups will be ignored. # # Some functions have different names in the API / documentation. This is # probably a documentation bug. We use the name that we get from the API. import argparse import datetime import json import logging import os import re import time import unicodedata import httpx import psycopg logging.basicConfig( format="%(asctime)s %(message)s", level=logging.INFO, ) DATE_RE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}") def maybe_date(value): """Fix date values when Notion returns them as datetimes.""" if value is None: return None # Switch to str.removesuffix when dropping Python 3.8. if value.endswith("T00:00:00.000+00:00"): return value[:-19] return value INVALID_IN_NAME_RE = re.compile("[^a-z0-9_]") # Maximum total delay for a single call is 2047 seconds which should let Notion # recover from most temporary issues. DELAY = 1 # before HTTP requests when reading databases, for throttling RETRIES = 10 # retry queries up to RETRIES times BACKOFF = 2 # multiply DELAY by BACKOFF between retries PAGE_SIZE = 64 # lower than the default of 100 to prevent timeouts TIMEOUT = 120 # seconds :-( Notion's API isn't all that fast def get_database(database_id, token): """Get properties of a Notion database.""" t0 = time.perf_counter() data = httpx.get( f"https://api.notion.com/v1/databases/{database_id}", headers={ "Authorization": f"Bearer {token}", "Notion-Version": "2021-08-16", }, ).json() t1 = time.perf_counter() if data["object"] == "error": logging.error( "Failed to fetch the next pages: Notion API error: HTTP %s: %s", data["status"], data["message"], ) raise RuntimeError(f"HTTP {data['status']}: {data['message']}") logging.info( "Fetched Notion database %s in %.1f seconds", database_id, t1 - t0, ) return data def iter_database(database_id, token): """Iterate over the pages of a Notion database.""" has_more = True query = { "sorts": [{"timestamp": "created_time", "direction": "descending"}], "page_size": PAGE_SIZE, } while has_more: t0 = time.perf_counter() delay = DELAY for retry in range(RETRIES): try: time.sleep(delay) data = httpx.post( f"https://api.notion.com/v1/databases/{database_id}/query", headers={ "Authorization": f"Bearer {token}", "Notion-Version": "2021-08-16", }, json=query, timeout=TIMEOUT, ).json() except httpx.RequestError as exc: logging.warning( "Failed to fetch the next pages: HTTP request error: %s", exc, ) if retry == RETRIES - 1: raise else: delay *= BACKOFF continue except json.JSONDecodeError as exc: logging.warning( "Failed to parse response: JSON decode error: %s", exc, ) if retry == RETRIES - 1: raise else: delay *= BACKOFF continue if data["object"] == "error": logging.error( "Failed to fetch the next pages: Notion API error: HTTP %s: %s", data["status"], data["message"], ) if retry == RETRIES - 1: raise RuntimeError(f"HTTP {data['status']}: {data['message']}") else: delay *= BACKOFF continue break t1 = time.perf_counter() assert data["object"] == "list" logging.info( "Fetched %d Notion pages in %.1f seconds", len(data["results"]), t1 - t0, ) has_more = data["has_more"] query["start_cursor"] = data["next_cursor"] yield from data["results"] def get_value(property): """Convert a Notion property value to a Python value.""" type_ = property["type"] if type_ == "title": # Optional[str] return "".join(t["plain_text"] for t in property["title"]) or None # Basic properties elif type_ == "rich_text": # Optional[str] return "".join(t["plain_text"] for t in property["rich_text"]) or None elif type_ == "number": # Optional[Number] return property["number"] elif type_ == "select": # Optional[str] if property["select"] is None: return None return property["select"]["name"] elif type_ == "multi_select": # List[str] return [ms["name"] for ms in property["multi_select"]] elif type_ == "date": # Tuple[Optional[str], Optional[str]] - start and end date or datetime if property["date"] is None: return None, None # "The public API will always return the time_zone field as null when # rendering dates and time zone will be displayed as a UTC offset in # the start and end date fields." assert property["date"]["time_zone"] is None return property["date"]["start"], property["date"]["end"] elif type_ == "people": # List[str] - UUID of person return [p["id"] for p in property["people"]] elif type_ == "files": # List[str] - URL of the file files = [] for f in property["files"]: url = f["file"]["url"] # Remove authentication information from files uploaded to Notion; # it is too short lived to be worth storing in a database. if "/secure.notion-static.com/" in url: url = url.partition("?")[0] files.append(url) return files elif type_ == "checkbox": # bool return property["checkbox"] elif type_ == "url": # Optional[str] return property["url"] elif type_ == "email": # Optional[str] return property["email"] elif type_ == "phone_number": # Optional[str] return property["phone_number"] # Advanced properties elif type_ == "formula": formula = property["formula"] subtype = formula["type"] if subtype == "string": # str return ("string", formula["string"]) elif subtype == "number": # Optional[Number] return ("number", formula["number"]) elif subtype == "date": # Tuple[Optional[str], NoneType] - start date or datetime if formula["date"] is None: return ("date", (None, None)) assert formula["date"]["time_zone"] is None assert formula["date"]["end"] is None # Return the same format for consistency, even if end date is never set. start_date = maybe_date(formula["date"]["start"]) return ("date", (start_date, None)) elif subtype == "boolean": # bool return ("boolean", formula["boolean"]) raise NotImplementedError(f"unsupported formula: {json.dumps(formula)}") elif type_ == "relation": # List[str] - UUID of related object return [r["id"] for r in property["relation"]] elif type_ == "rollup": rollup = property["rollup"] subtype = rollup["type"] if subtype == "array": # Skip rollups returning arrays return ("array", []) elif subtype == "number": # Optional[Number] return ("number", rollup["number"]) elif subtype == "date": # Tuple[Optional[str], Optional[str]] - start and end date or datetime if rollup["date"] is None: return ("date", (None, None)) assert rollup["date"]["time_zone"] is None start_date = maybe_date(rollup["date"]["start"]) end_date = maybe_date(rollup["date"]["end"]) return ("date", (start_date, end_date)) raise NotImplementedError(f"unsupported rollup: {json.dumps(rollup)}") elif type_ == "created_time": return property["created_time"] elif type_ == "created_by": return property["created_by"]["id"] elif type_ == "last_edited_time": return property["last_edited_time"] elif type_ == "last_edited_by": return property["last_edited_by"]["id"] raise NotImplementedError(f"unsupported property: {json.dumps(property)}") def convert(property, values): """Convert a Notion property to a PostgreSQL column.""" type_ = property["type"] if type_ == "title": return "text", values # Basic properties elif type_ == "rich_text": return "text", values elif type_ == "number": if all(isinstance(value, int) for value in values if value is not None): return "integer", values else: return "double precision", values elif type_ == "select": return "text", values elif type_ == "multi_select": return "text[]", values elif type_ == "date": if any(value[1] is not None for value in values): # This is a range of dates or datetimes. if all( DATE_RE.fullmatch(value[0]) for value in values if value[0] is not None ) and all( DATE_RE.fullmatch(value[1]) for value in values if value[1] is not None ): return "daterange", values else: return "tstzrange", values else: # This is a date or datetime. values = [value[0] for value in values] if all(DATE_RE.fullmatch(value) for value in values if value is not None): return "date", values else: return "timestamp with time zone", values elif type_ == "people": if all(len(value) <= 1 for value in values): return "uuid", [value[0] if value else None for value in values] else: return "uuid[]", values elif type_ == "files": if all(len(value) <= 1 for value in values): return "text", [value[0] if value else None for value in values] else: return "text[]", values elif type_ == "checkbox": return "boolean", values elif type_ == "url": return "text", values elif type_ == "email": return "text", values elif type_ == "phone_number": return "text", values # Advanced properties elif type_ == "formula": (subtype,) = set(value[0] for value in values) values = list(value[1] for value in values) if subtype == "string": return "text", values elif subtype == "number": return convert({"type": "number"}, values) elif subtype == "date": return convert({"type": "date"}, values) elif subtype == "boolean": return "boolean", values formula = property["formula"] raise NotImplementedError(f"unsupported formula: {json.dumps(formula)}") elif type_ == "relation": if all(len(value) <= 1 for value in values): return "uuid", [value[0] if value else None for value in values] else: return "uuid[]", values elif type_ == "rollup": (subtype,) = set(value[0] for value in values) values = list(value[1] for value in values) if subtype == "array": # Skip rollups returning arrays return None, values elif subtype == "number": return convert({"type": "number"}, values) elif subtype == "date": return convert({"type": "date"}, values) rollup = property["rollup"] raise NotImplementedError(f"unsupported rollup: {json.dumps(rollup)}") elif type_ == "created_time": return "timestamp with time zone", values elif type_ == "created_by": return "uuid", values elif type_ == "last_edited_time": return "timestamp with time zone", values elif type_ == "last_edited_by": return "uuid", values raise NotImplementedError(f"unsupported property: {json.dumps(property)}") def sanitize_name(name): """Convert a Notion property name to a PostgreSQL column name.""" name = unicodedata.normalize("NFKD", name) name = name.encode("ascii", "ignore").decode() name = name.lower().strip().replace(" ", "_") name = INVALID_IN_NAME_RE.sub("", name) return name def create_table(dsn, table_name, field_names, field_types, rows, drop, timestamp): """Create a PostgreSQL table.""" with psycopg.connect(dsn) as connection: with connection.cursor() as cursor: if timestamp is not None: view_name, table_name = table_name, table_name + timestamp if drop: cursor.execute(f"DROP TABLE IF EXISTS {table_name}") logging.info("Dropped PostgreSQL table %s", table_name) columns = ", ".join( f"{name} {type}" for name, type in zip(field_names, field_types) ) cursor.execute(f"CREATE TABLE {table_name} ({columns})") logging.info("Created PostgreSQL table %s", table_name) columns = ", ".join(field_names) with cursor.copy(f"COPY {table_name} ({columns}) FROM STDIN") as copy: for row in rows: copy.write_row(row) logging.info("Wrote %d rows to PostgreSQL", len(rows)) if timestamp is not None: cursor.execute( f"CREATE OR REPLACE VIEW {view_name} AS " f"SELECT * from {table_name}" ) logging.info("Created PostgreSQL view %s", view_name) connection.commit() def sync_database(database_id, table_name, drop_existing=False, versioned=False): """Sync a database from Notion to PostgreSQL.""" # Validate env vars. try: # Integration needs access to tables that will be synced and to every # table referenced by a relation or a rollup. token = os.environ["NOTION_TOKEN"] except KeyError: raise RuntimeError("missing environment variable NOTION_TOKEN") from None try: dsn = os.environ["POSTGRESQL_DSN"] except KeyError: raise RuntimeError("missing environment variable POSTGRESQL_DSN") from None # Validate arguments. DATABASE_ID_RE = re.compile(r"[0-9a-f]{32}") if not DATABASE_ID_RE.fullmatch(database_id): raise ValueError( f"invalid Notion database ID: {database_id}; " f"must match {DATABASE_ID_RE.pattern}" ) # PostgreSQL supports 31 characters in a name. We need 14 for the timestamp. TABLE_NAME_RE = re.compile(r"[a-z_][a-z0-9_]+") if not TABLE_NAME_RE.fullmatch(table_name): raise ValueError( f"invalid PostgreSQL table name: {table_name}; " f"must match {TABLE_NAME_RE.pattern}" ) TABLE_NAME_MAX_LENGTH = 17 if versioned else 31 if len(table_name) > TABLE_NAME_MAX_LENGTH: raise ValueError( f"invalid PostgreSQL table name: {table_name}; " f"must contain no more than {TABLE_NAME_MAX_LENGTH} characters" ) timestamp = datetime.datetime.utcnow().strftime("_%y%m%d_%H%M%S") # Read the Notion database structure and content in memory. database = get_database(database_id, token) pages = list(iter_database(database_id, token)) # Convert to PostgreSQL field types and corresponding column values. field_names = ["id"] field_types = ["uuid"] columns = [[page["id"] for page in pages]] # Notion returns properties ordered by the opaque "id" attribute. # Sort them alphabetically to get a more predictable result. for name, property in sorted(database["properties"].items()): assert name == property["name"] # Notion duplicates this info values = [get_value(page["properties"][name]) for page in pages] field_type, column = convert(property, values) if field_type is None: logging.info('Skipping unsupported property "%s"', name) continue logging.info('Converted property "%s" to %s', name, field_type) field_names.append(sanitize_name(name)) field_types.append(field_type) columns.append(column) rows = list(zip(*columns)) # Write PostgreSQL table. create_table( dsn, table_name, field_names, field_types, rows, drop=drop_existing, timestamp=timestamp if versioned else None, ) def main(): parser = argparse.ArgumentParser( description="Import a Notion database to a PostgreSQL table" ) parser.add_argument("database_id", help="Notion database ID") parser.add_argument("table_name", help="PostgreSQL table name") parser.add_argument( "--drop-existing", action="store_true", help="Drop table if it exists" ) parser.add_argument( "--versioned", action="store_true", help="Import into a timestamped table" ) sync_database(**vars(parser.parse_args())) if __name__ == "__main__": main()
#!/usr/bin/env python # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ Implementation for `pmg config` CLI. """ import glob import os import shutil import subprocess import sys from urllib.request import urlretrieve from monty.serialization import dumpfn, loadfn from pymatgen.core import SETTINGS_FILE def setup_potcars(args): """ Setup POTCAR directirt, :param args: args from command. """ pspdir, targetdir = (os.path.abspath(d) for d in args.potcar_dirs) try: os.makedirs(targetdir) except OSError: r = input("Destination directory exists. Continue (y/n)? ") if r != "y": print("Exiting ...") sys.exit(0) print("Generating pymatgen resources directory...") name_mappings = { "potpaw_PBE": "POT_GGA_PAW_PBE", "potpaw_PBE_52": "POT_GGA_PAW_PBE_52", "potpaw_PBE_54": "POT_GGA_PAW_PBE_54", "potpaw_PBE.52": "POT_GGA_PAW_PBE_52", "potpaw_PBE.54": "POT_GGA_PAW_PBE_54", "potpaw_LDA": "POT_LDA_PAW", "potpaw_LDA.52": "POT_LDA_PAW_52", "potpaw_LDA.54": "POT_LDA_PAW_54", "potpaw_LDA_52": "POT_LDA_PAW_52", "potpaw_LDA_54": "POT_LDA_PAW_54", "potUSPP_LDA": "POT_LDA_US", "potpaw_GGA": "POT_GGA_PAW_PW91", "potUSPP_GGA": "POT_GGA_US_PW91", } for (parent, subdirs, files) in os.walk(pspdir): basename = os.path.basename(parent) basename = name_mappings.get(basename, basename) for subdir in subdirs: filenames = glob.glob(os.path.join(parent, subdir, "POTCAR*")) if len(filenames) > 0: try: basedir = os.path.join(targetdir, basename) if not os.path.exists(basedir): os.makedirs(basedir) fname = filenames[0] dest = os.path.join(basedir, os.path.basename(fname)) shutil.copy(fname, dest) ext = fname.split(".")[-1] if ext.upper() in ["Z", "GZ"]: with subprocess.Popen(["gunzip", dest]) as p: p.communicate() elif ext.upper() in ["BZ2"]: with subprocess.Popen(["bunzip2", dest]) as p: p.communicate() if subdir == "Osmium": subdir = "Os" dest = os.path.join(basedir, f"POTCAR.{subdir}") shutil.move(os.path.join(basedir, "POTCAR"), dest) with subprocess.Popen(["gzip", "-f", dest]) as p: p.communicate() except Exception as ex: print(f"An error has occurred. Message is {str(ex)}. Trying to continue... ") print("") print( "PSP resources directory generated. It is recommended that you " "run 'pmg config --add PMG_VASP_PSP_DIR %s'" % os.path.abspath(targetdir) ) print("Start a new terminal to ensure that your environment variables are properly set.") def build_enum(fortran_command="gfortran"): """ Build enum. :param fortran_command: """ currdir = os.getcwd() state = True try: subprocess.call(["git", "clone", "--recursive", "https://github.com/msg-byu/enumlib.git"]) os.chdir(os.path.join(currdir, "enumlib", "symlib", "src")) os.environ["F90"] = fortran_command subprocess.call(["make"]) enumpath = os.path.join(currdir, "enumlib", "src") os.chdir(enumpath) subprocess.call(["make"]) for f in ["enum.x", "makestr.x"]: subprocess.call(["make", f]) shutil.copy(f, os.path.join("..", "..")) except Exception as ex: print(str(ex)) state = False finally: os.chdir(currdir) shutil.rmtree("enumlib") return state def build_bader(fortran_command="gfortran"): """ Build bader package. :param fortran_command: """ bader_url = "http://theory.cm.utexas.edu/henkelman/code/bader/download/bader.tar.gz" currdir = os.getcwd() state = True try: urlretrieve(bader_url, "bader.tar.gz") subprocess.call(["tar", "-zxf", "bader.tar.gz"]) os.chdir("bader") subprocess.call(["cp", "makefile.osx_" + fortran_command, "makefile"]) subprocess.call(["make"]) shutil.copy("bader", os.path.join("..", "bader_exe")) os.chdir("..") shutil.rmtree("bader") os.remove("bader.tar.gz") shutil.move("bader_exe", "bader") except Exception as ex: print(str(ex)) state = False finally: os.chdir(currdir) return state def install_software(args): """ Install all optional external software. :param args: """ try: subprocess.call(["ifort", "--version"]) print("Found ifort") fortran_command = "ifort" except Exception: try: subprocess.call(["gfortran", "--version"]) print("Found gfortran") fortran_command = "gfortran" except Exception as ex: print(str(ex)) print("No fortran compiler found.") sys.exit(-1) enum = None bader = None if args.install == "enumlib": print("Building enumlib") enum = build_enum(fortran_command) print("") elif args.install == "bader": print("Building bader") bader = build_bader(fortran_command) print("") if bader or enum: print( "Please add {} to your PATH or move the executables multinum.x, " "makestr.x and/or bader to a location in your PATH.".format(os.path.abspath(".")) ) print("") def add_config_var(args): """ Add configuration args. :param args: """ d = {} if os.path.exists(SETTINGS_FILE): shutil.copy(SETTINGS_FILE, SETTINGS_FILE + ".bak") print(f"Existing {SETTINGS_FILE} backed up to {SETTINGS_FILE + ".bak"}") d = loadfn(SETTINGS_FILE) toks = args.var_spec if len(toks) % 2 != 0: print("Bad variable specification!") sys.exit(-1) for i in range(int(len(toks) / 2)): d[toks[2 * i]] = toks[2 * i + 1] dumpfn(d, SETTINGS_FILE) print(f"New {SETTINGS_FILE} written!") def configure_pmg(args): """ Handle configure command. :param args: """ if args.potcar_dirs: setup_potcars(args) elif args.install: install_software(args) elif args.var_spec: add_config_var(args)
#!/usr/bin/env python # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ Implementation for `pmg config` CLI. """ import glob import os import shutil import subprocess import sys from urllib.request import urlretrieve from monty.serialization import dumpfn, loadfn from pymatgen.core import SETTINGS_FILE def setup_potcars(args): """ Setup POTCAR directirt, :param args: args from command. """ pspdir, targetdir = (os.path.abspath(d) for d in args.potcar_dirs) try: os.makedirs(targetdir) except OSError: r = input("Destination directory exists. Continue (y/n)? ") if r != "y": print("Exiting ...") sys.exit(0) print("Generating pymatgen resources directory...") name_mappings = { "potpaw_PBE": "POT_GGA_PAW_PBE", "potpaw_PBE_52": "POT_GGA_PAW_PBE_52", "potpaw_PBE_54": "POT_GGA_PAW_PBE_54", "potpaw_PBE.52": "POT_GGA_PAW_PBE_52", "potpaw_PBE.54": "POT_GGA_PAW_PBE_54", "potpaw_LDA": "POT_LDA_PAW", "potpaw_LDA.52": "POT_LDA_PAW_52", "potpaw_LDA.54": "POT_LDA_PAW_54", "potpaw_LDA_52": "POT_LDA_PAW_52", "potpaw_LDA_54": "POT_LDA_PAW_54", "potUSPP_LDA": "POT_LDA_US", "potpaw_GGA": "POT_GGA_PAW_PW91", "potUSPP_GGA": "POT_GGA_US_PW91", } for (parent, subdirs, files) in os.walk(pspdir): basename = os.path.basename(parent) basename = name_mappings.get(basename, basename) for subdir in subdirs: filenames = glob.glob(os.path.join(parent, subdir, "POTCAR*")) if len(filenames) > 0: try: basedir = os.path.join(targetdir, basename) if not os.path.exists(basedir): os.makedirs(basedir) fname = filenames[0] dest = os.path.join(basedir, os.path.basename(fname)) shutil.copy(fname, dest) ext = fname.split(".")[-1] if ext.upper() in ["Z", "GZ"]: with subprocess.Popen(["gunzip", dest]) as p: p.communicate() elif ext.upper() in ["BZ2"]: with subprocess.Popen(["bunzip2", dest]) as p: p.communicate() if subdir == "Osmium": subdir = "Os" dest = os.path.join(basedir, f"POTCAR.{subdir}") shutil.move(os.path.join(basedir, "POTCAR"), dest) with subprocess.Popen(["gzip", "-f", dest]) as p: p.communicate() except Exception as ex: print(f"An error has occurred. Message is {str(ex)}. Trying to continue... ") print("") print( "PSP resources directory generated. It is recommended that you " "run 'pmg config --add PMG_VASP_PSP_DIR %s'" % os.path.abspath(targetdir) ) print("Start a new terminal to ensure that your environment variables are properly set.") def build_enum(fortran_command="gfortran"): """ Build enum. :param fortran_command: """ currdir = os.getcwd() state = True try: subprocess.call(["git", "clone", "--recursive", "https://github.com/msg-byu/enumlib.git"]) os.chdir(os.path.join(currdir, "enumlib", "symlib", "src")) os.environ["F90"] = fortran_command subprocess.call(["make"]) enumpath = os.path.join(currdir, "enumlib", "src") os.chdir(enumpath) subprocess.call(["make"]) for f in ["enum.x", "makestr.x"]: subprocess.call(["make", f]) shutil.copy(f, os.path.join("..", "..")) except Exception as ex: print(str(ex)) state = False finally: os.chdir(currdir) shutil.rmtree("enumlib") return state def build_bader(fortran_command="gfortran"): """ Build bader package. :param fortran_command: """ bader_url = "http://theory.cm.utexas.edu/henkelman/code/bader/download/bader.tar.gz" currdir = os.getcwd() state = True try: urlretrieve(bader_url, "bader.tar.gz") subprocess.call(["tar", "-zxf", "bader.tar.gz"]) os.chdir("bader") subprocess.call(["cp", "makefile.osx_" + fortran_command, "makefile"]) subprocess.call(["make"]) shutil.copy("bader", os.path.join("..", "bader_exe")) os.chdir("..") shutil.rmtree("bader") os.remove("bader.tar.gz") shutil.move("bader_exe", "bader") except Exception as ex: print(str(ex)) state = False finally: os.chdir(currdir) return state def install_software(args): """ Install all optional external software. :param args: """ try: subprocess.call(["ifort", "--version"]) print("Found ifort") fortran_command = "ifort" except Exception: try: subprocess.call(["gfortran", "--version"]) print("Found gfortran") fortran_command = "gfortran" except Exception as ex: print(str(ex)) print("No fortran compiler found.") sys.exit(-1) enum = None bader = None if args.install == "enumlib": print("Building enumlib") enum = build_enum(fortran_command) print("") elif args.install == "bader": print("Building bader") bader = build_bader(fortran_command) print("") if bader or enum: print( "Please add {} to your PATH or move the executables multinum.x, " "makestr.x and/or bader to a location in your PATH.".format(os.path.abspath(".")) ) print("") def add_config_var(args): """ Add configuration args. :param args: """ d = {} if os.path.exists(SETTINGS_FILE): shutil.copy(SETTINGS_FILE, SETTINGS_FILE + ".bak") print(f"Existing {SETTINGS_FILE} backed up to {SETTINGS_FILE + '.bak'}") d = loadfn(SETTINGS_FILE) toks = args.var_spec if len(toks) % 2 != 0: print("Bad variable specification!") sys.exit(-1) for i in range(int(len(toks) / 2)): d[toks[2 * i]] = toks[2 * i + 1] dumpfn(d, SETTINGS_FILE) print(f"New {SETTINGS_FILE} written!") def configure_pmg(args): """ Handle configure command. :param args: """ if args.potcar_dirs: setup_potcars(args) elif args.install: install_software(args) elif args.var_spec: add_config_var(args)
""" Driver of graph construction, optimization, and linking. """ import copy import copyreg import logging import os import pickle import time import warnings from itertools import chain from typing import List import numpy as np import aesara import aesara.compile.profiling from aesara.compile.compilelock import lock_ctx from aesara.compile.io import In, SymbolicInput, SymbolicOutput from aesara.compile.ops import deep_copy_op, view_op from aesara.configdefaults import config from aesara.graph.basic import ( Constant, Variable, ancestors, clone_get_equiv, graph_inputs, vars_between, ) from aesara.graph.destroyhandler import DestroyHandler from aesara.graph.features import PreserveVariableAttributes from aesara.graph.fg import FunctionGraph, InconsistencyError from aesara.graph.op import HasInnerGraph from aesara.graph.opt_utils import is_same_graph from aesara.graph.utils import get_variable_trace_string from aesara.link.basic import Container from aesara.link.utils import raise_with_op _logger = logging.getLogger("aesara.compile.function.types") __docformat__ = "restructuredtext en" class UnusedInputError(Exception): """ A symbolic input passed to function is not needed. """ def alias_root(v): """ Return the variable to which v is aliased by view_maps and destroy_maps. """ if v.owner is None: return v vmap = v.owner.op.view_map dmap = v.owner.op.destroy_map outpos = v.owner.outputs.index(v) v_views = vmap.get(outpos, []) + dmap.get(outpos, []) if len(v_views) > 1: raise NotImplementedError( f"{v} is a view/destroyed version of more then one inputs. " "Currently, we only support the case where an output is a view or " "a destroyed version of one input." ) elif v_views: return alias_root(v.owner.inputs[v_views[0]]) else: return v def view_tree_set(fgraph, v, treeset): """ Add to `treeset` all variables that are views of v, given that v is not a view. """ treeset.add(v) for cl, v_input_pos_to_cl in fgraph.clients[v]: if cl == "output": continue vmap = cl.op.view_map dmap = cl.op.destroy_map for opos, iposlist in chain(vmap.items(), dmap.items()): if v_input_pos_to_cl in iposlist: if cl.outputs[opos] not in treeset: view_tree_set(fgraph, cl.outputs[opos], treeset) def infer_reuse_pattern(fgraph, outputs_to_disown): """ Given an fgraph and a list of variables, returns the list or set of all variables which may share the same underlying data storage as any of the specified variables. Used internally by function, FunctionMaker. This list (or set) is also referred to as no_recycling sometimes, especially by linker code. """ rval = set() for o in outputs_to_disown: view_tree_set(fgraph, alias_root(o), rval) # remove from rval all of the inputs, constants, values. rval = {r for r in rval if r.owner is not None} return rval def fgraph_updated_vars(fgraph, expanded_inputs): """ Reconstruct the full "updates" dictionary, mapping from FunctionGraph input variables to the fgraph outputs that will replace their values. Returns ------- dict variable -> variable """ updated_vars = {} potential_values = list(fgraph.outputs) # copy the list if len(expanded_inputs) != len(fgraph.inputs): raise ValueError("expanded_inputs must match len(fgraph.inputs)") for e_input, ivar in reversed(list(zip(expanded_inputs, fgraph.inputs))): if e_input.update is not None: updated_vars[ivar] = potential_values.pop() return updated_vars class Supervisor: """ Listener for FunctionGraph events which makes sure that no operation overwrites the contents of protected Variables. The outputs of the FunctionGraph are protected by default. """ def __init__(self, protected): self.protected = list(protected) def validate(self, fgraph): if config.cycle_detection == "fast" and hasattr(fgraph, "has_destroyers"): if fgraph.has_destroyers(self.protected): raise InconsistencyError("Trying to destroy protected variables.") return True if not hasattr(fgraph, "destroyers"): return True for r in self.protected + list(fgraph.outputs): if fgraph.destroyers(r): raise InconsistencyError(f"Trying to destroy a protected variable: {r}") def std_fgraph(input_specs, output_specs, accept_inplace=False): """ Makes an FunctionGraph corresponding to the input specs and the output specs. Any SymbolicInput in the input_specs, if its update field is not None, will add an output to the FunctionGraph corresponding to that update. The return value is the FunctionGraph as well as a list of SymbolicOutput instances corresponding to the updates. If accept_inplace is False, the graph will be checked for inplace operations and an exception will be raised if it has any. If accept_inplace is True, a DestroyHandler will be added to the FunctionGraph if there are any inplace operations. The returned FunctionGraph is a clone of the graph between the provided inputs and outputs. """ orig_inputs = [spec.variable for spec in input_specs] # Extract the updates and the mapping between update outputs and # the updated inputs. updates = [] update_mapping = {} out_idx = len(output_specs) for inp_idx in range(len(input_specs)): if input_specs[inp_idx].update: updates.append(input_specs[inp_idx].update) update_mapping[out_idx] = inp_idx out_idx += 1 orig_outputs = [spec.variable for spec in output_specs] + updates fgraph = FunctionGraph(orig_inputs, orig_outputs, update_mapping=update_mapping) for node in fgraph.apply_nodes: if node.op.destroy_map: if not accept_inplace: raise TypeError(f"Graph must not contain inplace operations: {node}") else: fgraph.attach_feature(DestroyHandler()) break # We need to protect all immutable inputs from inplace operations. fgraph.attach_feature( Supervisor( input for spec, input in zip(input_specs, fgraph.inputs) if not ( spec.mutable or (hasattr(fgraph, "destroyers") and fgraph.has_destroyers([input])) ) ) ) # If named nodes are replaced, keep the name for feature in std_fgraph.features: fgraph.attach_feature(feature()) return fgraph, list(map(SymbolicOutput, updates)) std_fgraph.features = [PreserveVariableAttributes] class AliasedMemoryError(Exception): """ Memory is aliased that should not be. """ ### # Function ### # unique id object used as a placeholder for duplicate entries DUPLICATE = ["DUPLICATE"] class Function: """ Type of the functions returned by aesara.function or aesara.FunctionMaker.create. `Function` is the callable object that does computation. It has the storage of inputs and outputs, performs the packing and unpacking of inputs and return values. It implements the square-bracket indexing so that you can look up the value of a symbolic node. Functions are copyable via {{{fn.copy()}}} and {{{copy.copy(fn)}}}. When a function is copied, this instance is duplicated. Contrast with self.maker (instance of `FunctionMaker`) that is shared between copies. The meaning of copying a function is that the containers and their current values will all be duplicated. This requires that mutable inputs be copied, whereas immutable inputs may be shared between copies. A Function instance is hashable, on the basis of its memory address (its id). A Function instance is only equal to itself. A Function instance may be serialized using the `pickle` or `cPickle` modules. This will save all default inputs, the graph, and WRITEME to the pickle file. A Function instance have a ``trust_input`` field that default to False. When True, we don't do extra check of the input to give better error message. In some case, python code will still return the good results if you pass a python or numpy scalar instead of a numpy tensor. C code should raise an error if you pass an object of the wrong type. Attributes ---------- finder inv_finder """ pickle_aliased_memory_strategy = "warn" """ How to deal with pickling finding aliased storage. Meaningful settings are: 'ignore', 'warn', 'raise'. If the value is 'warn', then a message will be printed to stderr if aliased storage is detected during pickle.dump. If the value is 'raise', then an AliasedMemoryError will be raised if aliased storage is detected during pickle.dump. """ input_storage = None """ List of Container instances. """ output_storage = None """ List of Container instances. """ indices = None """ List of (SymbolicInput, indices, [SymbolicInput,...]), one tuple for each input. The first tuple element is the SymbolicInput object for the corresponding function input. The second and third tuple elements are used only by Kits, which are deprecated. """ defaults = None """ List of 3-tuples, one 3-tuple for each input. Tuple element 0: Bool: Is this input required at each function call? Tuple element 1: Bool: Should this inputs value be reverted after each call? Tuple element 2: Any: The value associated with this input. """ unpack_single = None """ Bool: for outputs lists of length 1, should the 0'th element be returned directly? """ return_none = None """ Bool: whether the function should return None or not. """ maker = None """ FunctionMaker instance. """ fn = None """ A function that evaluates the graph. Typically a linker's make_thunk method created this function. """ finder = None """ Dictionary mapping several kinds of things to containers. We set an entry in finder for: - the index of the input - the variable instance the input is based on - the name of the input All entries map to the container or to DUPLICATE if an ambiguity is detected. """ inv_finder = None """ Dict. Reverse lookup of `finder`. It maps container -> SymbolicInput """ def __init__( self, fn, input_storage, output_storage, indices, outputs, defaults, unpack_single, return_none, output_keys, maker, name=None, ): self.fn = fn self.input_storage = input_storage self.output_storage = output_storage self.indices = indices self.outputs = outputs self.defaults = defaults self.unpack_single = unpack_single self.return_none = return_none self.maker = maker self.profile = None # reassigned in FunctionMaker.create self.trust_input = False # If True, we don't check the input parameter self.name = name self.nodes_with_inner_function = [] self.output_keys = output_keys # See if we have any mutable / borrow inputs # TODO: this only need to be set if there is more then 1 input self._check_for_aliased_inputs = False for i in maker.inputs: # If the input is a shared variable, the memory region is # under Aesara control and so we don't need to check if it # is aliased as we never do that. if ( isinstance(i, In) and not i.shared and (getattr(i, "borrow", False) or getattr(i, "mutable", False)) ): self._check_for_aliased_inputs = True break # We will be popping stuff off this `containers` object. It is a copy. containers = list(self.input_storage) finder = {} inv_finder = {} def distribute(indices, cs, value): input.distribute(value, indices, cs) for c in cs: c.provided += 1 # Store the list of names of named inputs. named_inputs = [] # Count the number of un-named inputs. n_unnamed_inputs = 0 # Initialize the storage # this loop works by modifying the elements (as variable c) of # self.input_storage inplace. for i, ((input, indices, sinputs), (required, refeed, value)) in enumerate( zip(self.indices, defaults) ): if indices is None: # containers is being used as a stack. Here we pop off # the next one. c = containers[0] c.strict = getattr(input, "strict", False) c.allow_downcast = getattr(input, "allow_downcast", None) if value is not None: # Always initialize the storage. if isinstance(value, Container): # There is no point in obtaining the current value # stored in the container, since the container is # shared. # For safety, we make sure 'refeed' is False, since # there is no need to refeed the default value. assert not refeed else: c.value = value c.required = required c.implicit = input.implicit # this is a count of how many times the input has been # provided (reinitialized to 0 on __call__) c.provided = 0 finder[i] = c finder[input.variable] = c if input.name not in finder: finder[input.name] = c else: finder[input.name] = DUPLICATE if input.name is None: n_unnamed_inputs += 1 else: named_inputs.append(input.name) inv_finder[c] = input containers[:1] = [] self.finder = finder self.inv_finder = inv_finder # this class is important in overriding the square-bracket notation: # fn.value[x] # self reference is available via the closure on the class class ValueAttribute: def __getitem__(self, item): try: s = finder[item] except KeyError: raise TypeError(f"Unknown input or state: {item}") if s is DUPLICATE: raise TypeError( f"Ambiguous name: {item} - please check the " "names of the inputs of your function " "for duplicates." ) if isinstance(s, Container): return s.value else: raise NotImplementedError def __setitem__(self, item, value): try: s = finder[item] except KeyError: # Print informative error message. msg = get_info_on_inputs(named_inputs, n_unnamed_inputs) raise TypeError(f"Unknown input or state: {item}. {msg}") if s is DUPLICATE: raise TypeError( f"Ambiguous name: {item} - please check the " "names of the inputs of your function " "for duplicates." ) if isinstance(s, Container): s.value = value s.provided += 1 else: s(value) def __contains__(self, item): return finder.__contains__(item) # this class is important in overriding the square-bracket notation: # fn.container[x] # self reference is available via the closure on the class class ContainerAttribute: def __getitem__(self, item): return finder[item] def __contains__(self, item): return finder.__contains__(item) # You cannot set the container self._value = ValueAttribute() self._container = ContainerAttribute() # Compute self.n_returned_outputs. # This is used only when fn.need_update_inputs is False # because we're using one of the VM objects and it is # putting updates back into the input containers all by itself. assert len(self.maker.expanded_inputs) == len(self.input_storage) self.n_returned_outputs = len(self.output_storage) for input in self.maker.expanded_inputs: if input.update is not None: self.n_returned_outputs -= 1 for node in self.maker.fgraph.apply_nodes: if isinstance(node.op, HasInnerGraph): self.nodes_with_inner_function.append(node.op) def __contains__(self, item): return self.value.__contains__(item) def __getitem__(self, item): return self.value[item] def __setitem__(self, item, value): self.value[item] = value def __copy__(self): """ Copy a function. Copied function have separate intermediate storages and output storages with original function """ return self.copy() def copy( self, share_memory=False, swap=None, delete_updates=False, name=None, profile=None, ): """ Copy this function. Copied function will have separated maker and fgraph with original function. User can choose whether to separate storage by changing the share_memory arguments. Parameters ---------- share_memory : boolean When True, two function share intermediate storages(storages except input and output storages). Otherwise two functions will only share partial storages and same maker. If two functions share memory and allow_gc=False, this will increase executing speed and save memory. swap : dict Dictionary that map old SharedVariables to new SharedVariables. Default is None. NOTE: The shared variable swap in only done in the new returned function, not in the user graph. delete_updates : boolean If True, Copied function will not have updates. name : string If provided, will be the name of the new Function. Otherwise, it will be old + " copy" profile : as aesara.function profile parameter Returns ------- aesara.Function Copied aesara.Function """ # helper function def checkSV(sv_ori, sv_rpl): """ Assert two SharedVariable follow some restirctions: 1. same type 2. same shape or dim? """ SharedVariable = aesara.tensor.sharedvar.SharedVariable assert isinstance(sv_ori, SharedVariable), ( "Key of swap should be SharedVariable, given:", sv_ori, " type", type(sv_ori), ) assert isinstance(sv_rpl, SharedVariable), ( "Value of swap should be SharedVariable, given:", sv_rpl, "type", type(sv_ori), ) assert sv_ori.type == sv_rpl.type, ( "Type of given SharedVariable conflicts with original one", "Type of given SharedVariable:", sv_rpl.type, "Type of original SharedVariable:", sv_ori.type, ) maker = self.maker # Copy Ins and their storage. # so that they have different storage as their value ins = [copy.copy(input) for input in maker.inputs] # Delete update output in fgraph and updates In instances if needed if delete_updates: # The first len(maker.outputs) variables are original variables. # The rest are the updates. out_vars = maker.fgraph.outputs[: len(maker.outputs)] else: out_vars = maker.fgraph.outputs # Init new fgraph using copied variables and get memo # memo: a dict that map old variables to new variables memo = clone_get_equiv(maker.fgraph.inputs, out_vars) fg_cpy = FunctionGraph( [memo[i] for i in maker.fgraph.inputs], [memo[o] for o in out_vars], clone=False, ) # Re initialize Outs and swap update and variable in Ins # By doing this, we can pass FunctionMaker._check_unused_inputs() outs = list(map(SymbolicOutput, fg_cpy.outputs[: len(maker.outputs)])) for out_ori, out_cpy in zip(maker.outputs, outs): out_cpy.borrow = out_ori.borrow # swap SharedVariable if swap is not None: exist_svs = [i.variable for i in maker.inputs] # Check if given ShareVariables exist for sv in swap.keys(): if sv not in exist_svs: raise ValueError(f"SharedVariable: {sv.name} not found") # Swap SharedVariable in fgraph and In instances for index, (i, in_v) in enumerate(zip(ins, fg_cpy.inputs)): # Variables in maker.inputs are defined by user, therefore we # use them to make comparison and do the mapping. # Otherwise we don't touch them. var = maker.inputs[index].variable if var in swap: swap_sv = swap[var] checkSV(i.variable, swap_sv) # swap variable and value of In instances i.variable = swap_sv i.value = swap_sv.container # In the fgraph we use the cloned SharedVariable swap_sv = swap_sv.clone() # Swap SharedVariable in fgraph # if inputs was replaced, change self.inputs fg_cpy.inputs[index] = swap_sv fg_cpy.replace(in_v, swap_sv, reason="Swap SV") # Delete update if needed update_i = len(outs) for i, in_var in zip(ins, fg_cpy.inputs): i.variable = in_var if not delete_updates and i.update is not None: i.update = fg_cpy.outputs[update_i] update_i += 1 else: i.update = None # Construct new storage_map that map new variable to old storage, # so that the ensuing function shares storage with the original one storage_map = self.fn.storage_map new_storage_map = {} # TODO: We could share the output storage, but we must make sure # 2 different function call won't override each other values. This # is already done elsewhere, so to reuse it the user would need to # use Out(var, borrow=True) and maybe the mutable=True flag too. # But to be safe for now as it isn't documented and we aren't sure # it is well tested, we don't share the part of the storage_map. if share_memory: i_o_vars = maker.fgraph.inputs + maker.fgraph.outputs for key in storage_map.keys(): if key not in i_o_vars: new_storage_map[memo[key]] = storage_map[key] if not name and self.name: name = self.name + " copy" input_storage = [i.value for i in ins] # reinitialize new maker and create new function if profile is None: profile = config.profile or config.print_global_stats # profile -> True or False if profile is True: if name: message = name else: message = str(profile.message) + " copy" profile = aesara.compile.profiling.ProfileStats(message=message) # profile -> object elif type(profile) == str: profile = aesara.compile.profiling.ProfileStats(message=profile) f_cpy = maker.__class__( inputs=ins, outputs=outs, fgraph=fg_cpy, mode=maker.mode, profile=profile, # When removing updates containing variables # not used in the output function, copy # generates an unused implicit input. # We ignore the resulting errors, # but could change it to 'warn' if this might # cause problems. on_unused_input="ignore", function_builder=maker.function_builder, # As this is an optimized graph, it # can contain inplace. DebugMode check # that. accept_inplace=True, ).create(input_storage, storage_map=new_storage_map) for in_ori, in_cpy, ori, cpy in zip( maker.inputs, f_cpy.maker.inputs, self.input_storage, f_cpy.input_storage ): # Share immutable ShareVariable and constant input's storage swapped = swap is not None and in_ori.variable in swap # Using the original storage if SharedVariable will not be updated # and is not swapped if not in_ori.mutable and not swapped: cpy.data = ori.data in_cpy.value = in_ori.value # Reconstruct Function.finder which map Variable defined by user # to container, to make Function.value and Function.data work well. # Replace variable in new maker.inputs by the original ones. # So that user can swap SharedVariable in a swapped function container = f_cpy.finder.pop(in_cpy.variable) if not swapped: f_cpy.finder[in_ori.variable] = container in_cpy.variable = in_ori.variable else: f_cpy.finder[swap[in_ori.variable]] = container in_cpy.variable = swap[in_ori.variable] f_cpy.name = name f_cpy.maker.fgraph.name = name return f_cpy def __call__(self, *args, **kwargs): """ Evaluates value of a function on given arguments. Parameters ---------- args : list List of inputs to the function. All inputs are required, even when some of them are not necessary to calculate requested subset of outputs. kwargs : dict The function inputs can be passed as keyword argument. For this, use the name of the input or the input instance as the key. Keyword argument ``output_subset`` is a list of either indices of the function's outputs or the keys belonging to the `output_keys` dict and represent outputs that are requested to be calculated. Regardless of the presence of ``output_subset``, the updates are always calculated and processed. To disable the updates, you should use the ``copy`` method with ``delete_updates=True``. Returns ------- list List of outputs on indices/keys from ``output_subset`` or all of them, if ``output_subset`` is not passed. """ def restore_defaults(): for i, (required, refeed, value) in enumerate(self.defaults): if refeed: if isinstance(value, Container): value = value.storage[0] self[i] = value profile = self.profile t0 = time.time() output_subset = kwargs.pop("output_subset", None) if output_subset is not None and self.output_keys is not None: output_subset = [self.output_keys.index(key) for key in output_subset] # Reinitialize each container's 'provided' counter if self.trust_input: i = 0 for arg in args: s = self.input_storage[i] s.storage[0] = arg i += 1 else: for c in self.input_storage: c.provided = 0 if len(args) + len(kwargs) > len(self.input_storage): raise TypeError("Too many parameter passed to aesara function") # Set positional arguments i = 0 for arg in args: # TODO: provide a Param option for skipping the filter if we # really want speed. s = self.input_storage[i] # see this emails for a discuation about None as input # https://groups.google.com/group/theano-dev/browse_thread/thread/920a5e904e8a8525/4f1b311a28fc27e5 if arg is None: s.storage[0] = arg else: try: s.storage[0] = s.type.filter( arg, strict=s.strict, allow_downcast=s.allow_downcast ) except Exception as e: function_name = "aesara function" argument_name = "argument" if self.name: function_name += ' with name "' + self.name + '"' if hasattr(arg, "name") and arg.name: argument_name += ' with name "' + arg.name + '"' where = get_variable_trace_string(self.maker.inputs[i].variable) if len(e.args) == 1: e.args = ( "Bad input " + argument_name + " to " + function_name + f" at index {int(i)} (0-based). {where}" + e.args[0], ) else: e.args = ( "Bad input " + argument_name + " to " + function_name + f" at index {int(i)} (0-based). {where}" ) + e.args restore_defaults() raise s.provided += 1 i += 1 # Set keyword arguments if kwargs: # for speed, skip the items for empty kwargs for k, arg in kwargs.items(): self[k] = arg if ( not self.trust_input and # The getattr is only needed for old pickle getattr(self, "_check_for_aliased_inputs", True) ): # Collect aliased inputs among the storage space args_share_memory = [] for i in range(len(self.input_storage)): i_var = self.maker.inputs[i].variable i_val = self.input_storage[i].storage[0] if hasattr(i_var.type, "may_share_memory"): is_aliased = False for j in range(len(args_share_memory)): group_j = zip( [ self.maker.inputs[k].variable for k in args_share_memory[j] ], [ self.input_storage[k].storage[0] for k in args_share_memory[j] ], ) if any( [ ( var.type is i_var.type and var.type.may_share_memory(val, i_val) ) for (var, val) in group_j ] ): is_aliased = True args_share_memory[j].append(i) break if not is_aliased: args_share_memory.append([i]) # Check for groups of more than one argument that share memory for group in args_share_memory: if len(group) > 1: # copy all but the first for j in group[1:]: self.input_storage[j].storage[0] = copy.copy( self.input_storage[j].storage[0] ) # Check if inputs are missing, or if inputs were set more than once, or # if we tried to provide inputs that are supposed to be implicit. if not self.trust_input: for c in self.input_storage: if c.required and not c.provided: restore_defaults() raise TypeError( f"Missing required input: {getattr(self.inv_finder[c], "variable", self.inv_finder[c])}" ) if c.provided > 1: restore_defaults() raise TypeError( f"Multiple values for input: {getattr(self.inv_finder[c], "variable", self.inv_finder[c])}" ) if c.implicit and c.provided > 0: restore_defaults() raise TypeError( f"Tried to provide value for implicit input: {getattr(self.inv_finder[c], "variable", self.inv_finder[c])}" ) # Do the actual work t0_fn = time.time() try: outputs = ( self.fn() if output_subset is None else self.fn(output_subset=output_subset) ) except Exception: restore_defaults() if hasattr(self.fn, "position_of_error"): # this is a new vm-provided function or c linker # they need this because the exception manipulation # done by raise_with_op is not implemented in C. thunk = None if hasattr(self.fn, "thunks"): thunk = self.fn.thunks[self.fn.position_of_error] raise_with_op( self.maker.fgraph, node=self.fn.nodes[self.fn.position_of_error], thunk=thunk, storage_map=getattr(self.fn, "storage_map", None), ) else: # old-style linkers raise their own exceptions raise dt_fn = time.time() - t0_fn self.maker.mode.fn_time += dt_fn if profile: profile.vm_call_time += dt_fn # Retrieve the values that were computed if outputs is None: outputs = [x.data for x in self.output_storage] assert len(outputs) == len(self.output_storage) # Remove internal references to required inputs. # These cannot be re-used anyway. for c in self.input_storage: if c.required: c.storage[0] = None # if we are allowing garbage collection, remove the # output reference from the internal storage cells if getattr(self.fn, "allow_gc", False): assert len(self.output_storage) == len(self.maker.fgraph.outputs) for o_container, o_variable in zip( self.output_storage, self.maker.fgraph.outputs ): if o_variable.owner is not None: # this node is the variable of computation # WARNING: This circumvents the 'readonly' attribute in x o_container.storage[0] = None if getattr(self.fn, "need_update_inputs", True): # Update the inputs that have an update function for input, storage in reversed( list(zip(self.maker.expanded_inputs, self.input_storage)) ): if input.update is not None: storage.data = outputs.pop() else: outputs = outputs[: self.n_returned_outputs] # Put default values back in the storage restore_defaults() # # NOTE: This logic needs to be replicated in # scan. # grep for 'PROFILE_CODE' # dt_call = time.time() - t0 aesara.compile.profiling.total_fct_exec_time += dt_call self.maker.mode.call_time += dt_call if profile: profile.fct_callcount += 1 profile.fct_call_time += dt_call if hasattr(self.fn, "update_profile"): self.fn.update_profile(profile) if profile.ignore_first_call: profile.reset() profile.ignore_first_call = False if self.return_none: return None elif self.unpack_single and len(outputs) == 1 and output_subset is None: return outputs[0] else: if self.output_keys is not None: assert len(self.output_keys) == len(outputs) if output_subset is None: return dict(zip(self.output_keys, outputs)) else: return { self.output_keys[index]: outputs[index] for index in output_subset } if output_subset is None: return outputs else: return [outputs[i] for i in output_subset] value = property( lambda self: self._value, None, # this property itself is not settable doc="dictionary-like access to the values associated with Variables", ) container = property( lambda self: self._container, None, # this property itself is not settable doc=("dictionary-like access to the containers associated with " "Variables"), ) def free(self): """ When allow_gc = False, clear the Variables in storage_map """ # 1.no allow_gc return False # 2.has allow_gc, if allow_gc is False, return True if not getattr(self.fn, "allow_gc", True): for key in self.fn.storage_map: if not isinstance(key, Constant): self.fn.storage_map[key][0] = None for node in self.nodes_with_inner_function: if hasattr(node.fn, "free"): node.fn.free() def get_shared(self): """ Return the shared variable read or updated by by this function. """ return [i.variable for i in self.maker.inputs if i.implicit] def sync_shared(self): if hasattr(aesara, "gpuarray") and aesara.gpuarray.pygpu_activated: import pygpu for i in self.maker.fgraph.update_mapping.values(): inp = self.input_storage[i] if isinstance(inp.data, pygpu.gpuarray.GpuArray): inp.data.sync() # pickling/deepcopy support for Function def _pickle_Function(f): # copy of the input storage list ins = list(f.input_storage) input_storage = [] for (input, indices, inputs), (required, refeed, default) in zip( f.indices, f.defaults ): input_storage.append(ins[0]) del ins[0] inputs_data = [x.data for x in f.input_storage] # HACK to detect aliased storage. # This is here because aliased relationships are not [currently] # preserved across the pickle operation if not (f.pickle_aliased_memory_strategy == "ignore"): all_data = input_storage + inputs_data for i, d_i in enumerate(all_data): for j, d_j in enumerate(all_data): if ( (i < j) and isinstance(d_i, np.ndarray) and isinstance(d_j, np.ndarray) ): if np.may_share_memory(d_i, d_j): if f.pickle_aliased_memory_strategy == "warn": _logger.warning( "aliased relationship between " f"Function arguments {d_i}, {d_j} " "will not be preserved by " "un-pickling operation" ) else: raise AliasedMemoryError(d_i, d_j) # The user can override trust_input. Our doc tell that. We should # not do that anymore and make sure the Maker have all the # information needed. rval = (_constructor_Function, (f.maker, input_storage, inputs_data, f.trust_input)) return rval def _constructor_Function(maker, input_storage, inputs_data, trust_input=False): if not config.unpickle_function: return None f = maker.create(input_storage, trustme=True) assert len(f.input_storage) == len(inputs_data) for container, x in zip(f.input_storage, inputs_data): assert ( (container.data is x) or (isinstance(x, np.ndarray) and (container.data == x).all()) or (container.data == x) ) f.trust_input = trust_input return f copyreg.pickle(Function, _pickle_Function) ### # FunctionMaker ### def insert_deepcopy(fgraph, wrapped_inputs, wrapped_outputs): """ Insert deepcopy in the fgraph to break aliasing of outputs """ # This loop was inserted to remove aliasing between outputs when # they all evaluate to the same value. Originally it was OK for # outputs to be aliased, but some of the outputs can be shared # variables, and is not good for shared variables to be # aliased. It might be possible to optimize this by making sure # there is no aliasing only between shared variables. # If some outputs are constant, we add deep copy to respect the # memory contract # We don't insert deep copy when the output.borrow is True for all # concerned outputs. assert len(wrapped_inputs) == len(fgraph.inputs) assert len(wrapped_outputs) == len(fgraph.outputs) reason = "insert_deepcopy" updated_fgraph_inputs = { fgraph_i for i, fgraph_i in zip(wrapped_inputs, fgraph.inputs) if getattr(i, "update", False) } # We can't use fgraph.inputs as this don't include Constant Value. all_graph_inputs = list(graph_inputs(fgraph.outputs)) has_destroyers_attr = hasattr(fgraph, "has_destroyers") for i in range(len(fgraph.outputs)): views_of_output_i = set() view_tree_set(fgraph, alias_root(fgraph.outputs[i]), views_of_output_i) copied = False # do not allow outputs to be aliased for j in range(i + 1, len(fgraph.outputs)): # We could don't put deep copy if both outputs have borrow==True # and not(wrapped_outputs[i].borrow and wrapped_outputs[j].borrow): if fgraph.outputs[j] in views_of_output_i: if wrapped_outputs[i].borrow and wrapped_outputs[j].borrow: fgraph.change_input( "output", i, view_op(fgraph.outputs[i]), reason=reason ) else: fgraph.change_input( "output", i, deep_copy_op(fgraph.outputs[i]), reason=reason ) copied = True break if not copied: for input_j in all_graph_inputs: # do not allow outputs to be aliased to an inputs (j), unless # a) that j'th input has been 'destroyed' by # e.g. in-place computations # b) that j'th input is a shared variable that is also # being updated if input_j in updated_fgraph_inputs: continue if input_j in views_of_output_i and not ( has_destroyers_attr and fgraph.has_destroyers([input_j]) ): # We don't put deep_copy_op if the input and the # output have borrow==True if input_j in fgraph.inputs: j = fgraph.inputs.index(input_j) if wrapped_outputs[i].borrow and wrapped_inputs[j].borrow: fgraph.change_input( "output", i, view_op(fgraph.outputs[i]), reason="insert_deepcopy", ) break else: fgraph.change_input( "output", i, deep_copy_op(fgraph.outputs[i]), reason="insert_deepcopy", ) break elif wrapped_outputs[i].borrow: fgraph.change_input( "output", i, view_op(fgraph.outputs[i]), reason="insert_deepcopy", ) break else: fgraph.change_input( "output", i, deep_copy_op(fgraph.outputs[i]), reason="insert_deepcopy", ) break NODEFAULT = ["NODEFAULT"] class FunctionMaker: """ `FunctionMaker` is the class to `create` `Function` instances. This class has the fgraph, the optimizer, and the linker. When copying a `Function`, there is no need to duplicate the `FunctionMaker` instance. Deepcopy still copies both, which can variable in re-compilation. Parameters ---------- inputs : list of SymbolicInput instances outputs : list of SymbolicOutput instances Outputs may also be a single Variable (not a list), in which case the functions produced by FunctionMaker will return their output value directly. mode : Mode instance Telling FunctionMaker how to optimize and link. None means to use the `config.mode`. accept_inplace : bool True iff it is acceptable to have inplace operations in the graph from the inputs to the outputs. on_unused_input : {'raise', 'warn', 'ignore', None} What to do if a variable in the 'inputs' list is not used in the graph. Possible values are: - 'raise': raise an error - 'warn': log a warning - 'ignore': do not do anything - None: Use the value in the Aesara flags on_unused_input. name : str An optional name for this function. If used, the profile mode will print the time spent in this function. """ @staticmethod def wrap_in(input): if isinstance(input, (SymbolicInput)): return input elif isinstance(input, Variable): # r -> SymbolicInput(variable=r) return SymbolicInput(input) elif isinstance(input, (list, tuple)): # (r, u) -> SymbolicInput(variable=r, update=u) if len(input) == 2: return SymbolicInput(input[0], update=input[1]) else: raise TypeError( f"Expected two elements in the list or tuple; got {input}" ) else: raise TypeError( f"Unknown input type: {type(input)} ({input}), expected Variable " "instance" ) @staticmethod def expand_in(sinput, rinputs): # For SymbolicInputKits, this extracts a list of SymbolicInput # instances and corresponding indices such that these # SymbolicInputs are representative of some of the Variable # instances in inputs. For SymbolicInput, this returns None # as the list of indices and a list with just the # SymbolicInput. # if isinstance(sinput, SymbolicInputKit): # return sinput.complete(rinputs) # elif isinstance(sinput, SymbolicInput): if isinstance(sinput, SymbolicInput): return [None, [sinput]] @staticmethod def wrap_out(output): if isinstance(output, SymbolicOutput): return output elif isinstance(output, Variable): return SymbolicOutput(output) else: raise TypeError(f"Unknown output type: {type(output)} ({output})") def optimize_graph_with_cache(self, optimizer, inputs, outputs): # This function is not finished graph_db_file = os.path.join(config.compiledir, "optimized_graphs.pkl") # the inputs, outputs, and size of the graph to be optimized inputs_new = [inp.variable for inp in inputs] outputs_new = [out.variable for out in outputs] size_new = len(self.fgraph.apply_nodes) # Beginning of cache optimizations. # Could be refactored in different functions. def load_graph_db(): if os.path.isfile(graph_db_file): print("graph_db already exists") else: # create graph_db with open(graph_db_file, "wb") as f: print(f"create new graph_db in {graph_db_file}") # load the graph_db dictionary try: with open(graph_db_file, "rb") as f, config.change_flags( unpickle_function=False ): # Temporary hack to allow # tests.scan.test_scan.T_Scan to # finish. Should be changed in definitive version. graph_db = pickle.load(f) print("graph_db loaded and it is not empty") except EOFError as e: # the file has nothing in it print(e) print("graph_db loaded and it is empty") graph_db = {} return graph_db def find_same_graph_in_db(graph_db): # If found_graph_in_db is None, then need to optimize. # Otherwise, return the graph found. found_graph_in_db = None # The sole purpose of this loop is to set 'need_optimize' by # going through graph_db, looking for graph that has the same # computation performed. for graph_old, graph_optimized in graph_db.items(): inputs_old = graph_old.inputs outputs_old = graph_old.outputs size_old = len(graph_old.apply_nodes) # Some heuristics to check is the same graphs have # already been optimized before. if len(inputs_new) != len(inputs_old): # If the inputs are of different size, # two graphs are for sure different print("need to optimize, because input size is different") continue elif len(outputs_new) != len(outputs_old): # If the inputs are of different size, # two graphs are for sure different print("need to optimize, because output size is different") continue elif not all( input_new.type == input_old.type for input_new, input_old in zip(inputs_new, inputs_old) ): print("need to optimize, because inputs are of different " "types") continue elif not all( output_new.type == output_old.type for output_new, output_old in zip(outputs_new, outputs_old) ): print("need to optimize, because outputs are of different " "types") continue elif not size_old == size_new: print( "need to optimize, because numbers of nodes in graph" " are different" ) continue else: flags = [] for i, (output_new, output_old) in enumerate( zip(outputs_new, outputs_old) ): print("loop through outputs node for both graphs") graph_old.variables = set( vars_between(graph_old.inputs, graph_old.outputs) ) # using clone allowed to avoid a lot of errors # deep copy seemed to had. f2 = graph_old.clone(check_integrity=False) t1 = output_new t2 = f2.outputs[i] givens = dict( zip( graph_inputs([t1]), graph_inputs([t2]), ) ) temp = dict( zip( graph_inputs([t1]), graph_inputs([t2]), ) ) # hack to remove inconsistent entry in givens # seems to work that but source of inconsistency # could be worth investigating. for key, value in temp.items(): if key.type != value.type: del givens[key] flag = is_same_graph(t1, t2, givens=givens) flags.append(flag) is_same = all(flags) if is_same: # found the match print("found a match, no need to optimize") found_graph_in_db = graph_optimized break return found_graph_in_db with lock_ctx(): graph_db = load_graph_db() print(f"loaded graph_db from {graph_db_file}, size={len(graph_db)}") found_graph = find_same_graph_in_db(graph_db) if found_graph: self.fgraph = found_graph optimizer_profile = None else: # this is a brand new graph, optimize it, save it to graph_db print("graph not found in graph_db, optimizing the graph") self.fgraph.variables = set( vars_between(self.fgraph.inputs, self.fgraph.outputs) ) # check_integrity parameters was added to ignore # "excess cached variables" errors. Works that way # but once again the error couldbe worth # investigating. before_opt = self.fgraph.clone(check_integrity=False) optimizer_profile = optimizer(self.fgraph) graph_db.update({before_opt: self.fgraph}) with open(graph_db_file, "wb") as f: pickle.dump(graph_db, f, -1) print("new graph saved into graph_db") return optimizer_profile def __init__( self, inputs, outputs, mode=None, accept_inplace=False, function_builder=Function, profile=None, on_unused_input=None, fgraph=None, output_keys=None, name=None, ): # Save the provided mode, not the instantiated mode. # The instantiated mode don't pickle and if we unpickle an Aesara # function and it get re-compiled, we want the current optimizer to be # used, not the optimizer when it was saved. self.mode = mode mode = aesara.compile.mode.get_mode(mode) # Assert old way of working isn't used if getattr(mode, "profile", None): raise TypeError("profile passed via 'mode'. This isn't supported anymore") self.profile = profile if profile: # This is very important: # 1) We preload the cache here to not have its timing # included in optimization that compile function. # 2) Do not refresh the cache here by default. It cause # too much execution time during testing as we compile # much more functions then the number of compile c # module. aesara.link.c.basic.get_module_cache().refresh() # Handle the case where inputs and/or outputs is a single # Variable (not in a list) unpack_single = False return_none = False if outputs is None: return_none = True outputs = [] if not isinstance(outputs, (list, tuple)): unpack_single = True outputs = [outputs] if not isinstance(inputs, (list, tuple)): inputs = [inputs] # Wrap them in In or Out instances if needed. inputs = [self.wrap_in(i) for i in inputs] outputs = [self.wrap_out(o) for o in outputs] _inputs = list( graph_inputs( [o.variable for o in outputs] + [i.update for i in inputs if getattr(i, "update", False)] ) ) # Check if some input variables are unused self._check_unused_inputs(inputs, outputs, on_unused_input) # Make a list of (SymbolicInput|SymblicInputKits, indices, # [SymbolicInput,...]), one tuple for each input. (See # Function.indices for more details) indices = [[input] + self.expand_in(input, _inputs) for input in inputs] if fgraph is None: need_opt = True # make the fgraph (copies the graph, creates NEW INPUT AND # OUTPUT VARIABLES) fgraph, additional_outputs = std_fgraph(inputs, outputs, accept_inplace) fgraph.profile = profile else: # fgraph is already an optimized one need_opt = False updates = [spec.update for spec in inputs if spec.update] additional_outputs = list(map(SymbolicOutput, updates)) self.fgraph = fgraph # Fetch the optimizer and linker optimizer, linker = mode.optimizer, copy.copy(mode.linker) if need_opt: # Why we add stack on node when it get done in output var? try: start_optimizer = time.time() # In case there is an error during optimization. optimizer_profile = None opt_time = None with config.change_flags( compute_test_value=config.compute_test_value_opt, traceback__limit=config.traceback__compile_limit, ): # now optimize the graph if config.cache_optimizations: optimizer_profile = self.optimize_graph_with_cache( optimizer, inputs, outputs ) else: optimizer_profile = optimizer(fgraph) end_optimizer = time.time() opt_time = end_optimizer - start_optimizer _logger.debug(f"Optimizing took {opt_time:f} seconds") # Add deep copy to respect the memory interface insert_deepcopy(fgraph, inputs, outputs + additional_outputs) finally: # If the optimizer got interrupted if opt_time is None: end_optimizer = time.time() opt_time = end_optimizer - start_optimizer aesara.compile.profiling.total_graph_opt_time += opt_time if profile: if optimizer_profile is None and hasattr(optimizer, "pre_profile"): optimizer_profile = optimizer.pre_profile profile.optimizer_time += opt_time if config.profile_optimizer: profile.optimizer_profile = (optimizer, optimizer_profile) # IF False, if mean the profile for that function was # explicitly disabled elif config.profile_optimizer and profile is not False: warnings.warn( ( "config.profile_optimizer requires config.profile to " " be set to True as well" ), stacklevel=3, ) # initialize the linker if not hasattr(linker, "accept"): raise ValueError( "'linker' parameter of FunctionMaker should be " f"a Linker with an accept method or one of {list(aesara.compile.mode.predefined_linkers.keys())}" ) # the 'no_borrow' outputs are the ones for which that we can't # return the internal storage pointer. assert len(fgraph.outputs) == len(outputs + additional_outputs) no_borrow = [ output for output, spec in zip(fgraph.outputs, outputs + additional_outputs) if not spec.borrow ] if no_borrow: self.linker = linker.accept( fgraph, no_recycling=infer_reuse_pattern(fgraph, no_borrow), profile=profile, ) else: self.linker = linker.accept(fgraph, profile=profile) if hasattr(linker, "accept_var_updates"): # hacky thing so VMLinker knows about updates self.linker.accept_var_updates(fgraph_updated_vars(fgraph, inputs)) fgraph.name = name self.indices = indices self.inputs = inputs self.expanded_inputs = inputs self.outputs = outputs self.unpack_single = unpack_single self.return_none = return_none self.accept_inplace = accept_inplace self.function_builder = function_builder self.on_unused_input = on_unused_input # Used for the pickling/copy self.output_keys = output_keys self.name = name self.required = [(i.value is None) for i in self.inputs] self.refeed = [ ( i.value is not None and not isinstance(i.value, Container) and i.update is None ) for i in self.inputs ] def _check_unused_inputs(self, inputs, outputs, on_unused_input): if on_unused_input is None: on_unused_input = config.on_unused_input if on_unused_input == "ignore": return # There should be two categories of variables in inputs: # - variables that have to be provided (used_inputs) # - shared variables that will be updated used_inputs = list( ancestors( ( [o.variable for o in outputs] + [i.update for i in inputs if getattr(i, "update", False)] ), blockers=[i.variable for i in inputs], ) ) msg = ( "aesara.function was asked to create a function computing " "outputs given certain inputs, but the provided input " "variable at index %i is not part of the computational graph " "needed to compute the outputs: %s.\n%s" ) warn_msg = ( "To make this warning into an error, you can pass the " "parameter on_unused_input='raise' to aesara.function. " "To disable it completely, use on_unused_input='ignore'." ) err_msg = ( "To make this error into a warning, you can pass the " "parameter on_unused_input='warn' to aesara.function. " "To disable it completely, use on_unused_input='ignore'." ) for i in inputs: if (i.variable not in used_inputs) and (i.update is None): if on_unused_input == "warn": warnings.warn( msg % (inputs.index(i), i.variable, warn_msg), stacklevel=6 ) elif on_unused_input == "raise": raise UnusedInputError(msg % (inputs.index(i), i.variable, err_msg)) else: raise ValueError( "Invalid value for keyword on_unused_input of aesara.function: " f"'{on_unused_input}'.\n" "Valid values are 'raise', 'warn', and 'ignore'." ) def create(self, input_storage=None, trustme=False, storage_map=None): """ Create a function. Parameters ---------- input_storage A list matching the inputs list and providing default values if the default for an input is None, then that input is a required input. For an input with an update, the default acts as initialization. trustme Disables some exceptions, used internally. """ if input_storage is None: input_storage = [None] * len(self.inputs) # list of independent one-element lists, will be passed to the linker input_storage_lists = [] defaults = [] # The following loop is to fill in the input_storage_lists and # defaults lists. assert len(self.indices) == len(input_storage) for i, ((input, indices, subinputs), input_storage_i) in enumerate( zip(self.indices, input_storage) ): # Replace any default value given as a variable by its # container. Note that this makes sense only in the # context of shared variables, but for now we avoid # dealing directly with them to avoid dependency on the # shared variables work-in-progress repository. if isinstance(input_storage_i, Variable): input_storage_i = input_storage_i.container if isinstance(input_storage_i, Container): # If the default is a Container, this means we want to # share the same storage. This is done by appending # input_storage_i.storage to input_storage_lists. if indices is not None: raise TypeError( "Cannot take a Container instance as " "default for a SymbolicInputKit." ) input_storage_lists.append(input_storage_i.storage) storage = input_storage[i].storage[0] else: # Normal case: one new, independent storage unit input_storage_lists.append([input_storage_i]) storage = input_storage_i required = self.required[i] refeed = self.refeed[i] # sanity check-- if an input is required it should not # need to be refed assert not (required and refeed) # shared variables need neither be input by the user nor refed if input.shared: assert not required assert not refeed storage = None # if an input is required, it never need be refed if required: storage = None # make sure that we only store a value if we actually need it if storage is not None: assert refeed or not required defaults.append((required, refeed, storage)) # Get a function instance start_linker = time.time() start_import_time = aesara.link.c.cmodule.import_time with config.change_flags(traceback__limit=config.traceback__compile_limit): _fn, _i, _o = self.linker.make_thunk( input_storage=input_storage_lists, storage_map=storage_map ) end_linker = time.time() linker_time = end_linker - start_linker aesara.compile.profiling.total_time_linker += linker_time _logger.debug(f"Linker took {linker_time:f} seconds") if self.profile: self.profile.linker_time += linker_time _fn.time_thunks = self.profile.flag_time_thunks import_time = aesara.link.c.cmodule.import_time - start_import_time self.profile.import_time += import_time fn = self.function_builder( _fn, _i, _o, self.indices, self.outputs, defaults, self.unpack_single, self.return_none, self.output_keys, self, name=self.name, ) fn.profile = self.profile return fn def _constructor_FunctionMaker(kwargs): # Needed for old pickle # Old pickle have at least the problem that output_keys where not saved. if config.unpickle_function: if config.reoptimize_unpickled_function: del kwargs["fgraph"] return FunctionMaker(**kwargs) else: return None __checkers: List = [] def check_equal(x, y): for checker in __checkers: try: return checker(x, y) except Exception: continue return x == y def register_checker(checker): __checkers.insert(0, checker) def orig_function( inputs, outputs, mode=None, accept_inplace=False, name=None, profile=None, on_unused_input=None, output_keys=None, ): """ Return a Function that will calculate the outputs from the inputs. Parameters ---------- inputs : list of `SymbolicInput` or `In` instances outputs : a SymbolicOutput or a list of `SymbolicOutput` or `Out` instances The return value of the returned function will match the format of this argument (either the value itself or a list of one or more return values). mode : descriptive string or Mode instance Default of None means to use `config.mode` (see below for descriptive string list). name : str An optional name for this function. If used, the profile mode will print the time spent in this function. accept_inplace : bool True iff the graph can contain inplace operations prior to the optimization phase (default is False). profile : None or ProfileStats instance on_unused_input : {'raise', 'warn', 'ignore', None} What to do if a variable in the 'inputs' list is not used in the graph. output_keys : If the outputs were provided to aesara.function as a list, then output_keys is None. Otherwise, if outputs were provided as a dict, output_keys is the sorted list of keys from the outputs. Notes ----- Currently, the library provides the following mode strings: - FAST_RUN (default) (optimize without too much time) - FAST_COMPILE (minimal optimization) - DebugMode: verify many internal conditions that are normally assumed (slow) """ # Every element of the input list will be upgraded to an `In` instance if # necessary, using the rules implemented by the `convert_function_input` # function. # Similarly, every element of the output list will be upgraded to an `Out` # instance if necessary: t1 = time.time() mode = aesara.compile.mode.get_mode(mode) inputs = list(map(convert_function_input, inputs)) if outputs is not None: if isinstance(outputs, (list, tuple)): outputs = list(map(FunctionMaker.wrap_out, outputs)) else: outputs = FunctionMaker.wrap_out(outputs) defaults = [getattr(input, "value", None) for input in inputs] if isinstance(mode, (list, tuple)): # "mode comparison" semantics raise Exception("We do not support the passing of multiple modes") fn = None try: Maker = getattr(mode, "function_maker", FunctionMaker) m = Maker( inputs, outputs, mode, accept_inplace=accept_inplace, profile=profile, on_unused_input=on_unused_input, output_keys=output_keys, name=name, ) with config.change_flags(compute_test_value="off"): fn = m.create(defaults) finally: t2 = time.time() if fn and profile: profile.compile_time += t2 - t1 # TODO: append profile.nb_nodes = len(fn.maker.fgraph.apply_nodes) return fn def convert_function_input(input): """ Upgrade a input shortcut to an In instance. The rules for upgrading are as follows: - a `Variable` instance r will be upgraded like `In`(r) - a tuple (name, r) will be `In`(r, name=name) - a tuple (r, val) will be `In`(r, value=value, autoname=True) - a tuple ((r,up), val) will be `In`(r, value=value, update=up, autoname=True) - a tuple (name, r, val) will be `In`(r, name=name, value=value) - a tuple (name, (r,up), val) will be `In`(r, name=name, value=val, update=up, autoname=True) """ if isinstance(input, SymbolicInput): return input elif isinstance(input, Constant): raise TypeError(f"A Constant instance is not a legal function input: {input}") elif isinstance(input, Variable): return In(input) elif isinstance(input, (list, tuple)): orig = input if not input: raise TypeError(f"Nonsensical input specification: {input}") if isinstance(input[0], str): name = input[0] input = input[1:] else: name = None if isinstance(input[0], (list, tuple)): if len(input[0]) != 2 or len(input) != 2: raise TypeError( f"Invalid input syntax: {orig} (check " "documentation or use an In instance)" ) (variable, update), value = input elif isinstance(input[0], Variable): if len(input) == 1: variable, update, value = input[0], None, None elif len(input) == 2: (variable, value), update = input, None else: raise TypeError( f"Invalid input syntax: {orig} (check " "documentation or use an In instance)" ) elif isinstance(input[0], SymbolicInput): if len(input) == 1: return input[0] elif len(input) == 2: input, value = input if name is not None: input.name = name input.value = value return input else: raise TypeError(f"The input specification is not valid: {input}") if not isinstance(variable, Variable): raise TypeError( f"Unknown input type: {type(variable)}, expected Variable instance" ) if update is not None and not isinstance(update, Variable): raise TypeError( f"Unknown update type: {type(update)}, expected Variable instance" ) if value is not None and isinstance(value, (Variable, SymbolicInput)): raise TypeError( f"The value for input {variable} should not be a Variable " f"or SymbolicInput instance (got: {value})" ) return In(variable, name=name, value=value, update=update) else: raise TypeError( f"Unknown input type: {type(input)}, expected Variable instance" ) def get_info_on_inputs(named_inputs, n_unnamed_inputs): """ Return a human-readable description of named and un-named inputs. """ n_named_inputs = len(named_inputs) def get_plural(n): if n > 1: return "s" else: return "" if n_named_inputs == 0: if n_unnamed_inputs == 0: msg = "The function is supposed to have no input." else: if n_unnamed_inputs == 1: msg = ( "The function has a single input variable which has no " "name, and thus cannot be assigned through a keyword" " argument (use 'name=...' in a Variable's " "constructor to give it a name)." ) else: # Use plural. msg = ( f"The function has {n_unnamed_inputs} inputs, but none of them is named," " and thus they cannot be assigned through keyword " "arguments (use 'name=...' in a Variable's " "constructor to give it a name)." ) else: if n_unnamed_inputs == 0: msg = "The function has {} named input{} ({}).".format( n_named_inputs, get_plural(n_named_inputs), ", ".join(named_inputs), ) else: msg = ( f"The function has {n_named_inputs} named input{get_plural(n_named_inputs)} ({", ".join(named_inputs)}), and {n_unnamed_inputs} unnamed " f"input{get_plural(n_unnamed_inputs)} which thus cannot be accessed through keyword " f"argument{get_plural(n_unnamed_inputs)} (use 'name=...' in a variable's constructor " "to give it a name)." ) return msg
""" Driver of graph construction, optimization, and linking. """ import copy import copyreg import logging import os import pickle import time import warnings from itertools import chain from typing import List import numpy as np import aesara import aesara.compile.profiling from aesara.compile.compilelock import lock_ctx from aesara.compile.io import In, SymbolicInput, SymbolicOutput from aesara.compile.ops import deep_copy_op, view_op from aesara.configdefaults import config from aesara.graph.basic import ( Constant, Variable, ancestors, clone_get_equiv, graph_inputs, vars_between, ) from aesara.graph.destroyhandler import DestroyHandler from aesara.graph.features import PreserveVariableAttributes from aesara.graph.fg import FunctionGraph, InconsistencyError from aesara.graph.op import HasInnerGraph from aesara.graph.opt_utils import is_same_graph from aesara.graph.utils import get_variable_trace_string from aesara.link.basic import Container from aesara.link.utils import raise_with_op _logger = logging.getLogger("aesara.compile.function.types") __docformat__ = "restructuredtext en" class UnusedInputError(Exception): """ A symbolic input passed to function is not needed. """ def alias_root(v): """ Return the variable to which v is aliased by view_maps and destroy_maps. """ if v.owner is None: return v vmap = v.owner.op.view_map dmap = v.owner.op.destroy_map outpos = v.owner.outputs.index(v) v_views = vmap.get(outpos, []) + dmap.get(outpos, []) if len(v_views) > 1: raise NotImplementedError( f"{v} is a view/destroyed version of more then one inputs. " "Currently, we only support the case where an output is a view or " "a destroyed version of one input." ) elif v_views: return alias_root(v.owner.inputs[v_views[0]]) else: return v def view_tree_set(fgraph, v, treeset): """ Add to `treeset` all variables that are views of v, given that v is not a view. """ treeset.add(v) for cl, v_input_pos_to_cl in fgraph.clients[v]: if cl == "output": continue vmap = cl.op.view_map dmap = cl.op.destroy_map for opos, iposlist in chain(vmap.items(), dmap.items()): if v_input_pos_to_cl in iposlist: if cl.outputs[opos] not in treeset: view_tree_set(fgraph, cl.outputs[opos], treeset) def infer_reuse_pattern(fgraph, outputs_to_disown): """ Given an fgraph and a list of variables, returns the list or set of all variables which may share the same underlying data storage as any of the specified variables. Used internally by function, FunctionMaker. This list (or set) is also referred to as no_recycling sometimes, especially by linker code. """ rval = set() for o in outputs_to_disown: view_tree_set(fgraph, alias_root(o), rval) # remove from rval all of the inputs, constants, values. rval = {r for r in rval if r.owner is not None} return rval def fgraph_updated_vars(fgraph, expanded_inputs): """ Reconstruct the full "updates" dictionary, mapping from FunctionGraph input variables to the fgraph outputs that will replace their values. Returns ------- dict variable -> variable """ updated_vars = {} potential_values = list(fgraph.outputs) # copy the list if len(expanded_inputs) != len(fgraph.inputs): raise ValueError("expanded_inputs must match len(fgraph.inputs)") for e_input, ivar in reversed(list(zip(expanded_inputs, fgraph.inputs))): if e_input.update is not None: updated_vars[ivar] = potential_values.pop() return updated_vars class Supervisor: """ Listener for FunctionGraph events which makes sure that no operation overwrites the contents of protected Variables. The outputs of the FunctionGraph are protected by default. """ def __init__(self, protected): self.protected = list(protected) def validate(self, fgraph): if config.cycle_detection == "fast" and hasattr(fgraph, "has_destroyers"): if fgraph.has_destroyers(self.protected): raise InconsistencyError("Trying to destroy protected variables.") return True if not hasattr(fgraph, "destroyers"): return True for r in self.protected + list(fgraph.outputs): if fgraph.destroyers(r): raise InconsistencyError(f"Trying to destroy a protected variable: {r}") def std_fgraph(input_specs, output_specs, accept_inplace=False): """ Makes an FunctionGraph corresponding to the input specs and the output specs. Any SymbolicInput in the input_specs, if its update field is not None, will add an output to the FunctionGraph corresponding to that update. The return value is the FunctionGraph as well as a list of SymbolicOutput instances corresponding to the updates. If accept_inplace is False, the graph will be checked for inplace operations and an exception will be raised if it has any. If accept_inplace is True, a DestroyHandler will be added to the FunctionGraph if there are any inplace operations. The returned FunctionGraph is a clone of the graph between the provided inputs and outputs. """ orig_inputs = [spec.variable for spec in input_specs] # Extract the updates and the mapping between update outputs and # the updated inputs. updates = [] update_mapping = {} out_idx = len(output_specs) for inp_idx in range(len(input_specs)): if input_specs[inp_idx].update: updates.append(input_specs[inp_idx].update) update_mapping[out_idx] = inp_idx out_idx += 1 orig_outputs = [spec.variable for spec in output_specs] + updates fgraph = FunctionGraph(orig_inputs, orig_outputs, update_mapping=update_mapping) for node in fgraph.apply_nodes: if node.op.destroy_map: if not accept_inplace: raise TypeError(f"Graph must not contain inplace operations: {node}") else: fgraph.attach_feature(DestroyHandler()) break # We need to protect all immutable inputs from inplace operations. fgraph.attach_feature( Supervisor( input for spec, input in zip(input_specs, fgraph.inputs) if not ( spec.mutable or (hasattr(fgraph, "destroyers") and fgraph.has_destroyers([input])) ) ) ) # If named nodes are replaced, keep the name for feature in std_fgraph.features: fgraph.attach_feature(feature()) return fgraph, list(map(SymbolicOutput, updates)) std_fgraph.features = [PreserveVariableAttributes] class AliasedMemoryError(Exception): """ Memory is aliased that should not be. """ ### # Function ### # unique id object used as a placeholder for duplicate entries DUPLICATE = ["DUPLICATE"] class Function: """ Type of the functions returned by aesara.function or aesara.FunctionMaker.create. `Function` is the callable object that does computation. It has the storage of inputs and outputs, performs the packing and unpacking of inputs and return values. It implements the square-bracket indexing so that you can look up the value of a symbolic node. Functions are copyable via {{{fn.copy()}}} and {{{copy.copy(fn)}}}. When a function is copied, this instance is duplicated. Contrast with self.maker (instance of `FunctionMaker`) that is shared between copies. The meaning of copying a function is that the containers and their current values will all be duplicated. This requires that mutable inputs be copied, whereas immutable inputs may be shared between copies. A Function instance is hashable, on the basis of its memory address (its id). A Function instance is only equal to itself. A Function instance may be serialized using the `pickle` or `cPickle` modules. This will save all default inputs, the graph, and WRITEME to the pickle file. A Function instance have a ``trust_input`` field that default to False. When True, we don't do extra check of the input to give better error message. In some case, python code will still return the good results if you pass a python or numpy scalar instead of a numpy tensor. C code should raise an error if you pass an object of the wrong type. Attributes ---------- finder inv_finder """ pickle_aliased_memory_strategy = "warn" """ How to deal with pickling finding aliased storage. Meaningful settings are: 'ignore', 'warn', 'raise'. If the value is 'warn', then a message will be printed to stderr if aliased storage is detected during pickle.dump. If the value is 'raise', then an AliasedMemoryError will be raised if aliased storage is detected during pickle.dump. """ input_storage = None """ List of Container instances. """ output_storage = None """ List of Container instances. """ indices = None """ List of (SymbolicInput, indices, [SymbolicInput,...]), one tuple for each input. The first tuple element is the SymbolicInput object for the corresponding function input. The second and third tuple elements are used only by Kits, which are deprecated. """ defaults = None """ List of 3-tuples, one 3-tuple for each input. Tuple element 0: Bool: Is this input required at each function call? Tuple element 1: Bool: Should this inputs value be reverted after each call? Tuple element 2: Any: The value associated with this input. """ unpack_single = None """ Bool: for outputs lists of length 1, should the 0'th element be returned directly? """ return_none = None """ Bool: whether the function should return None or not. """ maker = None """ FunctionMaker instance. """ fn = None """ A function that evaluates the graph. Typically a linker's make_thunk method created this function. """ finder = None """ Dictionary mapping several kinds of things to containers. We set an entry in finder for: - the index of the input - the variable instance the input is based on - the name of the input All entries map to the container or to DUPLICATE if an ambiguity is detected. """ inv_finder = None """ Dict. Reverse lookup of `finder`. It maps container -> SymbolicInput """ def __init__( self, fn, input_storage, output_storage, indices, outputs, defaults, unpack_single, return_none, output_keys, maker, name=None, ): self.fn = fn self.input_storage = input_storage self.output_storage = output_storage self.indices = indices self.outputs = outputs self.defaults = defaults self.unpack_single = unpack_single self.return_none = return_none self.maker = maker self.profile = None # reassigned in FunctionMaker.create self.trust_input = False # If True, we don't check the input parameter self.name = name self.nodes_with_inner_function = [] self.output_keys = output_keys # See if we have any mutable / borrow inputs # TODO: this only need to be set if there is more then 1 input self._check_for_aliased_inputs = False for i in maker.inputs: # If the input is a shared variable, the memory region is # under Aesara control and so we don't need to check if it # is aliased as we never do that. if ( isinstance(i, In) and not i.shared and (getattr(i, "borrow", False) or getattr(i, "mutable", False)) ): self._check_for_aliased_inputs = True break # We will be popping stuff off this `containers` object. It is a copy. containers = list(self.input_storage) finder = {} inv_finder = {} def distribute(indices, cs, value): input.distribute(value, indices, cs) for c in cs: c.provided += 1 # Store the list of names of named inputs. named_inputs = [] # Count the number of un-named inputs. n_unnamed_inputs = 0 # Initialize the storage # this loop works by modifying the elements (as variable c) of # self.input_storage inplace. for i, ((input, indices, sinputs), (required, refeed, value)) in enumerate( zip(self.indices, defaults) ): if indices is None: # containers is being used as a stack. Here we pop off # the next one. c = containers[0] c.strict = getattr(input, "strict", False) c.allow_downcast = getattr(input, "allow_downcast", None) if value is not None: # Always initialize the storage. if isinstance(value, Container): # There is no point in obtaining the current value # stored in the container, since the container is # shared. # For safety, we make sure 'refeed' is False, since # there is no need to refeed the default value. assert not refeed else: c.value = value c.required = required c.implicit = input.implicit # this is a count of how many times the input has been # provided (reinitialized to 0 on __call__) c.provided = 0 finder[i] = c finder[input.variable] = c if input.name not in finder: finder[input.name] = c else: finder[input.name] = DUPLICATE if input.name is None: n_unnamed_inputs += 1 else: named_inputs.append(input.name) inv_finder[c] = input containers[:1] = [] self.finder = finder self.inv_finder = inv_finder # this class is important in overriding the square-bracket notation: # fn.value[x] # self reference is available via the closure on the class class ValueAttribute: def __getitem__(self, item): try: s = finder[item] except KeyError: raise TypeError(f"Unknown input or state: {item}") if s is DUPLICATE: raise TypeError( f"Ambiguous name: {item} - please check the " "names of the inputs of your function " "for duplicates." ) if isinstance(s, Container): return s.value else: raise NotImplementedError def __setitem__(self, item, value): try: s = finder[item] except KeyError: # Print informative error message. msg = get_info_on_inputs(named_inputs, n_unnamed_inputs) raise TypeError(f"Unknown input or state: {item}. {msg}") if s is DUPLICATE: raise TypeError( f"Ambiguous name: {item} - please check the " "names of the inputs of your function " "for duplicates." ) if isinstance(s, Container): s.value = value s.provided += 1 else: s(value) def __contains__(self, item): return finder.__contains__(item) # this class is important in overriding the square-bracket notation: # fn.container[x] # self reference is available via the closure on the class class ContainerAttribute: def __getitem__(self, item): return finder[item] def __contains__(self, item): return finder.__contains__(item) # You cannot set the container self._value = ValueAttribute() self._container = ContainerAttribute() # Compute self.n_returned_outputs. # This is used only when fn.need_update_inputs is False # because we're using one of the VM objects and it is # putting updates back into the input containers all by itself. assert len(self.maker.expanded_inputs) == len(self.input_storage) self.n_returned_outputs = len(self.output_storage) for input in self.maker.expanded_inputs: if input.update is not None: self.n_returned_outputs -= 1 for node in self.maker.fgraph.apply_nodes: if isinstance(node.op, HasInnerGraph): self.nodes_with_inner_function.append(node.op) def __contains__(self, item): return self.value.__contains__(item) def __getitem__(self, item): return self.value[item] def __setitem__(self, item, value): self.value[item] = value def __copy__(self): """ Copy a function. Copied function have separate intermediate storages and output storages with original function """ return self.copy() def copy( self, share_memory=False, swap=None, delete_updates=False, name=None, profile=None, ): """ Copy this function. Copied function will have separated maker and fgraph with original function. User can choose whether to separate storage by changing the share_memory arguments. Parameters ---------- share_memory : boolean When True, two function share intermediate storages(storages except input and output storages). Otherwise two functions will only share partial storages and same maker. If two functions share memory and allow_gc=False, this will increase executing speed and save memory. swap : dict Dictionary that map old SharedVariables to new SharedVariables. Default is None. NOTE: The shared variable swap in only done in the new returned function, not in the user graph. delete_updates : boolean If True, Copied function will not have updates. name : string If provided, will be the name of the new Function. Otherwise, it will be old + " copy" profile : as aesara.function profile parameter Returns ------- aesara.Function Copied aesara.Function """ # helper function def checkSV(sv_ori, sv_rpl): """ Assert two SharedVariable follow some restirctions: 1. same type 2. same shape or dim? """ SharedVariable = aesara.tensor.sharedvar.SharedVariable assert isinstance(sv_ori, SharedVariable), ( "Key of swap should be SharedVariable, given:", sv_ori, " type", type(sv_ori), ) assert isinstance(sv_rpl, SharedVariable), ( "Value of swap should be SharedVariable, given:", sv_rpl, "type", type(sv_ori), ) assert sv_ori.type == sv_rpl.type, ( "Type of given SharedVariable conflicts with original one", "Type of given SharedVariable:", sv_rpl.type, "Type of original SharedVariable:", sv_ori.type, ) maker = self.maker # Copy Ins and their storage. # so that they have different storage as their value ins = [copy.copy(input) for input in maker.inputs] # Delete update output in fgraph and updates In instances if needed if delete_updates: # The first len(maker.outputs) variables are original variables. # The rest are the updates. out_vars = maker.fgraph.outputs[: len(maker.outputs)] else: out_vars = maker.fgraph.outputs # Init new fgraph using copied variables and get memo # memo: a dict that map old variables to new variables memo = clone_get_equiv(maker.fgraph.inputs, out_vars) fg_cpy = FunctionGraph( [memo[i] for i in maker.fgraph.inputs], [memo[o] for o in out_vars], clone=False, ) # Re initialize Outs and swap update and variable in Ins # By doing this, we can pass FunctionMaker._check_unused_inputs() outs = list(map(SymbolicOutput, fg_cpy.outputs[: len(maker.outputs)])) for out_ori, out_cpy in zip(maker.outputs, outs): out_cpy.borrow = out_ori.borrow # swap SharedVariable if swap is not None: exist_svs = [i.variable for i in maker.inputs] # Check if given ShareVariables exist for sv in swap.keys(): if sv not in exist_svs: raise ValueError(f"SharedVariable: {sv.name} not found") # Swap SharedVariable in fgraph and In instances for index, (i, in_v) in enumerate(zip(ins, fg_cpy.inputs)): # Variables in maker.inputs are defined by user, therefore we # use them to make comparison and do the mapping. # Otherwise we don't touch them. var = maker.inputs[index].variable if var in swap: swap_sv = swap[var] checkSV(i.variable, swap_sv) # swap variable and value of In instances i.variable = swap_sv i.value = swap_sv.container # In the fgraph we use the cloned SharedVariable swap_sv = swap_sv.clone() # Swap SharedVariable in fgraph # if inputs was replaced, change self.inputs fg_cpy.inputs[index] = swap_sv fg_cpy.replace(in_v, swap_sv, reason="Swap SV") # Delete update if needed update_i = len(outs) for i, in_var in zip(ins, fg_cpy.inputs): i.variable = in_var if not delete_updates and i.update is not None: i.update = fg_cpy.outputs[update_i] update_i += 1 else: i.update = None # Construct new storage_map that map new variable to old storage, # so that the ensuing function shares storage with the original one storage_map = self.fn.storage_map new_storage_map = {} # TODO: We could share the output storage, but we must make sure # 2 different function call won't override each other values. This # is already done elsewhere, so to reuse it the user would need to # use Out(var, borrow=True) and maybe the mutable=True flag too. # But to be safe for now as it isn't documented and we aren't sure # it is well tested, we don't share the part of the storage_map. if share_memory: i_o_vars = maker.fgraph.inputs + maker.fgraph.outputs for key in storage_map.keys(): if key not in i_o_vars: new_storage_map[memo[key]] = storage_map[key] if not name and self.name: name = self.name + " copy" input_storage = [i.value for i in ins] # reinitialize new maker and create new function if profile is None: profile = config.profile or config.print_global_stats # profile -> True or False if profile is True: if name: message = name else: message = str(profile.message) + " copy" profile = aesara.compile.profiling.ProfileStats(message=message) # profile -> object elif type(profile) == str: profile = aesara.compile.profiling.ProfileStats(message=profile) f_cpy = maker.__class__( inputs=ins, outputs=outs, fgraph=fg_cpy, mode=maker.mode, profile=profile, # When removing updates containing variables # not used in the output function, copy # generates an unused implicit input. # We ignore the resulting errors, # but could change it to 'warn' if this might # cause problems. on_unused_input="ignore", function_builder=maker.function_builder, # As this is an optimized graph, it # can contain inplace. DebugMode check # that. accept_inplace=True, ).create(input_storage, storage_map=new_storage_map) for in_ori, in_cpy, ori, cpy in zip( maker.inputs, f_cpy.maker.inputs, self.input_storage, f_cpy.input_storage ): # Share immutable ShareVariable and constant input's storage swapped = swap is not None and in_ori.variable in swap # Using the original storage if SharedVariable will not be updated # and is not swapped if not in_ori.mutable and not swapped: cpy.data = ori.data in_cpy.value = in_ori.value # Reconstruct Function.finder which map Variable defined by user # to container, to make Function.value and Function.data work well. # Replace variable in new maker.inputs by the original ones. # So that user can swap SharedVariable in a swapped function container = f_cpy.finder.pop(in_cpy.variable) if not swapped: f_cpy.finder[in_ori.variable] = container in_cpy.variable = in_ori.variable else: f_cpy.finder[swap[in_ori.variable]] = container in_cpy.variable = swap[in_ori.variable] f_cpy.name = name f_cpy.maker.fgraph.name = name return f_cpy def __call__(self, *args, **kwargs): """ Evaluates value of a function on given arguments. Parameters ---------- args : list List of inputs to the function. All inputs are required, even when some of them are not necessary to calculate requested subset of outputs. kwargs : dict The function inputs can be passed as keyword argument. For this, use the name of the input or the input instance as the key. Keyword argument ``output_subset`` is a list of either indices of the function's outputs or the keys belonging to the `output_keys` dict and represent outputs that are requested to be calculated. Regardless of the presence of ``output_subset``, the updates are always calculated and processed. To disable the updates, you should use the ``copy`` method with ``delete_updates=True``. Returns ------- list List of outputs on indices/keys from ``output_subset`` or all of them, if ``output_subset`` is not passed. """ def restore_defaults(): for i, (required, refeed, value) in enumerate(self.defaults): if refeed: if isinstance(value, Container): value = value.storage[0] self[i] = value profile = self.profile t0 = time.time() output_subset = kwargs.pop("output_subset", None) if output_subset is not None and self.output_keys is not None: output_subset = [self.output_keys.index(key) for key in output_subset] # Reinitialize each container's 'provided' counter if self.trust_input: i = 0 for arg in args: s = self.input_storage[i] s.storage[0] = arg i += 1 else: for c in self.input_storage: c.provided = 0 if len(args) + len(kwargs) > len(self.input_storage): raise TypeError("Too many parameter passed to aesara function") # Set positional arguments i = 0 for arg in args: # TODO: provide a Param option for skipping the filter if we # really want speed. s = self.input_storage[i] # see this emails for a discuation about None as input # https://groups.google.com/group/theano-dev/browse_thread/thread/920a5e904e8a8525/4f1b311a28fc27e5 if arg is None: s.storage[0] = arg else: try: s.storage[0] = s.type.filter( arg, strict=s.strict, allow_downcast=s.allow_downcast ) except Exception as e: function_name = "aesara function" argument_name = "argument" if self.name: function_name += ' with name "' + self.name + '"' if hasattr(arg, "name") and arg.name: argument_name += ' with name "' + arg.name + '"' where = get_variable_trace_string(self.maker.inputs[i].variable) if len(e.args) == 1: e.args = ( "Bad input " + argument_name + " to " + function_name + f" at index {int(i)} (0-based). {where}" + e.args[0], ) else: e.args = ( "Bad input " + argument_name + " to " + function_name + f" at index {int(i)} (0-based). {where}" ) + e.args restore_defaults() raise s.provided += 1 i += 1 # Set keyword arguments if kwargs: # for speed, skip the items for empty kwargs for k, arg in kwargs.items(): self[k] = arg if ( not self.trust_input and # The getattr is only needed for old pickle getattr(self, "_check_for_aliased_inputs", True) ): # Collect aliased inputs among the storage space args_share_memory = [] for i in range(len(self.input_storage)): i_var = self.maker.inputs[i].variable i_val = self.input_storage[i].storage[0] if hasattr(i_var.type, "may_share_memory"): is_aliased = False for j in range(len(args_share_memory)): group_j = zip( [ self.maker.inputs[k].variable for k in args_share_memory[j] ], [ self.input_storage[k].storage[0] for k in args_share_memory[j] ], ) if any( [ ( var.type is i_var.type and var.type.may_share_memory(val, i_val) ) for (var, val) in group_j ] ): is_aliased = True args_share_memory[j].append(i) break if not is_aliased: args_share_memory.append([i]) # Check for groups of more than one argument that share memory for group in args_share_memory: if len(group) > 1: # copy all but the first for j in group[1:]: self.input_storage[j].storage[0] = copy.copy( self.input_storage[j].storage[0] ) # Check if inputs are missing, or if inputs were set more than once, or # if we tried to provide inputs that are supposed to be implicit. if not self.trust_input: for c in self.input_storage: if c.required and not c.provided: restore_defaults() raise TypeError( f"Missing required input: {getattr(self.inv_finder[c], 'variable', self.inv_finder[c])}" ) if c.provided > 1: restore_defaults() raise TypeError( f"Multiple values for input: {getattr(self.inv_finder[c], 'variable', self.inv_finder[c])}" ) if c.implicit and c.provided > 0: restore_defaults() raise TypeError( f"Tried to provide value for implicit input: {getattr(self.inv_finder[c], 'variable', self.inv_finder[c])}" ) # Do the actual work t0_fn = time.time() try: outputs = ( self.fn() if output_subset is None else self.fn(output_subset=output_subset) ) except Exception: restore_defaults() if hasattr(self.fn, "position_of_error"): # this is a new vm-provided function or c linker # they need this because the exception manipulation # done by raise_with_op is not implemented in C. thunk = None if hasattr(self.fn, "thunks"): thunk = self.fn.thunks[self.fn.position_of_error] raise_with_op( self.maker.fgraph, node=self.fn.nodes[self.fn.position_of_error], thunk=thunk, storage_map=getattr(self.fn, "storage_map", None), ) else: # old-style linkers raise their own exceptions raise dt_fn = time.time() - t0_fn self.maker.mode.fn_time += dt_fn if profile: profile.vm_call_time += dt_fn # Retrieve the values that were computed if outputs is None: outputs = [x.data for x in self.output_storage] assert len(outputs) == len(self.output_storage) # Remove internal references to required inputs. # These cannot be re-used anyway. for c in self.input_storage: if c.required: c.storage[0] = None # if we are allowing garbage collection, remove the # output reference from the internal storage cells if getattr(self.fn, "allow_gc", False): assert len(self.output_storage) == len(self.maker.fgraph.outputs) for o_container, o_variable in zip( self.output_storage, self.maker.fgraph.outputs ): if o_variable.owner is not None: # this node is the variable of computation # WARNING: This circumvents the 'readonly' attribute in x o_container.storage[0] = None if getattr(self.fn, "need_update_inputs", True): # Update the inputs that have an update function for input, storage in reversed( list(zip(self.maker.expanded_inputs, self.input_storage)) ): if input.update is not None: storage.data = outputs.pop() else: outputs = outputs[: self.n_returned_outputs] # Put default values back in the storage restore_defaults() # # NOTE: This logic needs to be replicated in # scan. # grep for 'PROFILE_CODE' # dt_call = time.time() - t0 aesara.compile.profiling.total_fct_exec_time += dt_call self.maker.mode.call_time += dt_call if profile: profile.fct_callcount += 1 profile.fct_call_time += dt_call if hasattr(self.fn, "update_profile"): self.fn.update_profile(profile) if profile.ignore_first_call: profile.reset() profile.ignore_first_call = False if self.return_none: return None elif self.unpack_single and len(outputs) == 1 and output_subset is None: return outputs[0] else: if self.output_keys is not None: assert len(self.output_keys) == len(outputs) if output_subset is None: return dict(zip(self.output_keys, outputs)) else: return { self.output_keys[index]: outputs[index] for index in output_subset } if output_subset is None: return outputs else: return [outputs[i] for i in output_subset] value = property( lambda self: self._value, None, # this property itself is not settable doc="dictionary-like access to the values associated with Variables", ) container = property( lambda self: self._container, None, # this property itself is not settable doc=("dictionary-like access to the containers associated with " "Variables"), ) def free(self): """ When allow_gc = False, clear the Variables in storage_map """ # 1.no allow_gc return False # 2.has allow_gc, if allow_gc is False, return True if not getattr(self.fn, "allow_gc", True): for key in self.fn.storage_map: if not isinstance(key, Constant): self.fn.storage_map[key][0] = None for node in self.nodes_with_inner_function: if hasattr(node.fn, "free"): node.fn.free() def get_shared(self): """ Return the shared variable read or updated by by this function. """ return [i.variable for i in self.maker.inputs if i.implicit] def sync_shared(self): if hasattr(aesara, "gpuarray") and aesara.gpuarray.pygpu_activated: import pygpu for i in self.maker.fgraph.update_mapping.values(): inp = self.input_storage[i] if isinstance(inp.data, pygpu.gpuarray.GpuArray): inp.data.sync() # pickling/deepcopy support for Function def _pickle_Function(f): # copy of the input storage list ins = list(f.input_storage) input_storage = [] for (input, indices, inputs), (required, refeed, default) in zip( f.indices, f.defaults ): input_storage.append(ins[0]) del ins[0] inputs_data = [x.data for x in f.input_storage] # HACK to detect aliased storage. # This is here because aliased relationships are not [currently] # preserved across the pickle operation if not (f.pickle_aliased_memory_strategy == "ignore"): all_data = input_storage + inputs_data for i, d_i in enumerate(all_data): for j, d_j in enumerate(all_data): if ( (i < j) and isinstance(d_i, np.ndarray) and isinstance(d_j, np.ndarray) ): if np.may_share_memory(d_i, d_j): if f.pickle_aliased_memory_strategy == "warn": _logger.warning( "aliased relationship between " f"Function arguments {d_i}, {d_j} " "will not be preserved by " "un-pickling operation" ) else: raise AliasedMemoryError(d_i, d_j) # The user can override trust_input. Our doc tell that. We should # not do that anymore and make sure the Maker have all the # information needed. rval = (_constructor_Function, (f.maker, input_storage, inputs_data, f.trust_input)) return rval def _constructor_Function(maker, input_storage, inputs_data, trust_input=False): if not config.unpickle_function: return None f = maker.create(input_storage, trustme=True) assert len(f.input_storage) == len(inputs_data) for container, x in zip(f.input_storage, inputs_data): assert ( (container.data is x) or (isinstance(x, np.ndarray) and (container.data == x).all()) or (container.data == x) ) f.trust_input = trust_input return f copyreg.pickle(Function, _pickle_Function) ### # FunctionMaker ### def insert_deepcopy(fgraph, wrapped_inputs, wrapped_outputs): """ Insert deepcopy in the fgraph to break aliasing of outputs """ # This loop was inserted to remove aliasing between outputs when # they all evaluate to the same value. Originally it was OK for # outputs to be aliased, but some of the outputs can be shared # variables, and is not good for shared variables to be # aliased. It might be possible to optimize this by making sure # there is no aliasing only between shared variables. # If some outputs are constant, we add deep copy to respect the # memory contract # We don't insert deep copy when the output.borrow is True for all # concerned outputs. assert len(wrapped_inputs) == len(fgraph.inputs) assert len(wrapped_outputs) == len(fgraph.outputs) reason = "insert_deepcopy" updated_fgraph_inputs = { fgraph_i for i, fgraph_i in zip(wrapped_inputs, fgraph.inputs) if getattr(i, "update", False) } # We can't use fgraph.inputs as this don't include Constant Value. all_graph_inputs = list(graph_inputs(fgraph.outputs)) has_destroyers_attr = hasattr(fgraph, "has_destroyers") for i in range(len(fgraph.outputs)): views_of_output_i = set() view_tree_set(fgraph, alias_root(fgraph.outputs[i]), views_of_output_i) copied = False # do not allow outputs to be aliased for j in range(i + 1, len(fgraph.outputs)): # We could don't put deep copy if both outputs have borrow==True # and not(wrapped_outputs[i].borrow and wrapped_outputs[j].borrow): if fgraph.outputs[j] in views_of_output_i: if wrapped_outputs[i].borrow and wrapped_outputs[j].borrow: fgraph.change_input( "output", i, view_op(fgraph.outputs[i]), reason=reason ) else: fgraph.change_input( "output", i, deep_copy_op(fgraph.outputs[i]), reason=reason ) copied = True break if not copied: for input_j in all_graph_inputs: # do not allow outputs to be aliased to an inputs (j), unless # a) that j'th input has been 'destroyed' by # e.g. in-place computations # b) that j'th input is a shared variable that is also # being updated if input_j in updated_fgraph_inputs: continue if input_j in views_of_output_i and not ( has_destroyers_attr and fgraph.has_destroyers([input_j]) ): # We don't put deep_copy_op if the input and the # output have borrow==True if input_j in fgraph.inputs: j = fgraph.inputs.index(input_j) if wrapped_outputs[i].borrow and wrapped_inputs[j].borrow: fgraph.change_input( "output", i, view_op(fgraph.outputs[i]), reason="insert_deepcopy", ) break else: fgraph.change_input( "output", i, deep_copy_op(fgraph.outputs[i]), reason="insert_deepcopy", ) break elif wrapped_outputs[i].borrow: fgraph.change_input( "output", i, view_op(fgraph.outputs[i]), reason="insert_deepcopy", ) break else: fgraph.change_input( "output", i, deep_copy_op(fgraph.outputs[i]), reason="insert_deepcopy", ) break NODEFAULT = ["NODEFAULT"] class FunctionMaker: """ `FunctionMaker` is the class to `create` `Function` instances. This class has the fgraph, the optimizer, and the linker. When copying a `Function`, there is no need to duplicate the `FunctionMaker` instance. Deepcopy still copies both, which can variable in re-compilation. Parameters ---------- inputs : list of SymbolicInput instances outputs : list of SymbolicOutput instances Outputs may also be a single Variable (not a list), in which case the functions produced by FunctionMaker will return their output value directly. mode : Mode instance Telling FunctionMaker how to optimize and link. None means to use the `config.mode`. accept_inplace : bool True iff it is acceptable to have inplace operations in the graph from the inputs to the outputs. on_unused_input : {'raise', 'warn', 'ignore', None} What to do if a variable in the 'inputs' list is not used in the graph. Possible values are: - 'raise': raise an error - 'warn': log a warning - 'ignore': do not do anything - None: Use the value in the Aesara flags on_unused_input. name : str An optional name for this function. If used, the profile mode will print the time spent in this function. """ @staticmethod def wrap_in(input): if isinstance(input, (SymbolicInput)): return input elif isinstance(input, Variable): # r -> SymbolicInput(variable=r) return SymbolicInput(input) elif isinstance(input, (list, tuple)): # (r, u) -> SymbolicInput(variable=r, update=u) if len(input) == 2: return SymbolicInput(input[0], update=input[1]) else: raise TypeError( f"Expected two elements in the list or tuple; got {input}" ) else: raise TypeError( f"Unknown input type: {type(input)} ({input}), expected Variable " "instance" ) @staticmethod def expand_in(sinput, rinputs): # For SymbolicInputKits, this extracts a list of SymbolicInput # instances and corresponding indices such that these # SymbolicInputs are representative of some of the Variable # instances in inputs. For SymbolicInput, this returns None # as the list of indices and a list with just the # SymbolicInput. # if isinstance(sinput, SymbolicInputKit): # return sinput.complete(rinputs) # elif isinstance(sinput, SymbolicInput): if isinstance(sinput, SymbolicInput): return [None, [sinput]] @staticmethod def wrap_out(output): if isinstance(output, SymbolicOutput): return output elif isinstance(output, Variable): return SymbolicOutput(output) else: raise TypeError(f"Unknown output type: {type(output)} ({output})") def optimize_graph_with_cache(self, optimizer, inputs, outputs): # This function is not finished graph_db_file = os.path.join(config.compiledir, "optimized_graphs.pkl") # the inputs, outputs, and size of the graph to be optimized inputs_new = [inp.variable for inp in inputs] outputs_new = [out.variable for out in outputs] size_new = len(self.fgraph.apply_nodes) # Beginning of cache optimizations. # Could be refactored in different functions. def load_graph_db(): if os.path.isfile(graph_db_file): print("graph_db already exists") else: # create graph_db with open(graph_db_file, "wb") as f: print(f"create new graph_db in {graph_db_file}") # load the graph_db dictionary try: with open(graph_db_file, "rb") as f, config.change_flags( unpickle_function=False ): # Temporary hack to allow # tests.scan.test_scan.T_Scan to # finish. Should be changed in definitive version. graph_db = pickle.load(f) print("graph_db loaded and it is not empty") except EOFError as e: # the file has nothing in it print(e) print("graph_db loaded and it is empty") graph_db = {} return graph_db def find_same_graph_in_db(graph_db): # If found_graph_in_db is None, then need to optimize. # Otherwise, return the graph found. found_graph_in_db = None # The sole purpose of this loop is to set 'need_optimize' by # going through graph_db, looking for graph that has the same # computation performed. for graph_old, graph_optimized in graph_db.items(): inputs_old = graph_old.inputs outputs_old = graph_old.outputs size_old = len(graph_old.apply_nodes) # Some heuristics to check is the same graphs have # already been optimized before. if len(inputs_new) != len(inputs_old): # If the inputs are of different size, # two graphs are for sure different print("need to optimize, because input size is different") continue elif len(outputs_new) != len(outputs_old): # If the inputs are of different size, # two graphs are for sure different print("need to optimize, because output size is different") continue elif not all( input_new.type == input_old.type for input_new, input_old in zip(inputs_new, inputs_old) ): print("need to optimize, because inputs are of different " "types") continue elif not all( output_new.type == output_old.type for output_new, output_old in zip(outputs_new, outputs_old) ): print("need to optimize, because outputs are of different " "types") continue elif not size_old == size_new: print( "need to optimize, because numbers of nodes in graph" " are different" ) continue else: flags = [] for i, (output_new, output_old) in enumerate( zip(outputs_new, outputs_old) ): print("loop through outputs node for both graphs") graph_old.variables = set( vars_between(graph_old.inputs, graph_old.outputs) ) # using clone allowed to avoid a lot of errors # deep copy seemed to had. f2 = graph_old.clone(check_integrity=False) t1 = output_new t2 = f2.outputs[i] givens = dict( zip( graph_inputs([t1]), graph_inputs([t2]), ) ) temp = dict( zip( graph_inputs([t1]), graph_inputs([t2]), ) ) # hack to remove inconsistent entry in givens # seems to work that but source of inconsistency # could be worth investigating. for key, value in temp.items(): if key.type != value.type: del givens[key] flag = is_same_graph(t1, t2, givens=givens) flags.append(flag) is_same = all(flags) if is_same: # found the match print("found a match, no need to optimize") found_graph_in_db = graph_optimized break return found_graph_in_db with lock_ctx(): graph_db = load_graph_db() print(f"loaded graph_db from {graph_db_file}, size={len(graph_db)}") found_graph = find_same_graph_in_db(graph_db) if found_graph: self.fgraph = found_graph optimizer_profile = None else: # this is a brand new graph, optimize it, save it to graph_db print("graph not found in graph_db, optimizing the graph") self.fgraph.variables = set( vars_between(self.fgraph.inputs, self.fgraph.outputs) ) # check_integrity parameters was added to ignore # "excess cached variables" errors. Works that way # but once again the error couldbe worth # investigating. before_opt = self.fgraph.clone(check_integrity=False) optimizer_profile = optimizer(self.fgraph) graph_db.update({before_opt: self.fgraph}) with open(graph_db_file, "wb") as f: pickle.dump(graph_db, f, -1) print("new graph saved into graph_db") return optimizer_profile def __init__( self, inputs, outputs, mode=None, accept_inplace=False, function_builder=Function, profile=None, on_unused_input=None, fgraph=None, output_keys=None, name=None, ): # Save the provided mode, not the instantiated mode. # The instantiated mode don't pickle and if we unpickle an Aesara # function and it get re-compiled, we want the current optimizer to be # used, not the optimizer when it was saved. self.mode = mode mode = aesara.compile.mode.get_mode(mode) # Assert old way of working isn't used if getattr(mode, "profile", None): raise TypeError("profile passed via 'mode'. This isn't supported anymore") self.profile = profile if profile: # This is very important: # 1) We preload the cache here to not have its timing # included in optimization that compile function. # 2) Do not refresh the cache here by default. It cause # too much execution time during testing as we compile # much more functions then the number of compile c # module. aesara.link.c.basic.get_module_cache().refresh() # Handle the case where inputs and/or outputs is a single # Variable (not in a list) unpack_single = False return_none = False if outputs is None: return_none = True outputs = [] if not isinstance(outputs, (list, tuple)): unpack_single = True outputs = [outputs] if not isinstance(inputs, (list, tuple)): inputs = [inputs] # Wrap them in In or Out instances if needed. inputs = [self.wrap_in(i) for i in inputs] outputs = [self.wrap_out(o) for o in outputs] _inputs = list( graph_inputs( [o.variable for o in outputs] + [i.update for i in inputs if getattr(i, "update", False)] ) ) # Check if some input variables are unused self._check_unused_inputs(inputs, outputs, on_unused_input) # Make a list of (SymbolicInput|SymblicInputKits, indices, # [SymbolicInput,...]), one tuple for each input. (See # Function.indices for more details) indices = [[input] + self.expand_in(input, _inputs) for input in inputs] if fgraph is None: need_opt = True # make the fgraph (copies the graph, creates NEW INPUT AND # OUTPUT VARIABLES) fgraph, additional_outputs = std_fgraph(inputs, outputs, accept_inplace) fgraph.profile = profile else: # fgraph is already an optimized one need_opt = False updates = [spec.update for spec in inputs if spec.update] additional_outputs = list(map(SymbolicOutput, updates)) self.fgraph = fgraph # Fetch the optimizer and linker optimizer, linker = mode.optimizer, copy.copy(mode.linker) if need_opt: # Why we add stack on node when it get done in output var? try: start_optimizer = time.time() # In case there is an error during optimization. optimizer_profile = None opt_time = None with config.change_flags( compute_test_value=config.compute_test_value_opt, traceback__limit=config.traceback__compile_limit, ): # now optimize the graph if config.cache_optimizations: optimizer_profile = self.optimize_graph_with_cache( optimizer, inputs, outputs ) else: optimizer_profile = optimizer(fgraph) end_optimizer = time.time() opt_time = end_optimizer - start_optimizer _logger.debug(f"Optimizing took {opt_time:f} seconds") # Add deep copy to respect the memory interface insert_deepcopy(fgraph, inputs, outputs + additional_outputs) finally: # If the optimizer got interrupted if opt_time is None: end_optimizer = time.time() opt_time = end_optimizer - start_optimizer aesara.compile.profiling.total_graph_opt_time += opt_time if profile: if optimizer_profile is None and hasattr(optimizer, "pre_profile"): optimizer_profile = optimizer.pre_profile profile.optimizer_time += opt_time if config.profile_optimizer: profile.optimizer_profile = (optimizer, optimizer_profile) # IF False, if mean the profile for that function was # explicitly disabled elif config.profile_optimizer and profile is not False: warnings.warn( ( "config.profile_optimizer requires config.profile to " " be set to True as well" ), stacklevel=3, ) # initialize the linker if not hasattr(linker, "accept"): raise ValueError( "'linker' parameter of FunctionMaker should be " f"a Linker with an accept method or one of {list(aesara.compile.mode.predefined_linkers.keys())}" ) # the 'no_borrow' outputs are the ones for which that we can't # return the internal storage pointer. assert len(fgraph.outputs) == len(outputs + additional_outputs) no_borrow = [ output for output, spec in zip(fgraph.outputs, outputs + additional_outputs) if not spec.borrow ] if no_borrow: self.linker = linker.accept( fgraph, no_recycling=infer_reuse_pattern(fgraph, no_borrow), profile=profile, ) else: self.linker = linker.accept(fgraph, profile=profile) if hasattr(linker, "accept_var_updates"): # hacky thing so VMLinker knows about updates self.linker.accept_var_updates(fgraph_updated_vars(fgraph, inputs)) fgraph.name = name self.indices = indices self.inputs = inputs self.expanded_inputs = inputs self.outputs = outputs self.unpack_single = unpack_single self.return_none = return_none self.accept_inplace = accept_inplace self.function_builder = function_builder self.on_unused_input = on_unused_input # Used for the pickling/copy self.output_keys = output_keys self.name = name self.required = [(i.value is None) for i in self.inputs] self.refeed = [ ( i.value is not None and not isinstance(i.value, Container) and i.update is None ) for i in self.inputs ] def _check_unused_inputs(self, inputs, outputs, on_unused_input): if on_unused_input is None: on_unused_input = config.on_unused_input if on_unused_input == "ignore": return # There should be two categories of variables in inputs: # - variables that have to be provided (used_inputs) # - shared variables that will be updated used_inputs = list( ancestors( ( [o.variable for o in outputs] + [i.update for i in inputs if getattr(i, "update", False)] ), blockers=[i.variable for i in inputs], ) ) msg = ( "aesara.function was asked to create a function computing " "outputs given certain inputs, but the provided input " "variable at index %i is not part of the computational graph " "needed to compute the outputs: %s.\n%s" ) warn_msg = ( "To make this warning into an error, you can pass the " "parameter on_unused_input='raise' to aesara.function. " "To disable it completely, use on_unused_input='ignore'." ) err_msg = ( "To make this error into a warning, you can pass the " "parameter on_unused_input='warn' to aesara.function. " "To disable it completely, use on_unused_input='ignore'." ) for i in inputs: if (i.variable not in used_inputs) and (i.update is None): if on_unused_input == "warn": warnings.warn( msg % (inputs.index(i), i.variable, warn_msg), stacklevel=6 ) elif on_unused_input == "raise": raise UnusedInputError(msg % (inputs.index(i), i.variable, err_msg)) else: raise ValueError( "Invalid value for keyword on_unused_input of aesara.function: " f"'{on_unused_input}'.\n" "Valid values are 'raise', 'warn', and 'ignore'." ) def create(self, input_storage=None, trustme=False, storage_map=None): """ Create a function. Parameters ---------- input_storage A list matching the inputs list and providing default values if the default for an input is None, then that input is a required input. For an input with an update, the default acts as initialization. trustme Disables some exceptions, used internally. """ if input_storage is None: input_storage = [None] * len(self.inputs) # list of independent one-element lists, will be passed to the linker input_storage_lists = [] defaults = [] # The following loop is to fill in the input_storage_lists and # defaults lists. assert len(self.indices) == len(input_storage) for i, ((input, indices, subinputs), input_storage_i) in enumerate( zip(self.indices, input_storage) ): # Replace any default value given as a variable by its # container. Note that this makes sense only in the # context of shared variables, but for now we avoid # dealing directly with them to avoid dependency on the # shared variables work-in-progress repository. if isinstance(input_storage_i, Variable): input_storage_i = input_storage_i.container if isinstance(input_storage_i, Container): # If the default is a Container, this means we want to # share the same storage. This is done by appending # input_storage_i.storage to input_storage_lists. if indices is not None: raise TypeError( "Cannot take a Container instance as " "default for a SymbolicInputKit." ) input_storage_lists.append(input_storage_i.storage) storage = input_storage[i].storage[0] else: # Normal case: one new, independent storage unit input_storage_lists.append([input_storage_i]) storage = input_storage_i required = self.required[i] refeed = self.refeed[i] # sanity check-- if an input is required it should not # need to be refed assert not (required and refeed) # shared variables need neither be input by the user nor refed if input.shared: assert not required assert not refeed storage = None # if an input is required, it never need be refed if required: storage = None # make sure that we only store a value if we actually need it if storage is not None: assert refeed or not required defaults.append((required, refeed, storage)) # Get a function instance start_linker = time.time() start_import_time = aesara.link.c.cmodule.import_time with config.change_flags(traceback__limit=config.traceback__compile_limit): _fn, _i, _o = self.linker.make_thunk( input_storage=input_storage_lists, storage_map=storage_map ) end_linker = time.time() linker_time = end_linker - start_linker aesara.compile.profiling.total_time_linker += linker_time _logger.debug(f"Linker took {linker_time:f} seconds") if self.profile: self.profile.linker_time += linker_time _fn.time_thunks = self.profile.flag_time_thunks import_time = aesara.link.c.cmodule.import_time - start_import_time self.profile.import_time += import_time fn = self.function_builder( _fn, _i, _o, self.indices, self.outputs, defaults, self.unpack_single, self.return_none, self.output_keys, self, name=self.name, ) fn.profile = self.profile return fn def _constructor_FunctionMaker(kwargs): # Needed for old pickle # Old pickle have at least the problem that output_keys where not saved. if config.unpickle_function: if config.reoptimize_unpickled_function: del kwargs["fgraph"] return FunctionMaker(**kwargs) else: return None __checkers: List = [] def check_equal(x, y): for checker in __checkers: try: return checker(x, y) except Exception: continue return x == y def register_checker(checker): __checkers.insert(0, checker) def orig_function( inputs, outputs, mode=None, accept_inplace=False, name=None, profile=None, on_unused_input=None, output_keys=None, ): """ Return a Function that will calculate the outputs from the inputs. Parameters ---------- inputs : list of `SymbolicInput` or `In` instances outputs : a SymbolicOutput or a list of `SymbolicOutput` or `Out` instances The return value of the returned function will match the format of this argument (either the value itself or a list of one or more return values). mode : descriptive string or Mode instance Default of None means to use `config.mode` (see below for descriptive string list). name : str An optional name for this function. If used, the profile mode will print the time spent in this function. accept_inplace : bool True iff the graph can contain inplace operations prior to the optimization phase (default is False). profile : None or ProfileStats instance on_unused_input : {'raise', 'warn', 'ignore', None} What to do if a variable in the 'inputs' list is not used in the graph. output_keys : If the outputs were provided to aesara.function as a list, then output_keys is None. Otherwise, if outputs were provided as a dict, output_keys is the sorted list of keys from the outputs. Notes ----- Currently, the library provides the following mode strings: - FAST_RUN (default) (optimize without too much time) - FAST_COMPILE (minimal optimization) - DebugMode: verify many internal conditions that are normally assumed (slow) """ # Every element of the input list will be upgraded to an `In` instance if # necessary, using the rules implemented by the `convert_function_input` # function. # Similarly, every element of the output list will be upgraded to an `Out` # instance if necessary: t1 = time.time() mode = aesara.compile.mode.get_mode(mode) inputs = list(map(convert_function_input, inputs)) if outputs is not None: if isinstance(outputs, (list, tuple)): outputs = list(map(FunctionMaker.wrap_out, outputs)) else: outputs = FunctionMaker.wrap_out(outputs) defaults = [getattr(input, "value", None) for input in inputs] if isinstance(mode, (list, tuple)): # "mode comparison" semantics raise Exception("We do not support the passing of multiple modes") fn = None try: Maker = getattr(mode, "function_maker", FunctionMaker) m = Maker( inputs, outputs, mode, accept_inplace=accept_inplace, profile=profile, on_unused_input=on_unused_input, output_keys=output_keys, name=name, ) with config.change_flags(compute_test_value="off"): fn = m.create(defaults) finally: t2 = time.time() if fn and profile: profile.compile_time += t2 - t1 # TODO: append profile.nb_nodes = len(fn.maker.fgraph.apply_nodes) return fn def convert_function_input(input): """ Upgrade a input shortcut to an In instance. The rules for upgrading are as follows: - a `Variable` instance r will be upgraded like `In`(r) - a tuple (name, r) will be `In`(r, name=name) - a tuple (r, val) will be `In`(r, value=value, autoname=True) - a tuple ((r,up), val) will be `In`(r, value=value, update=up, autoname=True) - a tuple (name, r, val) will be `In`(r, name=name, value=value) - a tuple (name, (r,up), val) will be `In`(r, name=name, value=val, update=up, autoname=True) """ if isinstance(input, SymbolicInput): return input elif isinstance(input, Constant): raise TypeError(f"A Constant instance is not a legal function input: {input}") elif isinstance(input, Variable): return In(input) elif isinstance(input, (list, tuple)): orig = input if not input: raise TypeError(f"Nonsensical input specification: {input}") if isinstance(input[0], str): name = input[0] input = input[1:] else: name = None if isinstance(input[0], (list, tuple)): if len(input[0]) != 2 or len(input) != 2: raise TypeError( f"Invalid input syntax: {orig} (check " "documentation or use an In instance)" ) (variable, update), value = input elif isinstance(input[0], Variable): if len(input) == 1: variable, update, value = input[0], None, None elif len(input) == 2: (variable, value), update = input, None else: raise TypeError( f"Invalid input syntax: {orig} (check " "documentation or use an In instance)" ) elif isinstance(input[0], SymbolicInput): if len(input) == 1: return input[0] elif len(input) == 2: input, value = input if name is not None: input.name = name input.value = value return input else: raise TypeError(f"The input specification is not valid: {input}") if not isinstance(variable, Variable): raise TypeError( f"Unknown input type: {type(variable)}, expected Variable instance" ) if update is not None and not isinstance(update, Variable): raise TypeError( f"Unknown update type: {type(update)}, expected Variable instance" ) if value is not None and isinstance(value, (Variable, SymbolicInput)): raise TypeError( f"The value for input {variable} should not be a Variable " f"or SymbolicInput instance (got: {value})" ) return In(variable, name=name, value=value, update=update) else: raise TypeError( f"Unknown input type: {type(input)}, expected Variable instance" ) def get_info_on_inputs(named_inputs, n_unnamed_inputs): """ Return a human-readable description of named and un-named inputs. """ n_named_inputs = len(named_inputs) def get_plural(n): if n > 1: return "s" else: return "" if n_named_inputs == 0: if n_unnamed_inputs == 0: msg = "The function is supposed to have no input." else: if n_unnamed_inputs == 1: msg = ( "The function has a single input variable which has no " "name, and thus cannot be assigned through a keyword" " argument (use 'name=...' in a Variable's " "constructor to give it a name)." ) else: # Use plural. msg = ( f"The function has {n_unnamed_inputs} inputs, but none of them is named," " and thus they cannot be assigned through keyword " "arguments (use 'name=...' in a Variable's " "constructor to give it a name)." ) else: if n_unnamed_inputs == 0: msg = "The function has {} named input{} ({}).".format( n_named_inputs, get_plural(n_named_inputs), ", ".join(named_inputs), ) else: msg = ( f"The function has {n_named_inputs} named input{get_plural(n_named_inputs)} ({', '.join(named_inputs)}), and {n_unnamed_inputs} unnamed " f"input{get_plural(n_unnamed_inputs)} which thus cannot be accessed through keyword " f"argument{get_plural(n_unnamed_inputs)} (use 'name=...' in a variable's constructor " "to give it a name)." ) return msg
#!/usr/bin/env python3 '''This is a copy of the python script that bashtop starts in a coprocess when using psutil for data collection''' import os, sys, subprocess, re, time, psutil from datetime import timedelta from collections import defaultdict from typing import List, Set, Dict, Tuple, Optional, Union system: str if "linux" in sys.platform: system = "Linux" elif "bsd" in sys.platform: system = "BSD" elif "darwin" in sys.platform: system = "MacOS" else: system = "Other" parent_pid: int = psutil.Process(os.getpid()).ppid() allowed_commands: Tuple[str] = ( 'get_proc', 'get_disks', 'get_cpu_name', 'get_cpu_cores', 'get_nics', 'get_cpu_cores', 'get_cpu_usage', 'get_cpu_freq', 'get_uptime', 'get_load_avg', 'get_mem', 'get_detailed_names_cmd', 'get_detailed_mem_time', 'get_net', 'get_cmd_out', 'get_sensors', 'get_sensors_check', 'get_ms' ) command: str = '' cpu_count: int = psutil.cpu_count() disk_hist: Dict = {} def cleaned(string: str) -> str: '''Escape characters not suitable for "echo -e" in bash''' return string.replace("\\", "\\\\").replace("$", "\\$").replace("\n", "\\n").replace("\t", "\\t").replace("\"", "\\\"").replace("\'", "\\\'") def get_cmd_out(cmd: str): '''Save bash the trouble of creating child processes by running through python instead''' print(subprocess.check_output(cmd, shell=True, universal_newlines=True).rstrip()) def get_ms(): '''Get current epoch millisecond''' t = str(time.time()).split(".") print(f'{t[0]}{t[1][:3]}') def get_sensors(): '''A clone of "sensors" but using psutil''' temps = psutil.sensors_temperatures() if not temps: return try: for name, entries in temps.items(): print(name) for entry in entries: print(f'{entry.label or name}: {entry.current}°C (high = {entry.high}°C, crit = {entry.critical}°C)') print() except: pass def get_sensors_check(): '''Check if get_sensors() output contains accepted CPU temperature values''' if not hasattr(psutil, "sensors_temperatures"): print("false"); return try: temps = psutil.sensors_temperatures() except: pass print("false"); return if not temps: print("false"); return try: for _, entries in temps.items(): for entry in entries: if entry.label.startswith(('Package', 'Core 0', 'Tdie')): print("true") return except: pass print("false") def get_cpu_name(): '''Fetch a suitable CPU identifier from the CPU model name string''' name: str = "" command: str = "" all_info: str = "" rem_line: str = "" if system == "Linux": command = "cat /proc/cpuinfo" rem_line = "model name" elif system == "MacOS": command ="sysctl -n machdep.cpu.brand_string" elif system == "BSD": command ="sysctl hw.model" rem_line = "hw.model" all_info = subprocess.check_output("LANG=C " + command, shell=True, universal_newlines=True) if rem_line: for line in all_info.split("\n"): if rem_line in line: name = re.sub( ".*" + rem_line + ".*:", "", line,1).lstrip() else: name = all_info if "Xeon" in name: name = name.split(" ") name = name[name.index("CPU")+1] elif "Ryzen" in name: name = name.split(" ") name = " ".join(name[name.index("Ryzen"):name.index("Ryzen")+3]) elif "CPU" in name: name = name.split(" ") name = name[name.index("CPU")-1] print(name) def get_cpu_cores(): '''Get number of CPU cores and threads''' cores: int = psutil.cpu_count(logical=False) threads: int = psutil.cpu_count(logical=True) print(f'{cores} {threads if threads else cores}') def get_cpu_usage(): cpu: float = psutil.cpu_percent(percpu=False) threads: List[float] = psutil.cpu_percent(percpu=True) print(f'{cpu:.0f}') for thread in threads: print(f'{thread:.0f}') def get_cpu_freq(): '''Get current CPU frequency''' try: print(f'{psutil.cpu_freq().current:.0f}') except: print(0) def get_uptime(): '''Get current system uptime''' print(str(timedelta(seconds=round(time.time()-psutil.boot_time(),0)))[:-3]) def get_load_avg(): '''Get CPU load average''' for lavg in os.getloadavg(): print(round(lavg, 2), ' ', end='') print() def get_mem(): '''Get current system memory and swap usage''' mem = psutil.virtual_memory() swap = psutil.swap_memory() try: cmem = mem.cached>>10 except: cmem = mem.active>>10 print(mem.total>>10, mem.free>>10, mem.available>>10, cmem, swap.total>>10, swap.free>>10) def get_nics(): '''Get a list of all network devices sorted by highest throughput''' io_all = psutil.net_io_counters(pernic=True) up_stat = psutil.net_if_stats() for nic in sorted(psutil.net_if_addrs(), key=lambda nic: (io_all[nic].bytes_recv + io_all[nic].bytes_sent), reverse=True): if up_stat[nic].isup is False: continue print(nic) def get_net(net_dev: str): '''Emulated /proc/net/dev for selected network device''' net = psutil.net_io_counters(pernic=True)[net_dev] print(0,net.bytes_recv,0,0,0,0,0,0,0,net.bytes_sent) def get_detailed_names_cmd(pid: int): '''Get name, parent name, username and arguments for selected pid''' p = psutil.Process(pid) pa = psutil.Process(p.ppid()) with p.oneshot(): print(p.name()) print(pa.name()) print(p.username()) cmd = ' '.join(p.cmdline()) or '[' + p.name() + ']' print(cleaned(cmd)) def get_detailed_mem_time(pid: int): '''Get memory usage and runtime for selected pid''' p = psutil.Process(pid) with p.oneshot(): print(p.memory_info().rss) print(timedelta(seconds=round(time.time()-p.create_time(),0))) def get_proc(sorting='cpu lazy', tree=False, prog_len=0, arg_len=0, search='', reverse=True, proc_per_cpu=True, max_lines=0): '''List all processess with pid, name, arguments, threads, username, memory percent and cpu percent''' line_count: int = 0 err: float = 0.0 reverse = not reverse if sorting == 'pid': sort_cmd = "p.info['pid']" elif sorting == 'program' or tree and sorting == "arguments": sort_cmd = "p.info['name']" reverse = not reverse elif sorting == 'arguments': sort_cmd = "' '.join(str(p.info['cmdline'])) or p.info['name']" reverse = not reverse elif sorting == 'threads': sort_cmd = "str(p.info['num_threads'])" elif sorting == 'user': sort_cmd = "p.info['username']" reverse = not reverse elif sorting == 'memory': sort_cmd = "str(p.info['memory_percent'])" elif sorting == 'cpu responsive': sort_cmd = "p.info['cpu_percent']" if proc_per_cpu else "(p.info['cpu_percent'] / cpu_count)" else: sort_cmd = "(sum(p.info['cpu_times'][:2] if not p.info['cpu_times'] == 0.0 else [0.0, 0.0]) * 1000 / (time.time() - p.info['create_time']))" if tree: proc_tree(width=prog_len + arg_len, sorting=sort_cmd, reverse=reverse, max_lines=max_lines, proc_per_cpu=proc_per_cpu, search=search) return print(f"{"Pid:":>7} {"Program:":<{prog_len}}", f"{"Arguments:":<{arg_len-4}}" if arg_len else '', f"{"Threads:" if arg_len else " Tr:"} {"User:":<9}Mem%{"Cpu%":>11}", sep='') for p in sorted(psutil.process_iter(['pid', 'name', 'cmdline', 'num_threads', 'username', 'memory_percent', 'cpu_percent', 'cpu_times', 'create_time'], err), key=lambda p: eval(sort_cmd), reverse=reverse): if p.info['name'] == 'idle' or p.info['name'] == err or p.info['pid'] == err: continue if p.info['cmdline'] == err: p.info['cmdline'] = "" if p.info['username'] == err: p.info['username'] = "?" if p.info['num_threads'] == err: p.info['num_threads'] = 0 if search: found = False for value in [ p.info['name'], ' '.join(p.info['cmdline']), str(p.info['pid']), p.info['username'] ]: if search in value: found = True break if not found: continue cpu = p.info['cpu_percent'] if proc_per_cpu else (p.info['cpu_percent'] / psutil.cpu_count()) mem = p.info['memory_percent'] cmd = ' '.join(p.info['cmdline']) or '[' + p.info['name'] + ']' print(f"{p.info["pid"]:>7} ", f"{cleaned(p.info["name"]):<{prog_len}.{prog_len-1}}", f"{cleaned(cmd):<{arg_len}.{arg_len-1}}" if arg_len else '', f"{p.info["num_threads"]:>4} " if p.info['num_threads'] < 1000 else '999> ', f"{p.info["username"]:<9.9}" if len(p.info['username']) < 10 else f"{p.info["username"][:8]:<8}+", f"{mem:>4.1f}" if mem < 100 else f"{mem:>4.0f} ", f"{cpu:>11.1f} " if cpu < 100 else f"{cpu:>11.0f} ", sep='') line_count += 1 if max_lines and line_count == max_lines: break def proc_tree(width: int, sorting: str = 'cpu lazy', reverse: bool = True, max_lines: int = 0, proc_per_cpu=True, search=''): '''List all processess in a tree view with pid, name, threads, username, memory percent and cpu percent''' tree_line_count: int = 0 err: float = 0.0 def create_tree(parent: int, tree, indent: str = '', inindent: str = ' ', found: bool = False): nonlocal infolist, tree_line_count, max_lines, tree_width, proc_per_cpu, search cont: bool = True if max_lines and tree_line_count >= max_lines: return try: name: str = psutil.Process(parent).name() if name == "idle": return except psutil.Error: pass name: str = '' try: getinfo: Dict = infolist[parent] except: pass getinfo: bool = False if search and not found: for value in [ name, str(parent), getinfo['username'] if getinfo else '' ]: if search in value: found = True break if not found: cont = False if cont: print(f"{f"{inindent}{parent} {cleaned(name)}":<{tree_width}.{tree_width-1}}", sep='', end='') if getinfo and cont: if getinfo['cpu_times'] == err: getinfo['num_threads'] = 0 if p.info['username'] == err: p.info['username'] = "?" cpu = getinfo['cpu_percent'] if proc_per_cpu else (getinfo['cpu_percent'] / psutil.cpu_count()) print(f"{getinfo["num_threads"]:>4} " if getinfo['num_threads'] < 1000 else '999> ', f"{getinfo["username"]:<9.9}" if len(getinfo['username']) < 10 else f"{getinfo["username"][:8]:<8}+", f"{getinfo["memory_percent"]:>4.1f}" if getinfo['memory_percent'] < 100 else f"{getinfo["memory_percent"]:>4.0f} ", f"{cpu:>11.1f} " if cpu < 100 else f"{cpu:>11.0f} ", sep='') elif cont: print(f"{"":>14}{"0.0":>4}{"0.0":>11} ", sep='') tree_line_count += 1 if parent not in tree: return children = tree[parent][:-1] for child in children: create_tree(child, tree, indent + " │ ", indent + " ├─ ", found=found) if max_lines and tree_line_count >= max_lines: break child = tree[parent][-1] create_tree(child, tree, indent + " ", indent + " └─ ") infolist: Dict = {} tree: List = defaultdict(list) for p in sorted(psutil.process_iter(['pid', 'name', 'num_threads', 'username', 'memory_percent', 'cpu_percent', 'cpu_times', 'create_time'], err), key=lambda p: eval(sorting), reverse=reverse): try: tree[p.ppid()].append(p.pid) except (psutil.NoSuchProcess, psutil.ZombieProcess): pass else: infolist[p.pid] = p.info if 0 in tree and 0 in tree[0]: tree[0].remove(0) tree_width: int = width + 8 print(f"{" Tree:":<{tree_width-4}}", 'Threads: ', f"{"User:":<9}Mem%{"Cpu%":>11}", sep='') create_tree(min(tree), tree) def get_disks(exclude: str = None, filtering: str = None): '''Get stats, current read and current write for all disks''' global disk_hist disk_read: int = 0 disk_write: int = 0 dev_name: str disk_name: str disk_list: List[str] = [] excludes: List[str] = [] if exclude: excludes = exclude.split(' ') if system == "BSD": excludes += ["devfs", "tmpfs", "procfs", "linprocfs", "gvfs", "fusefs"] if filtering: filtering: Tuple[str] = tuple(filtering.split(' ')) io_counters = psutil.disk_io_counters(perdisk=True if system == "Linux" else False, nowrap=True) print("Ignored line") for disk in psutil.disk_partitions(): disk_io = None disk_name = disk.mountpoint.rsplit('/', 1)[-1] if not disk.mountpoint == "/" else "root" while disk_name in disk_list: disk_name += "_" disk_list += [disk_name] if excludes and disk.fstype in excludes or filtering and not disk_name.endswith(filtering): continue if system == "MacOS" and disk.mountpoint == "/private/var/vm": continue try: disk_u = psutil.disk_usage(disk.mountpoint) except: pass print(f'{disk.device} {disk_u.total >> 10} {disk_u.used >> 10} {disk_u.free >> 10} {disk_u.percent:.0f} ', end='') try: if system == "Linux": dev_name = os.path.realpath(disk.device).rsplit('/', 1)[-1] if dev_name.startswith("md"): try: dev_name = dev_name[:dev_name.index("p")] except: pass disk_io = io_counters[dev_name] elif disk.mountpoint == "/": disk_io = io_counters else: raise Exception disk_read = disk_io.read_bytes disk_write = disk_io.write_bytes disk_read -= disk_hist[disk.device][0] disk_write -= disk_hist[disk.device][1] except: pass disk_read = 0 disk_write = 0 if disk_io: disk_hist[disk.device] = (disk_io.read_bytes, disk_io.write_bytes) print(f'{disk_read >> 10} {disk_write >> 10} {disk_name}') #* The script takes input over coproc pipes and runs command if in the accepted commands list while command != 'quit': if not psutil.pid_exists(parent_pid): quit() try: command = input() except: pass quit() if not command or command == 'test': continue elif command.startswith(allowed_commands): try: exec(command) except Exception as e: pass print() print('/ERROR') print(f'PSUTIL ERROR! Command: {command}\n{e}', file=sys.stderr) else: continue print('/EOL') #print(f'{command}', file=sys.stderr)
#!/usr/bin/env python3 '''This is a copy of the python script that bashtop starts in a coprocess when using psutil for data collection''' import os, sys, subprocess, re, time, psutil from datetime import timedelta from collections import defaultdict from typing import List, Set, Dict, Tuple, Optional, Union system: str if "linux" in sys.platform: system = "Linux" elif "bsd" in sys.platform: system = "BSD" elif "darwin" in sys.platform: system = "MacOS" else: system = "Other" parent_pid: int = psutil.Process(os.getpid()).ppid() allowed_commands: Tuple[str] = ( 'get_proc', 'get_disks', 'get_cpu_name', 'get_cpu_cores', 'get_nics', 'get_cpu_cores', 'get_cpu_usage', 'get_cpu_freq', 'get_uptime', 'get_load_avg', 'get_mem', 'get_detailed_names_cmd', 'get_detailed_mem_time', 'get_net', 'get_cmd_out', 'get_sensors', 'get_sensors_check', 'get_ms' ) command: str = '' cpu_count: int = psutil.cpu_count() disk_hist: Dict = {} def cleaned(string: str) -> str: '''Escape characters not suitable for "echo -e" in bash''' return string.replace("\\", "\\\\").replace("$", "\\$").replace("\n", "\\n").replace("\t", "\\t").replace("\"", "\\\"").replace("\'", "\\\'") def get_cmd_out(cmd: str): '''Save bash the trouble of creating child processes by running through python instead''' print(subprocess.check_output(cmd, shell=True, universal_newlines=True).rstrip()) def get_ms(): '''Get current epoch millisecond''' t = str(time.time()).split(".") print(f'{t[0]}{t[1][:3]}') def get_sensors(): '''A clone of "sensors" but using psutil''' temps = psutil.sensors_temperatures() if not temps: return try: for name, entries in temps.items(): print(name) for entry in entries: print(f'{entry.label or name}: {entry.current}°C (high = {entry.high}°C, crit = {entry.critical}°C)') print() except: pass def get_sensors_check(): '''Check if get_sensors() output contains accepted CPU temperature values''' if not hasattr(psutil, "sensors_temperatures"): print("false"); return try: temps = psutil.sensors_temperatures() except: pass print("false"); return if not temps: print("false"); return try: for _, entries in temps.items(): for entry in entries: if entry.label.startswith(('Package', 'Core 0', 'Tdie')): print("true") return except: pass print("false") def get_cpu_name(): '''Fetch a suitable CPU identifier from the CPU model name string''' name: str = "" command: str = "" all_info: str = "" rem_line: str = "" if system == "Linux": command = "cat /proc/cpuinfo" rem_line = "model name" elif system == "MacOS": command ="sysctl -n machdep.cpu.brand_string" elif system == "BSD": command ="sysctl hw.model" rem_line = "hw.model" all_info = subprocess.check_output("LANG=C " + command, shell=True, universal_newlines=True) if rem_line: for line in all_info.split("\n"): if rem_line in line: name = re.sub( ".*" + rem_line + ".*:", "", line,1).lstrip() else: name = all_info if "Xeon" in name: name = name.split(" ") name = name[name.index("CPU")+1] elif "Ryzen" in name: name = name.split(" ") name = " ".join(name[name.index("Ryzen"):name.index("Ryzen")+3]) elif "CPU" in name: name = name.split(" ") name = name[name.index("CPU")-1] print(name) def get_cpu_cores(): '''Get number of CPU cores and threads''' cores: int = psutil.cpu_count(logical=False) threads: int = psutil.cpu_count(logical=True) print(f'{cores} {threads if threads else cores}') def get_cpu_usage(): cpu: float = psutil.cpu_percent(percpu=False) threads: List[float] = psutil.cpu_percent(percpu=True) print(f'{cpu:.0f}') for thread in threads: print(f'{thread:.0f}') def get_cpu_freq(): '''Get current CPU frequency''' try: print(f'{psutil.cpu_freq().current:.0f}') except: print(0) def get_uptime(): '''Get current system uptime''' print(str(timedelta(seconds=round(time.time()-psutil.boot_time(),0)))[:-3]) def get_load_avg(): '''Get CPU load average''' for lavg in os.getloadavg(): print(round(lavg, 2), ' ', end='') print() def get_mem(): '''Get current system memory and swap usage''' mem = psutil.virtual_memory() swap = psutil.swap_memory() try: cmem = mem.cached>>10 except: cmem = mem.active>>10 print(mem.total>>10, mem.free>>10, mem.available>>10, cmem, swap.total>>10, swap.free>>10) def get_nics(): '''Get a list of all network devices sorted by highest throughput''' io_all = psutil.net_io_counters(pernic=True) up_stat = psutil.net_if_stats() for nic in sorted(psutil.net_if_addrs(), key=lambda nic: (io_all[nic].bytes_recv + io_all[nic].bytes_sent), reverse=True): if up_stat[nic].isup is False: continue print(nic) def get_net(net_dev: str): '''Emulated /proc/net/dev for selected network device''' net = psutil.net_io_counters(pernic=True)[net_dev] print(0,net.bytes_recv,0,0,0,0,0,0,0,net.bytes_sent) def get_detailed_names_cmd(pid: int): '''Get name, parent name, username and arguments for selected pid''' p = psutil.Process(pid) pa = psutil.Process(p.ppid()) with p.oneshot(): print(p.name()) print(pa.name()) print(p.username()) cmd = ' '.join(p.cmdline()) or '[' + p.name() + ']' print(cleaned(cmd)) def get_detailed_mem_time(pid: int): '''Get memory usage and runtime for selected pid''' p = psutil.Process(pid) with p.oneshot(): print(p.memory_info().rss) print(timedelta(seconds=round(time.time()-p.create_time(),0))) def get_proc(sorting='cpu lazy', tree=False, prog_len=0, arg_len=0, search='', reverse=True, proc_per_cpu=True, max_lines=0): '''List all processess with pid, name, arguments, threads, username, memory percent and cpu percent''' line_count: int = 0 err: float = 0.0 reverse = not reverse if sorting == 'pid': sort_cmd = "p.info['pid']" elif sorting == 'program' or tree and sorting == "arguments": sort_cmd = "p.info['name']" reverse = not reverse elif sorting == 'arguments': sort_cmd = "' '.join(str(p.info['cmdline'])) or p.info['name']" reverse = not reverse elif sorting == 'threads': sort_cmd = "str(p.info['num_threads'])" elif sorting == 'user': sort_cmd = "p.info['username']" reverse = not reverse elif sorting == 'memory': sort_cmd = "str(p.info['memory_percent'])" elif sorting == 'cpu responsive': sort_cmd = "p.info['cpu_percent']" if proc_per_cpu else "(p.info['cpu_percent'] / cpu_count)" else: sort_cmd = "(sum(p.info['cpu_times'][:2] if not p.info['cpu_times'] == 0.0 else [0.0, 0.0]) * 1000 / (time.time() - p.info['create_time']))" if tree: proc_tree(width=prog_len + arg_len, sorting=sort_cmd, reverse=reverse, max_lines=max_lines, proc_per_cpu=proc_per_cpu, search=search) return print(f"{'Pid:':>7} {'Program:':<{prog_len}}", f"{'Arguments:':<{arg_len-4}}" if arg_len else '', f"{'Threads:' if arg_len else ' Tr:'} {'User:':<9}Mem%{'Cpu%':>11}", sep='') for p in sorted(psutil.process_iter(['pid', 'name', 'cmdline', 'num_threads', 'username', 'memory_percent', 'cpu_percent', 'cpu_times', 'create_time'], err), key=lambda p: eval(sort_cmd), reverse=reverse): if p.info['name'] == 'idle' or p.info['name'] == err or p.info['pid'] == err: continue if p.info['cmdline'] == err: p.info['cmdline'] = "" if p.info['username'] == err: p.info['username'] = "?" if p.info['num_threads'] == err: p.info['num_threads'] = 0 if search: found = False for value in [ p.info['name'], ' '.join(p.info['cmdline']), str(p.info['pid']), p.info['username'] ]: if search in value: found = True break if not found: continue cpu = p.info['cpu_percent'] if proc_per_cpu else (p.info['cpu_percent'] / psutil.cpu_count()) mem = p.info['memory_percent'] cmd = ' '.join(p.info['cmdline']) or '[' + p.info['name'] + ']' print(f"{p.info['pid']:>7} ", f"{cleaned(p.info['name']):<{prog_len}.{prog_len-1}}", f"{cleaned(cmd):<{arg_len}.{arg_len-1}}" if arg_len else '', f"{p.info['num_threads']:>4} " if p.info['num_threads'] < 1000 else '999> ', f"{p.info['username']:<9.9}" if len(p.info['username']) < 10 else f"{p.info['username'][:8]:<8}+", f"{mem:>4.1f}" if mem < 100 else f"{mem:>4.0f} ", f"{cpu:>11.1f} " if cpu < 100 else f"{cpu:>11.0f} ", sep='') line_count += 1 if max_lines and line_count == max_lines: break def proc_tree(width: int, sorting: str = 'cpu lazy', reverse: bool = True, max_lines: int = 0, proc_per_cpu=True, search=''): '''List all processess in a tree view with pid, name, threads, username, memory percent and cpu percent''' tree_line_count: int = 0 err: float = 0.0 def create_tree(parent: int, tree, indent: str = '', inindent: str = ' ', found: bool = False): nonlocal infolist, tree_line_count, max_lines, tree_width, proc_per_cpu, search cont: bool = True if max_lines and tree_line_count >= max_lines: return try: name: str = psutil.Process(parent).name() if name == "idle": return except psutil.Error: pass name: str = '' try: getinfo: Dict = infolist[parent] except: pass getinfo: bool = False if search and not found: for value in [ name, str(parent), getinfo['username'] if getinfo else '' ]: if search in value: found = True break if not found: cont = False if cont: print(f"{f'{inindent}{parent} {cleaned(name)}':<{tree_width}.{tree_width-1}}", sep='', end='') if getinfo and cont: if getinfo['cpu_times'] == err: getinfo['num_threads'] = 0 if p.info['username'] == err: p.info['username'] = "?" cpu = getinfo['cpu_percent'] if proc_per_cpu else (getinfo['cpu_percent'] / psutil.cpu_count()) print(f"{getinfo['num_threads']:>4} " if getinfo['num_threads'] < 1000 else '999> ', f"{getinfo['username']:<9.9}" if len(getinfo['username']) < 10 else f"{getinfo['username'][:8]:<8}+", f"{getinfo['memory_percent']:>4.1f}" if getinfo['memory_percent'] < 100 else f"{getinfo['memory_percent']:>4.0f} ", f"{cpu:>11.1f} " if cpu < 100 else f"{cpu:>11.0f} ", sep='') elif cont: print(f"{'':>14}{'0.0':>4}{'0.0':>11} ", sep='') tree_line_count += 1 if parent not in tree: return children = tree[parent][:-1] for child in children: create_tree(child, tree, indent + " │ ", indent + " ├─ ", found=found) if max_lines and tree_line_count >= max_lines: break child = tree[parent][-1] create_tree(child, tree, indent + " ", indent + " └─ ") infolist: Dict = {} tree: List = defaultdict(list) for p in sorted(psutil.process_iter(['pid', 'name', 'num_threads', 'username', 'memory_percent', 'cpu_percent', 'cpu_times', 'create_time'], err), key=lambda p: eval(sorting), reverse=reverse): try: tree[p.ppid()].append(p.pid) except (psutil.NoSuchProcess, psutil.ZombieProcess): pass else: infolist[p.pid] = p.info if 0 in tree and 0 in tree[0]: tree[0].remove(0) tree_width: int = width + 8 print(f"{' Tree:':<{tree_width-4}}", 'Threads: ', f"{'User:':<9}Mem%{'Cpu%':>11}", sep='') create_tree(min(tree), tree) def get_disks(exclude: str = None, filtering: str = None): '''Get stats, current read and current write for all disks''' global disk_hist disk_read: int = 0 disk_write: int = 0 dev_name: str disk_name: str disk_list: List[str] = [] excludes: List[str] = [] if exclude: excludes = exclude.split(' ') if system == "BSD": excludes += ["devfs", "tmpfs", "procfs", "linprocfs", "gvfs", "fusefs"] if filtering: filtering: Tuple[str] = tuple(filtering.split(' ')) io_counters = psutil.disk_io_counters(perdisk=True if system == "Linux" else False, nowrap=True) print("Ignored line") for disk in psutil.disk_partitions(): disk_io = None disk_name = disk.mountpoint.rsplit('/', 1)[-1] if not disk.mountpoint == "/" else "root" while disk_name in disk_list: disk_name += "_" disk_list += [disk_name] if excludes and disk.fstype in excludes or filtering and not disk_name.endswith(filtering): continue if system == "MacOS" and disk.mountpoint == "/private/var/vm": continue try: disk_u = psutil.disk_usage(disk.mountpoint) except: pass print(f'{disk.device} {disk_u.total >> 10} {disk_u.used >> 10} {disk_u.free >> 10} {disk_u.percent:.0f} ', end='') try: if system == "Linux": dev_name = os.path.realpath(disk.device).rsplit('/', 1)[-1] if dev_name.startswith("md"): try: dev_name = dev_name[:dev_name.index("p")] except: pass disk_io = io_counters[dev_name] elif disk.mountpoint == "/": disk_io = io_counters else: raise Exception disk_read = disk_io.read_bytes disk_write = disk_io.write_bytes disk_read -= disk_hist[disk.device][0] disk_write -= disk_hist[disk.device][1] except: pass disk_read = 0 disk_write = 0 if disk_io: disk_hist[disk.device] = (disk_io.read_bytes, disk_io.write_bytes) print(f'{disk_read >> 10} {disk_write >> 10} {disk_name}') #* The script takes input over coproc pipes and runs command if in the accepted commands list while command != 'quit': if not psutil.pid_exists(parent_pid): quit() try: command = input() except: pass quit() if not command or command == 'test': continue elif command.startswith(allowed_commands): try: exec(command) except Exception as e: pass print() print('/ERROR') print(f'PSUTIL ERROR! Command: {command}\n{e}', file=sys.stderr) else: continue print('/EOL') #print(f'{command}', file=sys.stderr)
# Copyright (c) 2018-2020, NVIDIA CORPORATION. from __future__ import division import inspect import itertools import numbers import pickle import sys import warnings from collections import OrderedDict, defaultdict from collections.abc import Iterable, Mapping, Sequence import cupy import numpy as np import pandas as pd import pyarrow as pa from numba import cuda from nvtx import annotate from pandas._config import get_option from pandas.api.types import is_dict_like from pandas.io.formats import console from pandas.io.formats.printing import pprint_thing import cudf from cudf import _lib as libcudf from cudf._lib.null_mask import MaskState, create_null_mask from cudf.core import column, reshape from cudf.core.abc import Serializable from cudf.core.column import as_column, column_empty from cudf.core.column_accessor import ColumnAccessor from cudf.core.frame import Frame from cudf.core.groupby.groupby import DataFrameGroupBy from cudf.core.index import Index, RangeIndex, as_index from cudf.core.indexing import _DataFrameIlocIndexer, _DataFrameLocIndexer from cudf.core.series import Series from cudf.core.window import Rolling from cudf.utils import applyutils, docutils, ioutils, queryutils, utils from cudf.utils.docutils import copy_docstring from cudf.utils.dtypes import ( cudf_dtype_from_pydata_dtype, find_common_type, is_categorical_dtype, is_column_like, is_datetime_dtype, is_list_dtype, is_list_like, is_scalar, is_string_dtype, is_struct_dtype, numeric_normalize_types, ) from cudf.utils.utils import OrderedColumnDict def _unique_name(existing_names, suffix="_unique_name"): ret = suffix i = 1 while ret in existing_names: ret = "%s_%d" % (suffix, i) i += 1 return ret def _reverse_op(fn): return { "add": "radd", "radd": "add", "sub": "rsub", "rsub": "sub", "mul": "rmul", "rmul": "mul", "mod": "rmod", "rmod": "mod", "pow": "rpow", "rpow": "pow", "floordiv": "rfloordiv", "rfloordiv": "floordiv", "truediv": "rtruediv", "rtruediv": "truediv", "__add__": "__radd__", "__radd__": "__add__", "__sub__": "__rsub__", "__rsub__": "__sub__", "__mul__": "__rmul__", "__rmul__": "__mul__", "__mod__": "__rmod__", "__rmod__": "__mod__", "__pow__": "__rpow__", "__rpow__": "__pow__", "__floordiv__": "__rfloordiv__", "__rfloordiv__": "__floordiv__", "__truediv__": "__rtruediv__", "__rtruediv__": "__truediv__", }[fn] _cupy_nan_methods_map = { "min": "nanmin", "max": "nanmax", "sum": "nansum", "prod": "nanprod", "mean": "nanmean", "std": "nanstd", "var": "nanvar", } class DataFrame(Frame, Serializable): _internal_names = {"_data", "_index"} @annotate("DATAFRAME_INIT", color="blue", domain="cudf_python") def __init__(self, data=None, index=None, columns=None, dtype=None): """ A GPU Dataframe object. Parameters ---------- data : array-like, Iterable, dict, or DataFrame. Dict can contain Series, arrays, constants, or list-like objects. index : Index or array-like Index to use for resulting frame. Will default to RangeIndex if no indexing information part of input data and no index provided. columns : Index or array-like Column labels to use for resulting frame. Will default to RangeIndex (0, 1, 2, …, n) if no column labels are provided. dtype : dtype, default None Data type to force. Only a single dtype is allowed. If None, infer. Examples -------- Build dataframe with ``__setitem__``: >>> import cudf >>> df = cudf.DataFrame() >>> df['key'] = [0, 1, 2, 3, 4] >>> df['val'] = [float(i + 10) for i in range(5)] # insert column >>> df key val 0 0 10.0 1 1 11.0 2 2 12.0 3 3 13.0 4 4 14.0 Build DataFrame via dict of columns: >>> import numpy as np >>> from datetime import datetime, timedelta >>> t0 = datetime.strptime('2018-10-07 12:00:00', '%Y-%m-%d %H:%M:%S') >>> n = 5 >>> df = cudf.DataFrame({ ... 'id': np.arange(n), ... 'datetimes': np.array( ... [(t0+ timedelta(seconds=x)) for x in range(n)]) ... }) >>> df id datetimes 0 0 2018-10-07T12:00:00.000 1 1 2018-10-07T12:00:01.000 2 2 2018-10-07T12:00:02.000 3 3 2018-10-07T12:00:03.000 4 4 2018-10-07T12:00:04.000 Build DataFrame via list of rows as tuples: >>> df = cudf.DataFrame([ ... (5, "cats", "jump", np.nan), ... (2, "dogs", "dig", 7.5), ... (3, "cows", "moo", -2.1, "occasionally"), ... ]) >>> df 0 1 2 3 4 0 5 cats jump <NA> <NA> 1 2 dogs dig 7.5 <NA> 2 3 cows moo -2.1 occasionally Convert from a Pandas DataFrame: >>> import pandas as pd >>> pdf = pd.DataFrame({'a': [0, 1, 2, 3],'b': [0.1, 0.2, None, 0.3]}) >>> pdf a b 0 0 0.1 1 1 0.2 2 2 NaN 3 3 0.3 >>> df = cudf.from_pandas(pdf) >>> df a b 0 0 0.1 1 1 0.2 2 2 <NA> 3 3 0.3 """ super().__init__() if isinstance(columns, (Series, cudf.Index)): columns = columns.to_pandas() if isinstance(data, ColumnAccessor): if index is None: index = as_index(range(data.nrows)) else: index = as_index(index) self._index = index if columns is not None: self._data = data self._reindex(columns=columns, deep=True, inplace=True) else: self._data = data elif isinstance(data, (DataFrame, pd.DataFrame)): if isinstance(data, pd.DataFrame): data = self.from_pandas(data) if index is not None: if not data.index.equals(index): data = data.reindex(index) index = data._index else: index = as_index(index) else: index = data._index self._index = index if columns is not None: self._data = data._data self._reindex( columns=columns, index=index, deep=False, inplace=True ) else: self._data = data._data self.columns = data.columns elif data is None: if index is None: self._index = RangeIndex(0) else: self._index = as_index(index) if columns is not None: self._data = ColumnAccessor( OrderedDict.fromkeys( columns, column.column_empty( len(self), dtype="object", masked=True ), ) ) elif hasattr(data, "__cuda_array_interface__"): arr_interface = data.__cuda_array_interface__ # descr is an optional field of the _cuda_ary_iface_ if "descr" in arr_interface: if len(arr_interface["descr"]) == 1: new_df = self._from_arrays( data, index=index, columns=columns ) else: new_df = self.from_records( data, index=index, columns=columns ) else: new_df = self._from_arrays(data, index=index, columns=columns) self._data = new_df._data self.index = new_df._index self.columns = new_df.columns elif hasattr(data, "__array_interface__"): arr_interface = data.__array_interface__ if len(arr_interface["descr"]) == 1: # not record arrays new_df = self._from_arrays(data, index=index, columns=columns) else: new_df = self.from_records(data, index=index, columns=columns) self._data = new_df._data self.index = new_df._index self.columns = new_df.columns else: if is_list_like(data): if len(data) > 0 and is_scalar(data[0]): new_df = self._from_columns( [data], index=index, columns=columns ) self._data = new_df._data self.index = new_df._index self.columns = new_df.columns elif len(data) > 0 and isinstance(data[0], Series): self._init_from_series_list( data=data, columns=columns, index=index ) else: self._init_from_list_like( data, index=index, columns=columns ) else: if not is_dict_like(data): raise TypeError("data must be list or dict-like") self._init_from_dict_like(data, index=index, columns=columns) if dtype: self._data = self.astype(dtype)._data def _init_from_series_list(self, data, columns, index): if index is None: # When `index` is `None`, the final index of # resulting dataframe will be union of # all Series's names. final_index = as_index(_get_union_of_series_names(data)) else: # When an `index` is passed, the final index of # resulting dataframe will be whatever # index passed, but will need # shape validations - explained below data_length = len(data) index_length = len(index) if data_length != index_length: # If the passed `index` length doesn't match # length of Series objects in `data`, we must # check if `data` can be duplicated/expanded # to match the length of index. For that we # check if the length of index is a factor # of length of data. # # 1. If yes, we extend data # until length of data is equal to length of index. # 2. If no, we throw an error stating the # shape of resulting `data` and `index` # Simple example # >>> import pandas as pd # >>> s = pd.Series([1, 2, 3]) # >>> pd.DataFrame([s], index=['a', 'b']) # 0 1 2 # a 1 2 3 # b 1 2 3 # >>> pd.DataFrame([s], index=['a', 'b', 'c']) # 0 1 2 # a 1 2 3 # b 1 2 3 # c 1 2 3 if index_length % data_length == 0: initial_data = data data = [] for _ in range(int(index_length / data_length)): data.extend([o for o in initial_data]) else: raise ValueError( f"Shape of passed values is " f"{(data_length, len(data[0]))}, " f"indices imply {(index_length, len(data[0]))}" ) final_index = as_index(index) series_lengths = list(map(lambda x: len(x), data)) data = numeric_normalize_types(*data) if series_lengths.count(series_lengths[0]) == len(series_lengths): # Calculating the final dataframe columns by # getting union of all `index` of the Series objects. final_columns = _get_union_of_indices([d.index for d in data]) for idx, series in enumerate(data): if not series.index.is_unique: raise ValueError( "Reindexing only valid with uniquely valued Index " "objects" ) if not series.index.equals(final_columns): series = series.reindex(final_columns) self._data[idx] = column.as_column(series._column) # Setting `final_columns` to self._index so # that the resulting `transpose` will be have # columns set to `final_columns` self._index = final_columns transpose = self.T else: concat_df = cudf.concat(data, axis=1) if concat_df.columns.dtype == "object": concat_df.columns = concat_df.columns.astype("str") transpose = concat_df.T transpose._index = final_index self._data = transpose._data self._index = transpose._index # If `columns` is passed, the result dataframe # contain a dataframe with only the # specified `columns` in the same order. if columns: for col_name in columns: if col_name not in self._data: self._data[col_name] = column.column_empty( row_count=len(self), dtype=None, masked=True ) self._data = self._data.select_by_label(columns) def _init_from_list_like(self, data, index=None, columns=None): if index is None: index = RangeIndex(start=0, stop=len(data)) else: index = as_index(index) self._index = as_index(index) # list-of-dicts case if len(data) > 0 and isinstance(data[0], dict): data = DataFrame.from_pandas(pd.DataFrame(data)) self._data = data._data else: data = list(itertools.zip_longest(*data)) if columns is not None and len(data) == 0: data = [ cudf.core.column.column_empty(row_count=0, dtype=None) for _ in columns ] for col_name, col in enumerate(data): self._data[col_name] = column.as_column(col) if columns: self.columns = columns def _init_from_dict_like(self, data, index=None, columns=None): data = data.copy() num_rows = 0 if columns is not None: # remove all entries in `data` that are # not in `columns` keys = [key for key in data.keys() if key in columns] data = {key: data[key] for key in keys} extra_cols = [col for col in columns if col not in data.keys()] if keys: # if keys is non-empty, # add null columns for all values # in `columns` that don't exist in `keys`: data.update({key: None for key in extra_cols}) else: # if keys is empty, # it means that none of the actual keys in `data` # matches with `columns`. # Hence only assign `data` with `columns` as keys # and their values as empty columns. data = { key: cudf.core.column.column_empty(row_count=0, dtype=None) for key in extra_cols } data, index = self._align_input_series_indices(data, index=index) if index is None: if data: col_name = next(iter(data)) if is_scalar(data[col_name]): num_rows = num_rows or 1 else: data[col_name] = column.as_column(data[col_name]) num_rows = len(data[col_name]) self._index = RangeIndex(0, num_rows) else: self._index = as_index(index) if len(data): self._data.multiindex = True for (i, col_name) in enumerate(data): self._data.multiindex = self._data.multiindex and isinstance( col_name, tuple ) self.insert(i, col_name, data[col_name]) if columns is not None: self.columns = columns @classmethod def _from_table(cls, table, index=None): if index is None: if table._index is not None: index = Index._from_table(table._index) else: index = RangeIndex(table._num_rows) out = cls.__new__(cls) out._data = table._data out._index = index return out @staticmethod def _align_input_series_indices(data, index): data = data.copy() input_series = [ Series(val) for val in data.values() if isinstance(val, (pd.Series, Series)) ] if input_series: if index is not None: aligned_input_series = [ sr._align_to_index(index, how="right", sort=False) for sr in input_series ] else: aligned_input_series = cudf.core.series._align_indices( input_series ) index = aligned_input_series[0].index for name, val in data.items(): if isinstance(val, (pd.Series, Series)): data[name] = aligned_input_series.pop(0) return data, index @property def _constructor(self): return DataFrame @property def _constructor_sliced(self): return Series @property def _constructor_expanddim(self): raise NotImplementedError( "_constructor_expanddim not supported for DataFrames!" ) def serialize(self): header = {} frames = [] header["type-serialized"] = pickle.dumps(type(self)) header["index"], index_frames = self._index.serialize() header["index_frame_count"] = len(index_frames) frames.extend(index_frames) # Use the column directly to avoid duplicating the index # need to pickle column names to handle numpy integer columns header["column_names"] = pickle.dumps(tuple(self._data.names)) column_header, column_frames = column.serialize_columns(self._columns) header["columns"] = column_header frames.extend(column_frames) return header, frames @classmethod def deserialize(cls, header, frames): # Reconstruct the index index_frames = frames[: header["index_frame_count"]] idx_typ = pickle.loads(header["index"]["type-serialized"]) index = idx_typ.deserialize(header["index"], index_frames) # Reconstruct the columns column_frames = frames[header["index_frame_count"] :] column_names = pickle.loads(header["column_names"]) columns = column.deserialize_columns(header["columns"], column_frames) return cls(dict(zip(column_names, columns)), index=index) @property def dtypes(self): """Return the dtypes in this object.""" return pd.Series( [x.dtype for x in self._data.columns], index=self._data.names ) @property def shape(self): """Returns a tuple representing the dimensionality of the DataFrame. """ return self._num_rows, self._num_columns @property def ndim(self): """Dimension of the data. DataFrame ndim is always 2. """ return 2 def __dir__(self): o = set(dir(type(self))) o.update(self.__dict__) o.update( c for c in self.columns if isinstance(c, str) and c.isidentifier() ) return list(o) def __setattr__(self, key, col): # if an attribute already exists, set it. try: object.__getattribute__(self, key) object.__setattr__(self, key, col) return except AttributeError: pass # if a column already exists, set it. if key not in self._internal_names: try: self[key] # __getitem__ to verify key exists self[key] = col return except KeyError: pass object.__setattr__(self, key, col) def __getattr__(self, key): if key in self._internal_names: return object.__getattribute__(self, key) else: if key in self: return self[key] raise AttributeError("'DataFrame' object has no attribute %r" % key) @annotate("DATAFRAME_GETITEM", color="blue", domain="cudf_python") def __getitem__(self, arg): """ If *arg* is a ``str`` or ``int`` type, return the column Series. If *arg* is a ``slice``, return a new DataFrame with all columns sliced to the specified range. If *arg* is an ``array`` containing column names, return a new DataFrame with the corresponding columns. If *arg* is a ``dtype.bool array``, return the rows marked True Examples -------- >>> df = DataFrame([('a', list(range(20))), ... ('b', list(range(20))), ... ('c', list(range(20)))]) >>> df[:4] # get first 4 rows of all columns a b c 0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 >>> df[-5:] # get last 5 rows of all columns a b c 15 15 15 15 16 16 16 16 17 17 17 17 18 18 18 18 19 19 19 19 >>> df[['a', 'c']] # get columns a and c a c 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 8 8 8 9 9 9 >>> df[[True, False, True, False]] # mask the entire dataframe, # returning the rows specified in the boolean mask """ if is_scalar(arg) or isinstance(arg, tuple): return self._get_columns_by_label(arg, downcast=True) elif isinstance(arg, slice): return self._slice(arg) elif isinstance( arg, ( list, cupy.ndarray, np.ndarray, pd.Series, Series, Index, pd.Index, ), ): mask = arg if isinstance(mask, list): mask = pd.Series(mask) if mask.dtype == "bool": return self._apply_boolean_mask(mask) else: return self._get_columns_by_label(mask) elif isinstance(arg, DataFrame): return self.where(arg) else: raise TypeError( f"__getitem__ on type {type(arg)} is not supported" ) @annotate("DATAFRAME_SETITEM", color="blue", domain="cudf_python") def __setitem__(self, arg, value): """Add/set column by *arg or DataFrame* """ if isinstance(arg, DataFrame): # not handling set_item where arg = df & value = df if isinstance(value, DataFrame): raise TypeError( f"__setitem__ with arg = {type(value)} and " f"value = {type(arg)} is not supported" ) else: for col_name in self._data: scatter_map = arg[col_name] if is_scalar(value): self._data[col_name][scatter_map] = value else: self._data[col_name][scatter_map] = column.as_column( value )[scatter_map] elif is_scalar(arg) or isinstance(arg, tuple): if isinstance(value, DataFrame): _setitem_with_dataframe( input_df=self, replace_df=value, input_cols=[arg], mask=None, ) else: if arg in self._data: if len(self) == 0: if isinstance(value, (pd.Series, Series)): self._index = as_index(value.index) elif len(value) > 0: self._index = RangeIndex(start=0, stop=len(value)) value = column.as_column(value) new_data = self._data.__class__() for key in self._data: if key == arg: new_data[key] = value else: new_data[key] = column.column_empty_like( self._data[key], masked=True, newsize=len(value), ) self._data = new_data return elif isinstance(value, (pd.Series, Series)): value = Series(value)._align_to_index( self._index, how="right", sort=False, allow_non_unique=True, ) if is_scalar(value): self._data[arg][:] = value else: value = as_column(value) self._data[arg] = value else: # disc. with pandas here # pandas raises key error here self.insert(len(self._data), arg, value) elif isinstance( arg, (list, np.ndarray, pd.Series, Series, Index, pd.Index) ): mask = arg if isinstance(mask, list): mask = np.array(mask) if mask.dtype == "bool": mask = column.as_column(arg) if isinstance(value, DataFrame): _setitem_with_dataframe( input_df=self, replace_df=value, input_cols=None, mask=mask, ) else: if not is_scalar(value): value = column.as_column(value)[mask] for col_name in self._data: self._data[col_name][mask] = value else: if isinstance(value, DataFrame): _setitem_with_dataframe( input_df=self, replace_df=value, input_cols=arg, mask=None, ) else: for col in arg: if is_scalar(value): self._data[col] = column.full( size=len(self), fill_value=value ) else: self._data[col] = column.as_column(value) else: raise TypeError( f"__setitem__ on type {type(arg)} is not supported" ) def __delitem__(self, name): """ Drop the given column by *name*. """ self._drop_column(name) def __sizeof__(self): columns = sum(col.__sizeof__() for col in self._data.columns) index = self._index.__sizeof__() return columns + index def memory_usage(self, index=True, deep=False): """ Return the memory usage of each column in bytes. The memory usage can optionally include the contribution of the index and elements of `object` dtype. Parameters ---------- index : bool, default True Specifies whether to include the memory usage of the DataFrame's index in returned Series. If ``index=True``, the memory usage of the index is the first item in the output. deep : bool, default False If True, introspect the data deeply by interrogating `object` dtypes for system-level memory consumption, and include it in the returned values. Returns ------- Series A Series whose index is the original column names and whose values is the memory usage of each column in bytes. Examples -------- >>> dtypes = ['int64', 'float64', 'object', 'bool'] >>> data = dict([(t, np.ones(shape=5000).astype(t)) ... for t in dtypes]) >>> df = cudf.DataFrame(data) >>> df.head() int64 float64 object bool 0 1 1.0 1.0 True 1 1 1.0 1.0 True 2 1 1.0 1.0 True 3 1 1.0 1.0 True 4 1 1.0 1.0 True >>> df.memory_usage(index=False) int64 40000 float64 40000 object 40000 bool 5000 dtype: int64 Use a Categorical for efficient storage of an object-dtype column with many repeated values. >>> df['object'].astype('category').memory_usage(deep=True) 5048 """ ind = list(self.columns) sizes = [col._memory_usage(deep=deep) for col in self._data.columns] if index: ind.append("Index") ind = cudf.Index(ind, dtype="str") sizes.append(self.index.memory_usage(deep=deep)) return Series(sizes, index=ind) def __len__(self): """ Returns the number of rows """ return len(self.index) def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): import cudf if method == "__call__" and hasattr(cudf, ufunc.__name__): func = getattr(cudf, ufunc.__name__) return func(self) else: return NotImplemented def __array_function__(self, func, types, args, kwargs): cudf_df_module = DataFrame cudf_series_module = Series for submodule in func.__module__.split(".")[1:]: # point cudf to the correct submodule if hasattr(cudf_df_module, submodule): cudf_df_module = getattr(cudf_df_module, submodule) else: return NotImplemented fname = func.__name__ handled_types = [cudf_df_module, cudf_series_module] for t in types: if t not in handled_types: return NotImplemented if hasattr(cudf_df_module, fname): cudf_func = getattr(cudf_df_module, fname) # Handle case if cudf_func is same as numpy function if cudf_func is func: return NotImplemented else: return cudf_func(*args, **kwargs) else: return NotImplemented @property def values(self): """ Return a CuPy representation of the DataFrame. Only the values in the DataFrame will be returned, the axes labels will be removed. Returns ------- out: cupy.ndarray The values of the DataFrame. """ return cupy.asarray(self.as_gpu_matrix()) def __array__(self, dtype=None): raise TypeError( "Implicit conversion to a host NumPy array via __array__ is not " "allowed, To explicitly construct a GPU matrix, consider using " ".as_gpu_matrix()\nTo explicitly construct a host " "matrix, consider using .as_matrix()" ) def __arrow_array__(self, type=None): raise TypeError( "Implicit conversion to a host PyArrow Table via __arrow_array__ " "is not allowed, To explicitly construct a PyArrow Table, " "consider using .to_arrow()" ) def _get_numeric_data(self): """ Return a dataframe with only numeric data types """ columns = [ c for c, dt in self.dtypes.items() if dt != object and not is_categorical_dtype(dt) ] return self[columns] def assign(self, **kwargs): """ Assign columns to DataFrame from keyword arguments. Examples -------- >>> import cudf >>> df = cudf.DataFrame() >>> df = df.assign(a=[0, 1, 2], b=[3, 4, 5]) >>> df a b 0 0 3 1 1 4 2 2 5 """ new = self.copy() for k, v in kwargs.items(): new[k] = v return new def head(self, n=5): """ Returns the first n rows as a new DataFrame Examples -------- >>> import cudf >>> df = cudf.DataFrame() >>> df['key'] = [0, 1, 2, 3, 4] >>> df['val'] = [float(i + 10) for i in range(5)] # insert column >>> df.head(2) key val 0 0 10.0 1 1 11.0 """ return self.iloc[:n] def tail(self, n=5): """ Returns the last n rows as a new DataFrame Examples -------- >>> import cudf >>> df = cudf.DataFrame() >>> df['key'] = [0, 1, 2, 3, 4] >>> df['val'] = [float(i + 10) for i in range(5)] # insert column >>> df.tail(2) key val 3 3 13.0 4 4 14.0 """ if n == 0: return self.iloc[0:0] return self.iloc[-n:] def to_string(self): """ Convert to string cuDF uses Pandas internals for efficient string formatting. Set formatting options using pandas string formatting options and cuDF objects will print identically to Pandas objects. cuDF supports `null/None` as a value in any column type, which is transparently supported during this output process. Examples -------- >>> import cudf >>> df = cudf.DataFrame() >>> df['key'] = [0, 1, 2] >>> df['val'] = [float(i + 10) for i in range(3)] >>> df.to_string() ' key val\\n0 0 10.0\\n1 1 11.0\\n2 2 12.0' """ return self.__repr__() def __str__(self): return self.to_string() def astype(self, dtype, copy=False, errors="raise", **kwargs): """ Cast the DataFrame to the given dtype Parameters ---------- dtype : data type, or dict of column name -> data type Use a numpy.dtype or Python type to cast entire DataFrame object to the same type. Alternatively, use ``{col: dtype, ...}``, where col is a column label and dtype is a numpy.dtype or Python type to cast one or more of the DataFrame's columns to column-specific types. copy : bool, default False Return a deep-copy when ``copy=True``. Note by default ``copy=False`` setting is used and hence changes to values then may propagate to other cudf objects. errors : {'raise', 'ignore', 'warn'}, default 'raise' Control raising of exceptions on invalid data for provided dtype. - ``raise`` : allow exceptions to be raised - ``ignore`` : suppress exceptions. On error return original object. - ``warn`` : prints last exceptions as warnings and return original object. **kwargs : extra arguments to pass on to the constructor Returns ------- casted : DataFrame """ result = DataFrame(index=self.index) if is_dict_like(dtype): current_cols = self._data.names if len(set(dtype.keys()) - set(current_cols)) > 0: raise KeyError( "Only a column name can be used for the " "key in a dtype mappings argument." ) for col_name in current_cols: if col_name in dtype: result._data[col_name] = self._data[col_name].astype( dtype=dtype[col_name], errors=errors, copy=copy, **kwargs, ) else: result._data[col_name] = ( self._data[col_name].copy(deep=True) if copy else self._data[col_name] ) else: for col in self._data: result._data[col] = self._data[col].astype( dtype=dtype, **kwargs ) return result def _repr_pandas025_formatting(self, ncols, nrows, dtype=None): """ With Pandas > 0.25 there are some new conditional formatting for some datatypes and column/row configurations. This fixes most of them in context to match the expected Pandas repr of the same content. Examples -------- >>> gdf.__repr__() 0 ... 19 0 46 ... 48 .. .. ... .. 19 40 ... 29 [20 rows x 20 columns] >>> nrows, ncols = _repr_pandas025_formatting(2, 2, dtype="category") >>> pd.options.display.max_rows = nrows >>> pd.options.display.max_columns = ncols >>> gdf.__repr__() 0 ... 19 0 46 ... 48 .. .. ... .. 19 40 ... 29 [20 rows x 20 columns] """ ncols = 1 if ncols in [0, 2] and dtype == "datetime64[ns]" else ncols ncols = ( 1 if ncols == 0 and nrows == 1 and dtype in ["int8", "str", "category"] else ncols ) ncols = ( 1 if nrows == 1 and dtype in ["int8", "int16", "int64", "str", "category"] else ncols ) ncols = 0 if ncols == 2 else ncols ncols = 19 if ncols in [20, 21] else ncols return ncols, nrows def _clean_renderable_dataframe(self, output): """ This method takes in partial/preprocessed dataframe and returns correct representation of it with correct dimensions (rows x columns) """ max_rows = get_option("display.max_rows") min_rows = get_option("display.min_rows") max_cols = get_option("display.max_columns") max_colwidth = get_option("display.max_colwidth") show_dimensions = get_option("display.show_dimensions") if get_option("display.expand_frame_repr"): width, _ = console.get_console_size() else: width = None output = output.to_pandas().to_string( max_rows=max_rows, min_rows=min_rows, max_cols=max_cols, line_width=width, max_colwidth=max_colwidth, show_dimensions=show_dimensions, ) lines = output.split("\n") if lines[-1].startswith("["): lines = lines[:-1] lines.append( "[%d rows x %d columns]" % (len(self), len(self._data.names)) ) return "\n".join(lines) def _clean_nulls_from_dataframe(self, df): """ This function converts all ``null`` values to ``<NA>`` for representation as a string in `__repr__`. Since we utilize Pandas `__repr__` at all places in our code for formatting purposes, we convert columns to `str` dtype for filling with `<NA>` values. """ for col in df._data: if is_list_dtype(df._data[col]) or is_struct_dtype(df._data[col]): # TODO we need to handle this pass elif df._data[col].has_nulls: df[col] = df._data[col].astype("str").fillna(cudf._NA_REP) else: df[col] = df._data[col] return df def _get_renderable_dataframe(self): """ takes rows and columns from pandas settings or estimation from size. pulls quadrents based off of some known parameters then style for multiindex as well producing an efficient representative string for printing with the dataframe. """ max_rows = pd.options.display.max_rows nrows = np.max([len(self) if max_rows is None else max_rows, 1]) if pd.options.display.max_rows == 0: nrows = len(self) ncols = ( pd.options.display.max_columns if pd.options.display.max_columns else pd.options.display.width / 2 ) if len(self) <= nrows and len(self._data.names) <= ncols: output = self.copy(deep=False) elif self.empty and len(self.index) > 0: max_seq_items = pd.options.display.max_seq_items # Incase of Empty DataFrame with index, Pandas prints # first `pd.options.display.max_seq_items` index values # followed by ... To obtain ... at the end of index list, # adding 1 extra value. # If `pd.options.display.max_seq_items` is None, # entire sequence/Index is to be printed. # Note : Pandas truncates the dimensions at the end of # the resulting dataframe when `display.show_dimensions` # is set to truncate. Hence to display the dimensions we # need to extract maximum of `max_seq_items` and `nrows` # and have 1 extra value for ... to show up in the output # string. if max_seq_items is not None: output = self.head(max(max_seq_items, nrows) + 1) else: output = self.copy(deep=False) else: left_cols = len(self._data.names) right_cols = 0 upper_rows = len(self) lower_rows = 0 if len(self) > nrows and nrows > 0: upper_rows = int(nrows / 2.0) + 1 lower_rows = upper_rows + (nrows % 2) if len(self._data.names) > ncols: right_cols = len(self._data.names) - int(ncols / 2.0) # adjust right columns for output if multiindex. right_cols = ( right_cols - 1 if isinstance(self.index, cudf.MultiIndex) else right_cols ) left_cols = int(ncols / 2.0) + 1 if right_cols > 0: # Pick ncols - left_cols number of columns # from the right side/from the end. right_cols = -(int(ncols) - left_cols + 1) else: # If right_cols is 0 or negative, it means # self has lesser number of columns than ncols. # Hence assign len(self._data.names) which # will result in empty `*_right` quadrants. # This is because `*_left` quadrants will # contain all columns. right_cols = len(self._data.names) upper_left = self.head(upper_rows).iloc[:, :left_cols] upper_right = self.head(upper_rows).iloc[:, right_cols:] lower_left = self.tail(lower_rows).iloc[:, :left_cols] lower_right = self.tail(lower_rows).iloc[:, right_cols:] upper = cudf.concat([upper_left, upper_right], axis=1) lower = cudf.concat([lower_left, lower_right], axis=1) output = cudf.concat([upper, lower]) output = self._clean_nulls_from_dataframe(output) output._index = output._index._clean_nulls_from_index() return output def __repr__(self): output = self._get_renderable_dataframe() return self._clean_renderable_dataframe(output) def _repr_html_(self): lines = ( self._get_renderable_dataframe() .to_pandas() ._repr_html_() .split("\n") ) if lines[-2].startswith("<p>"): lines = lines[:-2] lines.append( "<p>%d rows × %d columns</p>" % (len(self), len(self._data.names)) ) lines.append("</div>") return "\n".join(lines) def _repr_latex_(self): return self._get_renderable_dataframe().to_pandas()._repr_latex_() # unary, binary, rbinary, orderedcompare, unorderedcompare def _apply_op(self, fn, other=None, fill_value=None): result = DataFrame(index=self.index) def op(lhs, rhs): if fill_value is None: return getattr(lhs, fn)(rhs) else: return getattr(lhs, fn)(rhs, fill_value) if other is None: for col in self._data: result[col] = getattr(self[col], fn)() return result elif isinstance(other, Sequence): for k, col in enumerate(self._data): result[col] = getattr(self[col], fn)(other[k]) elif isinstance(other, DataFrame): if fn in cudf.utils.utils._EQUALITY_OPS: if not self.index.equals(other.index): raise ValueError( "Can only compare identically-labeled " "DataFrame objects" ) lhs, rhs = _align_indices(self, other) result.index = lhs.index max_num_rows = max(lhs.shape[0], rhs.shape[0]) def fallback(col, fn): if fill_value is None: return Series.from_masked_array( data=column_empty(max_num_rows, dtype="float64"), mask=create_null_mask( max_num_rows, state=MaskState.ALL_NULL ), ).set_index(col.index) else: return getattr(col, fn)(fill_value) for col in lhs._data: if col not in rhs._data: result[col] = fallback(lhs[col], fn) else: result[col] = op(lhs[col], rhs[col]) for col in rhs._data: if col not in lhs._data: result[col] = fallback(rhs[col], _reverse_op(fn)) elif isinstance(other, Series): other_cols = other.to_pandas().to_dict() other_cols_keys = list(other_cols.keys()) result_cols = list(self.columns) df_cols = list(result_cols) for new_col in other_cols.keys(): if new_col not in result_cols: result_cols.append(new_col) for col in result_cols: if col in df_cols and col in other_cols_keys: l_opr = self[col] r_opr = other_cols[col] else: if col not in df_cols: r_opr = other_cols[col] l_opr = Series( column_empty( len(self), masked=True, dtype=other.dtype ) ) if col not in other_cols_keys: r_opr = None l_opr = self[col] result[col] = op(l_opr, r_opr) elif isinstance(other, (numbers.Number, cudf.Scalar)) or ( isinstance(other, np.ndarray) and other.ndim == 0 ): for col in self._data: result[col] = op(self[col], other) else: raise NotImplementedError( "DataFrame operations with " + str(type(other)) + " not " "supported at this time." ) return result def add(self, other, axis="columns", level=None, fill_value=None): """ Get Addition of dataframe and other, element-wise (binary operator `add`). Equivalent to ``dataframe + other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `radd`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> df + 1 angles degrees circle 1 361 triangle 4 181 rectangle 5 361 >>> df.add(1) angles degrees circle 1 361 triangle 4 181 rectangle 5 361 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("add", other, fill_value) def __add__(self, other): return self._apply_op("__add__", other) def radd(self, other, axis=1, level=None, fill_value=None): """ Get Addition of dataframe and other, element-wise (binary operator `radd`). Equivalent to ``other + dataframe``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `add`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> df + 1 angles degrees circle 1 361 triangle 4 181 rectangle 5 361 >>> df.radd(1) angles degrees circle 1 361 triangle 4 181 rectangle 5 361 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("radd", other, fill_value) def __radd__(self, other): return self._apply_op("__radd__", other) def sub(self, other, axis="columns", level=None, fill_value=None): """ Get Subtraction of dataframe and other, element-wise (binary operator `sub`). Equivalent to ``dataframe - other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `rsub`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> df.sub(1) angles degrees circle -1 359 triangle 2 179 rectangle 3 359 >>> df.sub([1, 2]) angles degrees circle -1 358 triangle 2 178 rectangle 3 358 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("sub", other, fill_value) def __sub__(self, other): return self._apply_op("__sub__", other) def rsub(self, other, axis="columns", level=None, fill_value=None): """ Get Subtraction of dataframe and other, element-wise (binary operator `rsub`). Equivalent to ``other - dataframe``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `sub`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> df angles degrees circle 0 360 triangle 3 180 rectangle 4 360 >>> df.rsub(1) angles degrees circle 1 -359 triangle -2 -179 rectangle -3 -359 >>> df.rsub([1, 2]) angles degrees circle 1 -358 triangle -2 -178 rectangle -3 -358 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("rsub", other, fill_value) def __rsub__(self, other): return self._apply_op("__rsub__", other) def mul(self, other, axis="columns", level=None, fill_value=None): """ Get Multiplication of dataframe and other, element-wise (binary operator `mul`). Equivalent to ``dataframe * other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `rmul`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> other = cudf.DataFrame({'angles': [0, 3, 4]}, ... index=['circle', 'triangle', 'rectangle']) >>> df * other angles degrees circle 0 <NA> triangle 9 <NA> rectangle 16 <NA> >>> df.mul(other, fill_value=0) angles degrees circle 0 0 triangle 9 0 rectangle 16 0 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("mul", other, fill_value) def __mul__(self, other): return self._apply_op("__mul__", other) def rmul(self, other, axis="columns", level=None, fill_value=None): """ Get Multiplication of dataframe and other, element-wise (binary operator `rmul`). Equivalent to ``other * dataframe``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `mul`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> other = cudf.DataFrame({'angles': [0, 3, 4]}, ... index=['circle', 'triangle', 'rectangle']) >>> other * df angles degrees circle 0 <NA> triangle 9 <NA> rectangle 16 <NA> >>> df.rmul(other, fill_value=0) angles degrees circle 0 0 triangle 9 0 rectangle 16 0 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("rmul", other, fill_value) def __rmul__(self, other): return self._apply_op("__rmul__", other) def mod(self, other, axis="columns", level=None, fill_value=None): """ Get Modulo division of dataframe and other, element-wise (binary operator `mod`). Equivalent to ``dataframe % other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `rmod`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> df % 100 angles degrees circle 0 60 triangle 3 80 rectangle 4 60 >>> df.mod(100) angles degrees circle 0 60 triangle 3 80 rectangle 4 60 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("mod", other, fill_value) def __mod__(self, other): return self._apply_op("__mod__", other) def rmod(self, other, axis="columns", level=None, fill_value=None): """ Get Modulo division of dataframe and other, element-wise (binary operator `rmod`). Equivalent to ``other % dataframe``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `mod`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [1, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> 100 % df angles degrees circle 0 100 triangle 1 100 rectangle 0 100 >>> df.rmod(100) angles degrees circle 0 100 triangle 1 100 rectangle 0 100 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("rmod", other, fill_value) def __rmod__(self, other): return self._apply_op("__rmod__", other) def pow(self, other, axis="columns", level=None, fill_value=None): """ Get Exponential power of dataframe and other, element-wise (binary operator `pow`). Equivalent to ``dataframe ** other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `rpow`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [1, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> df ** 2 angles degrees circle 0 129600 triangle 9 32400 rectangle 16 129600 >>> df.pow(2) angles degrees circle 0 129600 triangle 9 32400 rectangle 16 129600 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("pow", other, fill_value) def __pow__(self, other): return self._apply_op("__pow__", other) def rpow(self, other, axis="columns", level=None, fill_value=None): """ Get Exponential power of dataframe and other, element-wise (binary operator `pow`). Equivalent to ``other ** dataframe``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `pow`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [1, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> 1 ** df angles degrees circle 1 1 triangle 1 1 rectangle 1 1 >>> df.rpow(1) angles degrees circle 1 1 triangle 1 1 rectangle 1 1 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("rpow", other, fill_value) def __rpow__(self, other): return self._apply_op("__pow__", other) def floordiv(self, other, axis="columns", level=None, fill_value=None): """ Get Integer division of dataframe and other, element-wise (binary operator `floordiv`). Equivalent to ``dataframe // other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `rfloordiv`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [1, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> df.floordiv(2) angles degrees circle 0 180 triangle 1 90 rectangle 2 180 >>> df // 2 angles degrees circle 0 180 triangle 1 90 rectangle 2 180 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("floordiv", other, fill_value) def __floordiv__(self, other): return self._apply_op("__floordiv__", other) def rfloordiv(self, other, axis="columns", level=None, fill_value=None): """ Get Integer division of dataframe and other, element-wise (binary operator `rfloordiv`). Equivalent to ``other // dataframe``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `floordiv`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'col1': [10, 11, 23], ... 'col2': [101, 122, 321]}) >>> df col1 col2 0 10 101 1 11 122 2 23 321 >>> df.rfloordiv(df) col1 col2 0 1 1 1 1 1 2 1 1 >>> df.rfloordiv(200) col1 col2 0 20 1 1 18 1 2 8 0 >>> df.rfloordiv(100) col1 col2 0 10 0 1 9 0 2 4 0 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("rfloordiv", other, fill_value) def __rfloordiv__(self, other): return self._apply_op("__rfloordiv__", other) def truediv(self, other, axis="columns", level=None, fill_value=None): """ Get Floating division of dataframe and other, element-wise (binary operator `truediv`). Equivalent to ``dataframe / other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `rtruediv`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> df.truediv(10) angles degrees circle 0.0 36.0 triangle 0.3 18.0 rectangle 0.4 36.0 >>> df.div(10) angles degrees circle 0.0 36.0 triangle 0.3 18.0 rectangle 0.4 36.0 >>> df / 10 angles degrees circle 0.0 36.0 triangle 0.3 18.0 rectangle 0.4 36.0 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("truediv", other, fill_value) # Alias for truediv div = truediv def __truediv__(self, other): return self._apply_op("__truediv__", other) def rtruediv(self, other, axis="columns", level=None, fill_value=None): """ Get Floating division of dataframe and other, element-wise (binary operator `rtruediv`). Equivalent to ``other / dataframe``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `truediv`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> df angles degrees circle 0 360 triangle 3 180 rectangle 4 360 >>> df.rtruediv(10) angles degrees circle inf 0.027778 triangle 3.333333 0.055556 rectangle 2.500000 0.027778 >>> df.rdiv(10) angles degrees circle inf 0.027778 triangle 3.333333 0.055556 rectangle 2.500000 0.027778 >>> 10 / df angles degrees circle inf 0.027778 triangle 3.333333 0.055556 rectangle 2.500000 0.027778 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("rtruediv", other, fill_value) # Alias for rtruediv rdiv = rtruediv def __rtruediv__(self, other): return self._apply_op("__rtruediv__", other) __div__ = __truediv__ def __and__(self, other): return self._apply_op("__and__", other) def __or__(self, other): return self._apply_op("__or__", other) def __xor__(self, other): return self._apply_op("__xor__", other) def __eq__(self, other): return self._apply_op("__eq__", other) def __ne__(self, other): return self._apply_op("__ne__", other) def __lt__(self, other): return self._apply_op("__lt__", other) def __le__(self, other): return self._apply_op("__le__", other) def __gt__(self, other): return self._apply_op("__gt__", other) def __ge__(self, other): return self._apply_op("__ge__", other) def __invert__(self): return self._apply_op("__invert__") def __neg__(self): return self._apply_op("__neg__") def __abs__(self): return self._apply_op("__abs__") def __iter__(self): return iter(self.columns) def iteritems(self): """ Iterate over column names and series pairs """ for k in self: yield (k, self[k]) @property @annotate("DATAFRAME_LOC", color="blue", domain="cudf_python") def loc(self): """ Selecting rows and columns by label or boolean mask. Examples -------- DataFrame with string index. >>> df a b a 0 5 b 1 6 c 2 7 d 3 8 e 4 9 Select a single row by label. >>> df.loc['a'] a 0 b 5 Name: a, dtype: int64 Select multiple rows and a single column. >>> df.loc[['a', 'c', 'e'], 'b'] a 5 c 7 e 9 Name: b, dtype: int64 Selection by boolean mask. >>> df.loc[df.a > 2] a b d 3 8 e 4 9 Setting values using loc. >>> df.loc[['a', 'c', 'e'], 'a'] = 0 >>> df a b a 0 5 b 1 6 c 0 7 d 3 8 e 0 9 See also -------- DataFrame.iloc Notes ----- One notable difference from Pandas is when DataFrame is of mixed types and result is expected to be a Series in case of Pandas. cuDF will return a DataFrame as it doesn't support mixed types under Series yet. Mixed dtype single row output as a dataframe (pandas results in Series) >>> import cudf >>> df = cudf.DataFrame({"a":[1, 2, 3], "b":["a", "b", "c"]}) >>> df.loc[0] a b 0 1 a """ return _DataFrameLocIndexer(self) @property def iloc(self): """ Selecting rows and column by position. Examples -------- >>> df = cudf.DataFrame({'a': range(20), ... 'b': range(20), ... 'c': range(20)}) Select a single row using an integer index. >>> df.iloc[1] a 1 b 1 c 1 Name: 1, dtype: int64 Select multiple rows using a list of integers. >>> df.iloc[[0, 2, 9, 18]] a b c 0 0 0 0 2 2 2 2 9 9 9 9 18 18 18 18 Select rows using a slice. >>> df.iloc[3:10:2] a b c 3 3 3 3 5 5 5 5 7 7 7 7 9 9 9 9 Select both rows and columns. >>> df.iloc[[1, 3, 5, 7], 2] 1 1 3 3 5 5 7 7 Name: c, dtype: int64 Setting values in a column using iloc. >>> df.iloc[:4] = 0 >>> df a b c 0 0 0 0 1 0 0 0 2 0 0 0 3 0 0 0 4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7 8 8 8 8 9 9 9 9 [10 more rows] See also -------- DataFrame.loc Notes ----- One notable difference from Pandas is when DataFrame is of mixed types and result is expected to be a Series in case of Pandas. cuDF will return a DataFrame as it doesn't support mixed types under Series yet. Mixed dtype single row output as a dataframe (pandas results in Series) >>> import cudf >>> df = cudf.DataFrame({"a":[1, 2, 3], "b":["a", "b", "c"]}) >>> df.iloc[0] a b 0 1 a """ return _DataFrameIlocIndexer(self) @property def iat(self): """ Alias for ``DataFrame.iloc``; provided for compatibility with Pandas. """ return self.iloc @property def at(self): """ Alias for ``DataFrame.loc``; provided for compatibility with Pandas. """ return self.loc @property @annotate("DATAFRAME_COLUMNS_GETTER", color="yellow", domain="cudf_python") def columns(self): """Returns a tuple of columns """ return self._data.to_pandas_index() @columns.setter @annotate("DATAFRAME_COLUMNS_SETTER", color="yellow", domain="cudf_python") def columns(self, columns): if isinstance(columns, (cudf.MultiIndex, cudf.Index)): columns = columns.to_pandas() if columns is None: columns = pd.Index(range(len(self._data.columns))) is_multiindex = isinstance(columns, pd.MultiIndex) if isinstance( columns, (Series, cudf.Index, cudf.core.column.ColumnBase) ): columns = pd.Index(columns.to_array(), tupleize_cols=is_multiindex) elif not isinstance(columns, pd.Index): columns = pd.Index(columns, tupleize_cols=is_multiindex) if not len(columns) == len(self._data.names): raise ValueError( f"Length mismatch: expected {len(self._data.names)} elements ," f"got {len(columns)} elements" ) data = dict(zip(columns, self._data.columns)) if len(columns) != len(data): raise ValueError("Duplicate column names are not allowed") self._data = ColumnAccessor( data, multiindex=is_multiindex, level_names=columns.names, ) def _rename_columns(self, new_names): old_cols = iter(self._data.names) l_old_cols = len(self._data) l_new_cols = len(new_names) if l_new_cols != l_old_cols: msg = ( f"Length of new column names: {l_new_cols} does not " "match length of previous column names: {l_old_cols}" ) raise ValueError(msg) mapper = dict(zip(old_cols, new_names)) self.rename(mapper=mapper, inplace=True, axis=1) @property def index(self): """Returns the index of the DataFrame """ return self._index @index.setter def index(self, value): old_length = ( self._num_rows if self._index is None else len(self._index) ) if isinstance(value, cudf.core.multiindex.MultiIndex): if len(self._data) > 0 and len(value) != old_length: msg = ( f"Length mismatch: Expected axis has {old_length} " f"elements, new values have {len(value)} elements" ) raise ValueError(msg) self._index = value return new_length = len(value) if len(self._data) > 0 and new_length != old_length: msg = ( f"Length mismatch: Expected axis has {old_length} elements, " f"new values have {new_length} elements" ) raise ValueError(msg) # try to build an index from generic _index idx = as_index(value) self._index = idx def reindex( self, labels=None, axis=0, index=None, columns=None, copy=True ): """ Return a new DataFrame whose axes conform to a new index ``DataFrame.reindex`` supports two calling conventions: - ``(index=index_labels, columns=column_names)`` - ``(labels, axis={0 or 'index', 1 or 'columns'})`` Parameters ---------- labels : Index, Series-convertible, optional, default None axis : {0 or 'index', 1 or 'columns'}, optional, default 0 index : Index, Series-convertible, optional, default None Shorthand for ``df.reindex(labels=index_labels, axis=0)`` columns : array-like, optional, default None Shorthand for ``df.reindex(labels=column_names, axis=1)`` copy : boolean, optional, default True Returns ------- A DataFrame whose axes conform to the new index(es) Examples -------- >>> import cudf >>> df = cudf.DataFrame() >>> df['key'] = [0, 1, 2, 3, 4] >>> df['val'] = [float(i + 10) for i in range(5)] >>> df_new = df.reindex(index=[0, 3, 4, 5], ... columns=['key', 'val', 'sum']) >>> df key val 0 0 10.0 1 1 11.0 2 2 12.0 3 3 13.0 4 4 14.0 >>> df_new key val sum 0 0 10.0 NaN 3 3 13.0 NaN 4 4 14.0 NaN 5 -1 NaN NaN """ if labels is None and index is None and columns is None: return self.copy(deep=copy) df = self cols = columns dtypes = OrderedDict(df.dtypes) idx = labels if index is None and axis in (0, "index") else index cols = labels if cols is None and axis in (1, "columns") else cols df = df if cols is None else df[list(set(df.columns) & set(cols))] result = df._reindex( columns=cols, dtypes=dtypes, deep=copy, index=idx, inplace=False ) return result def _set_index( self, index, to_drop=None, inplace=False, verify_integrity=False, ): """Helper for `.set_index` Parameters ---------- index : Index The new index to set. to_drop : list optional, default None A list of labels indicating columns to drop. inplace : boolean, default False Modify the DataFrame in place (do not create a new object). verify_integrity : boolean, default False Check for duplicates in the new index. """ if not isinstance(index, Index): raise ValueError("Parameter index should be type `Index`.") df = self if inplace else self.copy(deep=True) if verify_integrity and not index.is_unique: raise ValueError(f"Values in Index are not unique: {index}") if to_drop: df.drop(columns=to_drop, inplace=True) df.index = index return df if not inplace else None def set_index( self, keys, drop=True, append=False, inplace=False, verify_integrity=False, ): """Return a new DataFrame with a new index Parameters ---------- keys : Index, Series-convertible, label-like, or list Index : the new index. Series-convertible : values for the new index. Label-like : Label of column to be used as index. List : List of items from above. drop : boolean, default True Whether to drop corresponding column for str index argument append : boolean, default True Whether to append columns to the existing index, resulting in a MultiIndex. inplace : boolean, default False Modify the DataFrame in place (do not create a new object). verify_integrity : boolean, default False Check for duplicates in the new index. Examples -------- >>> df = cudf.DataFrame({ ... "a": [1, 2, 3, 4, 5], ... "b": ["a", "b", "c", "d","e"], ... "c": [1.0, 2.0, 3.0, 4.0, 5.0] ... }) >>> df a b c 0 1 a 1.0 1 2 b 2.0 2 3 c 3.0 3 4 d 4.0 4 5 e 5.0 Set the index to become the ‘b’ column: >>> df.set_index('b') a c b a 1 1.0 b 2 2.0 c 3 3.0 d 4 4.0 e 5 5.0 Create a MultiIndex using columns ‘a’ and ‘b’: >>> df.set_index(["a", "b"]) c a b 1 a 1.0 2 b 2.0 3 c 3.0 4 d 4.0 5 e 5.0 Set new Index instance as index: >>> df.set_index(cudf.RangeIndex(10, 15)) a b c 10 1 a 1.0 11 2 b 2.0 12 3 c 3.0 13 4 d 4.0 14 5 e 5.0 Setting `append=True` will combine current index with column `a`: >>> df.set_index("a", append=True) b c a 0 1 a 1.0 1 2 b 2.0 2 3 c 3.0 3 4 d 4.0 4 5 e 5.0 `set_index` supports `inplace` parameter too: >>> df.set_index("a", inplace=True) >>> df b c a 1 a 1.0 2 b 2.0 3 c 3.0 4 d 4.0 5 e 5.0 """ if not isinstance(keys, list): keys = [keys] # Preliminary type check col_not_found = [] columns_to_add = [] names = [] to_drop = [] for i, col in enumerate(keys): # Is column label if is_scalar(col) or isinstance(col, tuple): if col in self.columns: columns_to_add.append(self[col]) names.append(col) if drop: to_drop.append(col) else: col_not_found.append(col) else: # Try coerce into column if not is_column_like(col): try: col = as_column(col) except TypeError: msg = f"{col} cannot be converted to column-like." raise TypeError(msg) if isinstance(col, (cudf.MultiIndex, pd.MultiIndex)): col = ( cudf.from_pandas(col) if isinstance(col, pd.MultiIndex) else col ) cols = [col._data[x] for x in col._data] columns_to_add.extend(cols) names.extend(col.names) else: if isinstance(col, (pd.RangeIndex, cudf.RangeIndex)): # Corner case: RangeIndex does not need to instantiate columns_to_add.append(col) else: # For pandas obj, convert to gpu obj columns_to_add.append(as_column(col)) if isinstance( col, (cudf.Series, cudf.Index, pd.Series, pd.Index) ): names.append(col.name) else: names.append(None) if col_not_found: raise KeyError(f"None of {col_not_found} are in the columns") if append: idx_cols = [self.index._data[x] for x in self.index._data] if isinstance(self.index, cudf.MultiIndex): idx_names = self.index.names else: idx_names = [self.index.name] columns_to_add = idx_cols + columns_to_add names = idx_names + names if len(columns_to_add) == 0: raise ValueError("No valid columns to be added to index.") elif len(columns_to_add) == 1: idx = cudf.Index(columns_to_add[0], name=names[0]) else: idf = cudf.DataFrame() for i, col in enumerate(columns_to_add): idf[i] = col idx = cudf.MultiIndex.from_frame(idf, names=names) return self._set_index( index=idx, to_drop=to_drop, inplace=inplace, verify_integrity=verify_integrity, ) def reset_index( self, level=None, drop=False, inplace=False, col_level=0, col_fill="" ): """ Reset the index. Reset the index of the DataFrame, and use the default one instead. Parameters ---------- drop : bool, default False Do not try to insert index into dataframe columns. This resets the index to the default integer index. inplace : bool, default False Modify the DataFrame in place (do not create a new object). Returns ------- DataFrame or None DataFrame with the new index or None if ``inplace=True``. Examples -------- >>> df = cudf.DataFrame([('bird', 389.0), ... ('bird', 24.0), ... ('mammal', 80.5), ... ('mammal', np.nan)], ... index=['falcon', 'parrot', 'lion', 'monkey'], ... columns=('class', 'max_speed')) >>> df class max_speed falcon bird 389.0 parrot bird 24.0 lion mammal 80.5 monkey mammal <NA> >>> df.reset_index() index class max_speed 0 falcon bird 389.0 1 parrot bird 24.0 2 lion mammal 80.5 3 monkey mammal <NA> >>> df.reset_index(drop=True) class max_speed 0 bird 389.0 1 bird 24.0 2 mammal 80.5 3 mammal <NA> """ if level is not None: raise NotImplementedError("level parameter is not supported yet.") if col_level != 0: raise NotImplementedError( "col_level parameter is not supported yet." ) if col_fill != "": raise NotImplementedError( "col_fill parameter is not supported yet." ) if inplace: result = self else: result = self.copy() if all(name is None for name in self.index.names): if isinstance(self.index, cudf.MultiIndex): names = tuple( f"level_{i}" for i, _ in enumerate(self.index.names) ) else: names = ("index",) else: names = self.index.names if not drop: index_columns = self.index._data.columns for name, index_column in zip( reversed(names), reversed(index_columns) ): result.insert(0, name, index_column) result.index = RangeIndex(len(self)) if inplace: return else: return result def take(self, positions, keep_index=True): """ Return a new DataFrame containing the rows specified by *positions* Parameters ---------- positions : array-like Integer or boolean array-like specifying the rows of the output. If integer, each element represents the integer index of a row. If boolean, *positions* must be of the same length as *self*, and represents a boolean mask. Returns ------- out : DataFrame New DataFrame Examples -------- >>> a = cudf.DataFrame({'a': [1.0, 2.0, 3.0], ... 'b': cudf.Series(['a', 'b', 'c'])}) >>> a.take([0, 2, 2]) a b 0 1.0 a 2 3.0 c 2 3.0 c >>> a.take([True, False, True]) a b 0 1.0 a 2 3.0 c """ positions = as_column(positions) if pd.api.types.is_bool_dtype(positions): return self._apply_boolean_mask(positions) out = self._gather(positions, keep_index=keep_index) out.columns = self.columns return out @annotate("DATAFRAME_COPY", color="cyan", domain="cudf_python") def copy(self, deep=True): """ Returns a copy of this dataframe Parameters ---------- deep: bool Make a full copy of Series columns and Index at the GPU level, or create a new allocation with references. """ out = DataFrame(data=self._data.copy(deep=deep)) out.index = self.index.copy(deep=deep) return out def __copy__(self): return self.copy(deep=True) def __deepcopy__(self, memo=None): """ Parameters ---------- memo, default None Standard signature. Unused """ if memo is None: memo = {} return self.copy(deep=True) @annotate("INSERT", color="green", domain="cudf_python") def insert(self, loc, name, value): """ Add a column to DataFrame at the index specified by loc. Parameters ---------- loc : int location to insert by index, cannot be greater then num columns + 1 name : number or string name or label of column to be inserted value : Series or array-like """ num_cols = len(self._data) if name in self._data: raise NameError(f"duplicated column name {name}") if loc < 0: loc = num_cols + loc + 1 if not (0 <= loc <= num_cols): raise ValueError( f"insert location must be within range " f"{-(num_cols + 1) * (num_cols > 0)}, " f"{num_cols * (num_cols > 0)}" ) if is_scalar(value): value = utils.scalar_broadcast_to(value, len(self)) if len(self) == 0: if isinstance(value, (pd.Series, Series)): self._index = as_index(value.index) elif len(value) > 0: self._index = RangeIndex(start=0, stop=len(value)) new_data = self._data.__class__() if num_cols != 0: for col_name in self._data: new_data[col_name] = column.column_empty_like( self._data[col_name], masked=True, newsize=len(value), ) self._data = new_data elif isinstance(value, (pd.Series, Series)): value = Series(value)._align_to_index( self._index, how="right", sort=False ) value = column.as_column(value) self._data.insert(name, value, loc=loc) def drop( self, labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors="raise", ): """ Drop specified labels from rows or columns. Remove rows or columns by specifying label names and corresponding axis, or by specifying directly index or column names. When using a multi-index, labels on different levels can be removed by specifying the level. Parameters ---------- labels : single label or list-like Index or column labels to drop. axis : {0 or 'index', 1 or 'columns'}, default 0 Whether to drop labels from the index (0 or 'index') or columns (1 or 'columns'). index : single label or list-like Alternative to specifying axis (``labels, axis=0`` is equivalent to ``index=labels``). columns : single label or list-like Alternative to specifying axis (``labels, axis=1`` is equivalent to ``columns=labels``). level : int or level name, optional For MultiIndex, level from which the labels will be removed. inplace : bool, default False If False, return a copy. Otherwise, do operation inplace and return None. errors : {'ignore', 'raise'}, default 'raise' If 'ignore', suppress error and only existing labels are dropped. Returns ------- DataFrame DataFrame without the removed index or column labels. Raises ------ KeyError If any of the labels is not found in the selected axis. See Also -------- DataFrame.loc : Label-location based indexer for selection by label. DataFrame.dropna : Return DataFrame with labels on given axis omitted where (all or any) data are missing. DataFrame.drop_duplicates : Return DataFrame with duplicate rows removed, optionally only considering certain columns. Examples -------- >>> import cudf >>> df = cudf.DataFrame({"A": [1, 2, 3, 4], ... "B": [5, 6, 7, 8], ... "C": [10, 11, 12, 13], ... "D": [20, 30, 40, 50]}) >>> df A B C D 0 1 5 10 20 1 2 6 11 30 2 3 7 12 40 3 4 8 13 50 Drop columns >>> df.drop(['B', 'C'], axis=1) A D 0 1 20 1 2 30 2 3 40 3 4 50 >>> df.drop(columns=['B', 'C']) A D 0 1 20 1 2 30 2 3 40 3 4 50 Drop a row by index >>> df.drop([0, 1]) A B C D 2 3 7 12 40 3 4 8 13 50 Drop columns and/or rows of MultiIndex DataFrame >>> midx = cudf.MultiIndex(levels=[['lama', 'cow', 'falcon'], ... ['speed', 'weight', 'length']], ... codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2], ... [0, 1, 2, 0, 1, 2, 0, 1, 2]]) >>> df = cudf.DataFrame(index=midx, columns=['big', 'small'], ... data=[[45, 30], [200, 100], [1.5, 1], [30, 20], ... [250, 150], [1.5, 0.8], [320, 250], ... [1, 0.8], [0.3, 0.2]]) >>> df big small lama speed 45.0 30.0 weight 200.0 100.0 length 1.5 1.0 cow speed 30.0 20.0 weight 250.0 150.0 length 1.5 0.8 falcon speed 320.0 250.0 weight 1.0 0.8 length 0.3 0.2 >>> df.drop(index='cow', columns='small') big lama speed 45.0 weight 200.0 length 1.5 falcon speed 320.0 weight 1.0 length 0.3 >>> df.drop(index='length', level=1) big small lama speed 45.0 30.0 weight 200.0 100.0 cow speed 30.0 20.0 weight 250.0 150.0 falcon speed 320.0 250.0 weight 1.0 0.8 """ if labels is not None: if index is not None or columns is not None: raise ValueError( "Cannot specify both 'labels' and 'index'/'columns'" ) target = labels elif index is not None: target = index axis = 0 elif columns is not None: target = columns axis = 1 else: raise ValueError( "Need to specify at least one of 'labels', " "'index' or 'columns'" ) if inplace: outdf = self else: outdf = self.copy() if axis in (1, "columns"): target = _get_host_unique(target) _drop_columns(outdf, target, errors) elif axis in (0, "index"): if not isinstance(target, (cudf.Series, cudf.Index)): target = column.as_column(target) if isinstance(self._index, cudf.MultiIndex): if level is None: level = 0 levels_index = outdf.index.get_level_values(level) if errors == "raise" and not target.isin(levels_index).all(): raise KeyError("One or more values not found in axis") # TODO : Could use anti-join as a future optimization sliced_df = outdf.take(~levels_index.isin(target)) sliced_df._index.names = self._index.names else: if errors == "raise" and not target.isin(outdf.index).all(): raise KeyError("One or more values not found in axis") sliced_df = outdf.join( cudf.DataFrame(index=target), how="leftanti" ) if columns is not None: columns = _get_host_unique(columns) _drop_columns(sliced_df, columns, errors) outdf._data = sliced_df._data outdf._index = sliced_df._index if not inplace: return outdf def _drop_column(self, name): """Drop a column by *name* """ if name not in self._data: raise KeyError(f"column '{name}' does not exist") del self._data[name] def drop_duplicates( self, subset=None, keep="first", inplace=False, ignore_index=False ): """ Return DataFrame with duplicate rows removed, optionally only considering certain subset of columns. """ outdf = super().drop_duplicates( subset=subset, keep=keep, ignore_index=ignore_index ) return self._mimic_inplace(outdf, inplace=inplace) def pop(self, item): """Return a column and drop it from the DataFrame. """ popped = self[item] del self[item] return popped def rename( self, mapper=None, index=None, columns=None, axis=0, copy=True, inplace=False, level=None, errors="ignore", ): """Alter column and index labels. Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don’t throw an error. ``DataFrame.rename`` supports two calling conventions: - ``(index=index_mapper, columns=columns_mapper, ...)`` - ``(mapper, axis={0/'index' or 1/'column'}, ...)`` We highly recommend using keyword arguments to clarify your intent. Parameters ---------- mapper : dict-like or function, default None optional dict-like or functions transformations to apply to the index/column values depending on selected ``axis``. index : dict-like, default None Optional dict-like transformations to apply to the index axis' values. Does not support functions for axis 0 yet. columns : dict-like or function, default None optional dict-like or functions transformations to apply to the columns axis' values. axis : int, default 0 Axis to rename with mapper. 0 or 'index' for index 1 or 'columns' for columns copy : boolean, default True Also copy underlying data inplace : boolean, default False Return new DataFrame. If True, assign columns without copy level : int or level name, default None In case of a MultiIndex, only rename labels in the specified level. errors : {'raise', 'ignore', 'warn'}, default 'ignore' *Only 'ignore' supported* Control raising of exceptions on invalid data for provided dtype. - ``raise`` : allow exceptions to be raised - ``ignore`` : suppress exceptions. On error return original object. - ``warn`` : prints last exceptions as warnings and return original object. Returns ------- DataFrame Notes ----- Difference from pandas: * Not supporting: level Rename will not overwite column names. If a list with duplicates is passed, column names will be postfixed with a number. """ if errors != "ignore": raise NotImplementedError( "Only errors='ignore' is currently supported" ) if level: raise NotImplementedError( "Only level=False is currently supported" ) if mapper is None and index is None and columns is None: return self.copy(deep=copy) index = mapper if index is None and axis in (0, "index") else index columns = ( mapper if columns is None and axis in (1, "columns") else columns ) if index: if ( any(type(item) == str for item in index.values()) and type(self.index) != cudf.core.index.StringIndex ): raise NotImplementedError( "Implicit conversion of index to " "mixed type is not yet supported." ) out = DataFrame( index=self.index.replace( to_replace=list(index.keys()), replacement=list(index.values()), ) ) else: out = DataFrame(index=self.index) if columns: postfix = 1 if isinstance(columns, Mapping): # It is possible for DataFrames with a MultiIndex columns # object to have columns with the same name. The following # use of _cols.items and ("_1", "_2"... allows the use of # rename in this case for key, col in self._data.items(): if key in columns: if columns[key] in out._data: out_column = columns[key] + "_" + str(postfix) postfix += 1 else: out_column = columns[key] out[out_column] = col else: out[key] = col elif callable(columns): for key, col in self._data.items(): out[columns(key)] = col else: out._data = self._data.copy(deep=copy) if inplace: self._data = out._data else: return out.copy(deep=copy) def nans_to_nulls(self): """ Convert nans (if any) to nulls. """ df = self.copy() for col in df.columns: df[col] = df[col].nans_to_nulls() return df def as_gpu_matrix(self, columns=None, order="F"): """Convert to a matrix in device memory. Parameters ---------- columns : sequence of str List of a column names to be extracted. The order is preserved. If None is specified, all columns are used. order : 'F' or 'C' Optional argument to determine whether to return a column major (Fortran) matrix or a row major (C) matrix. Returns ------- A (nrow x ncol) numba device ndarray """ if columns is None: columns = self._data.names cols = [self._data[k] for k in columns] ncol = len(cols) nrow = len(self) if ncol < 1: # This is the case for empty dataframe - construct empty cupy array matrix = cupy.empty( shape=(0, 0), dtype=np.dtype("float64"), order=order ) return cuda.as_cuda_array(matrix) if any( (is_categorical_dtype(c) or np.issubdtype(c, np.dtype("object"))) for c in cols ): raise TypeError("non-numeric data not yet supported") dtype = find_common_type([col.dtype for col in cols]) for k, c in self._data.items(): if c.has_nulls: raise ValueError( f"column '{k}' has null values. " f"hint: use .fillna() to replace null values" ) cupy_dtype = dtype if np.issubdtype(cupy_dtype, np.datetime64): cupy_dtype = np.dtype("int64") if order not in ("F", "C"): raise ValueError( "order parameter should be 'C' for row major or 'F' for" "column major GPU matrix" ) matrix = cupy.empty(shape=(nrow, ncol), dtype=cupy_dtype, order=order) for colidx, inpcol in enumerate(cols): dense = inpcol.astype(cupy_dtype) matrix[:, colidx] = cupy.asarray(dense) return cuda.as_cuda_array(matrix).view(dtype) def as_matrix(self, columns=None): """Convert to a matrix in host memory. Parameters ---------- columns : sequence of str List of a column names to be extracted. The order is preserved. If None is specified, all columns are used. Returns ------- A (nrow x ncol) numpy ndarray in "F" order. """ return self.as_gpu_matrix(columns=columns).copy_to_host() def one_hot_encoding( self, column, prefix, cats, prefix_sep="_", dtype="float64" ): """ Expand a column with one-hot-encoding. Parameters ---------- column : str the source column with binary encoding for the data. prefix : str the new column name prefix. cats : sequence of ints the sequence of categories as integers. prefix_sep : str the separator between the prefix and the category. dtype : the dtype for the outputs; defaults to float64. Returns ------- a new dataframe with new columns append for each category. Examples -------- >>> import pandas as pd >>> import cudf >>> pet_owner = [1, 2, 3, 4, 5] >>> pet_type = ['fish', 'dog', 'fish', 'bird', 'fish'] >>> df = pd.DataFrame({'pet_owner': pet_owner, 'pet_type': pet_type}) >>> df.pet_type = df.pet_type.astype('category') Create a column with numerically encoded category values >>> df['pet_codes'] = df.pet_type.cat.codes >>> gdf = cudf.from_pandas(df) Create the list of category codes to use in the encoding >>> codes = gdf.pet_codes.unique() >>> gdf.one_hot_encoding('pet_codes', 'pet_dummy', codes).head() pet_owner pet_type pet_codes pet_dummy_0 pet_dummy_1 pet_dummy_2 0 1 fish 2 0.0 0.0 1.0 1 2 dog 1 0.0 1.0 0.0 2 3 fish 2 0.0 0.0 1.0 3 4 bird 0 1.0 0.0 0.0 4 5 fish 2 0.0 0.0 1.0 """ if hasattr(cats, "to_arrow"): cats = cats.to_arrow().to_pylist() else: cats = pd.Series(cats, dtype="object") newnames = [ prefix_sep.join([prefix, "null" if cat is None else str(cat)]) for cat in cats ] newcols = self[column].one_hot_encoding(cats=cats, dtype=dtype) outdf = self.copy() for name, col in zip(newnames, newcols): outdf.insert(len(outdf._data), name, col) return outdf def label_encoding( self, column, prefix, cats, prefix_sep="_", dtype=None, na_sentinel=-1 ): """Encode labels in a column with label encoding. Parameters ---------- column : str the source column with binary encoding for the data. prefix : str the new column name prefix. cats : sequence of ints the sequence of categories as integers. prefix_sep : str the separator between the prefix and the category. dtype : the dtype for the outputs; see Series.label_encoding na_sentinel : number Value to indicate missing category. Returns ------- a new dataframe with a new column append for the coded values. """ newname = prefix_sep.join([prefix, "labels"]) newcol = self[column].label_encoding( cats=cats, dtype=dtype, na_sentinel=na_sentinel ) outdf = self.copy() outdf.insert(len(outdf._data), newname, newcol) return outdf @annotate("ARGSORT", color="yellow", domain="cudf_python") def argsort(self, ascending=True, na_position="last"): """ Sort by the values. Parameters ---------- ascending : bool or list of bool, default True If True, sort values in ascending order, otherwise descending. na_position : {‘first’ or ‘last’}, default ‘last’ Argument ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end. Returns ------- out_column_inds : cuDF Column of indices sorted based on input Notes ----- Difference from pandas: - Support axis='index' only. - Not supporting: inplace, kind - Ascending can be a list of bools to control per column """ return self._get_sorted_inds( ascending=ascending, na_position=na_position ) @annotate("SORT_INDEX", color="red", domain="cudf_python") def sort_index( self, axis=0, level=None, ascending=True, inplace=False, kind=None, na_position="last", sort_remaining=True, ignore_index=False, ): """Sort object by labels (along an axis). Parameters ---------- axis : {0 or ‘index’, 1 or ‘columns’}, default 0 The axis along which to sort. The value 0 identifies the rows, and 1 identifies the columns. level : int or level name or list of ints or list of level names If not None, sort on values in specified index level(s). This is only useful in the case of MultiIndex. ascending : bool, default True Sort ascending vs. descending. inplace : bool, default False If True, perform operation in-place. kind : sorting method such as `quick sort` and others. Not yet supported. na_position : {‘first’, ‘last’}, default ‘last’ Puts NaNs at the beginning if first; last puts NaNs at the end. sort_remaining : bool, default True Not yet supported ignore_index : bool, default False if True, index will be replaced with RangeIndex. Returns ------- DataFrame or None Examples -------- >>> df = cudf.DataFrame( ... {"b":[3, 2, 1], "a":[2, 1, 3]}, index=[1, 3, 2]) >>> df.sort_index(axis=0) b a 1 3 2 2 1 3 3 2 1 >>> df.sort_index(axis=1) a b 1 2 3 3 1 2 2 3 1 """ if kind is not None: raise NotImplementedError("kind is not yet supported") if not sort_remaining: raise NotImplementedError( "sort_remaining == False is not yet supported" ) if axis in (0, "index"): if level is not None and isinstance(self.index, cudf.MultiIndex): # Pandas currently don't handle na_position # in case of MultiIndex if ascending is True: na_position = "first" else: na_position = "last" if is_list_like(level): labels = [ self.index._get_level_label(lvl) for lvl in level ] else: labels = [self.index._get_level_label(level)] inds = self.index._source_data[labels].argsort( ascending=ascending, na_position=na_position ) else: inds = self.index.argsort( ascending=ascending, na_position=na_position ) outdf = self.take(inds) else: labels = sorted(self._data.names, reverse=not ascending) outdf = self[labels] if ignore_index is True: outdf = outdf.reset_index(drop=True) return self._mimic_inplace(outdf, inplace=inplace) def sort_values( self, by, axis=0, ascending=True, inplace=False, kind="quicksort", na_position="last", ignore_index=False, ): """ Sort by the values row-wise. Parameters ---------- by : str or list of str Name or list of names to sort by. ascending : bool or list of bool, default True Sort ascending vs. descending. Specify list for multiple sort orders. If this is a list of bools, must match the length of the by. na_position : {‘first’, ‘last’}, default ‘last’ 'first' puts nulls at the beginning, 'last' puts nulls at the end ignore_index : bool, default False If True, index will not be sorted. Returns ------- sorted_obj : cuDF DataFrame Notes ----- Difference from pandas: * Support axis='index' only. * Not supporting: inplace, kind Examples -------- >>> import cudf >>> a = ('a', [0, 1, 2]) >>> b = ('b', [-3, 2, 0]) >>> df = cudf.DataFrame([a, b]) >>> df.sort_values('b') a b 0 0 -3 2 2 0 1 1 2 """ if inplace: raise NotImplementedError("`inplace` not currently implemented.") if kind != "quicksort": raise NotImplementedError("`kind` not currently implemented.") if axis != 0: raise NotImplementedError("`axis` not currently implemented.") # argsort the `by` column return self.take( self[by].argsort(ascending=ascending, na_position=na_position), keep_index=not ignore_index, ) def agg(self, aggs, axis=None): """ Aggregate using one or more operations over the specified axis. Parameters ---------- aggs : Iterable (set, list, string, tuple or dict) Function to use for aggregating data. Accepted types are: * string name, e.g. ``"sum"`` * list of functions, e.g. ``["sum", "min", "max"]`` * dict of axis labels specified operations per column, e.g. ``{"a": "sum"}`` axis : not yet supported Returns ------- Aggregation Result : ``Series`` or ``DataFrame`` When ``DataFrame.agg`` is called with single agg, ``Series`` is returned. When ``DataFrame.agg`` is called with several aggs, ``DataFrame`` is returned. Notes ----- Difference from pandas: * Not supporting: ``axis``, ``*args``, ``**kwargs`` """ # TODO: Remove the typecasting below once issue #6846 is fixed # link <https://github.com/rapidsai/cudf/issues/6846> dtypes = [self[col].dtype for col in self._column_names] common_dtype = cudf.utils.dtypes.find_common_type(dtypes) df_normalized = self.astype(common_dtype) if any(is_string_dtype(dt) for dt in dtypes): raise NotImplementedError( "DataFrame.agg() is not supported for " "frames containing string columns" ) if axis == 0 or axis is not None: raise NotImplementedError("axis not implemented yet") if isinstance(aggs, Iterable) and not isinstance(aggs, (str, dict)): result = cudf.DataFrame() # TODO : Allow simultaneous pass for multi-aggregation as # a future optimization for agg in aggs: result[agg] = getattr(df_normalized, agg)() return result.T.sort_index(axis=1, ascending=True) elif isinstance(aggs, str): if not hasattr(df_normalized, aggs): raise AttributeError( f"{aggs} is not a valid function for " f"'DataFrame' object" ) result = cudf.DataFrame() result[aggs] = getattr(df_normalized, aggs)() result = result.iloc[:, 0] result.name = None return result elif isinstance(aggs, dict): cols = aggs.keys() if any([callable(val) for val in aggs.values()]): raise NotImplementedError( "callable parameter is not implemented yet" ) elif all([isinstance(val, str) for val in aggs.values()]): result = cudf.Series(index=cols) for key, value in aggs.items(): col = df_normalized[key] if not hasattr(col, value): raise AttributeError( f"{value} is not a valid function for " f"'Series' object" ) result[key] = getattr(col, value)() elif all([isinstance(val, Iterable) for val in aggs.values()]): idxs = set() for val in aggs.values(): if isinstance(val, Iterable): idxs.update(val) elif isinstance(val, str): idxs.add(val) idxs = sorted(list(idxs)) for agg in idxs: if agg is callable: raise NotImplementedError( "callable parameter is not implemented yet" ) result = cudf.DataFrame(index=idxs, columns=cols) for key in aggs.keys(): col = df_normalized[key] col_empty = column_empty( len(idxs), dtype=col.dtype, masked=True ) ans = cudf.Series(data=col_empty, index=idxs) if isinstance(aggs.get(key), Iterable): # TODO : Allow simultaneous pass for multi-aggregation # as a future optimization for agg in aggs.get(key): if not hasattr(col, agg): raise AttributeError( f"{agg} is not a valid function for " f"'Series' object" ) ans[agg] = getattr(col, agg)() elif isinstance(aggs.get(key), str): if not hasattr(col, aggs.get(key)): raise AttributeError( f"{aggs.get(key)} is not a valid function for " f"'Series' object" ) ans[aggs.get(key)] = getattr(col, agg)() result[key] = ans else: raise ValueError("values of dict must be a string or list") return result elif callable(aggs): raise NotImplementedError( "callable parameter is not implemented yet" ) else: raise ValueError("argument must be a string, list or dict") def nlargest(self, n, columns, keep="first"): """Get the rows of the DataFrame sorted by the n largest value of *columns* Notes ----- Difference from pandas: - Only a single column is supported in *columns* """ return self._n_largest_or_smallest("nlargest", n, columns, keep) def nsmallest(self, n, columns, keep="first"): """Get the rows of the DataFrame sorted by the n smallest value of *columns* Notes ----- Difference from pandas: - Only a single column is supported in *columns* """ return self._n_largest_or_smallest("nsmallest", n, columns, keep) def _n_largest_or_smallest(self, method, n, columns, keep): # Get column to operate on if not isinstance(columns, str): [column] = columns else: column = columns col = self[column].reset_index(drop=True) # Operate sorted_series = getattr(col, method)(n=n, keep=keep) df = DataFrame() new_positions = sorted_series.index.gpu_values for k in self._data.names: if k == column: df[k] = sorted_series else: df[k] = self[k].reset_index(drop=True).take(new_positions) return df.set_index(self.index.take(new_positions)) def transpose(self): """Transpose index and columns. Returns ------- a new (ncol x nrow) dataframe. self is (nrow x ncol) Notes ----- Difference from pandas: Not supporting *copy* because default and only behavior is copy=True """ # Never transpose a MultiIndex - remove the existing columns and # replace with a RangeIndex. Afterward, reassign. columns = self.index.copy(deep=False) index = self.columns.copy(deep=False) if self._num_columns == 0 or self._num_rows == 0: return DataFrame(index=index, columns=columns) # Cython renames the columns to the range [0...ncols] result = self.__class__._from_table(libcudf.transpose.transpose(self)) # Set the old column names as the new index result._index = as_index(index) # Set the old index as the new column names result.columns = columns return result @property def T(self): """ Transpose index and columns. Reflect the DataFrame over its main diagonal by writing rows as columns and vice-versa. The property T is an accessor to the method transpose(). Returns ------- out : DataFrame The transposed DataFrame. """ return self.transpose() def melt(self, **kwargs): """Unpivots a DataFrame from wide format to long format, optionally leaving identifier variables set. Parameters ---------- frame : DataFrame id_vars : tuple, list, or ndarray, optional Column(s) to use as identifier variables. default: None value_vars : tuple, list, or ndarray, optional Column(s) to unpivot. default: all columns that are not set as `id_vars`. var_name : scalar Name to use for the `variable` column. default: frame.columns.name or 'variable' value_name : str Name to use for the `value` column. default: 'value' Returns ------- out : DataFrame Melted result """ from cudf.core.reshape import melt return melt(self, **kwargs) @annotate("JOIN", color="blue", domain="cudf_python") def merge( self, right, on=None, left_on=None, right_on=None, left_index=False, right_index=False, how="inner", sort=False, lsuffix=None, rsuffix=None, method="hash", indicator=False, suffixes=("_x", "_y"), ): """Merge GPU DataFrame objects by performing a database-style join operation by columns or indexes. Parameters ---------- right : DataFrame on : label or list; defaults to None Column or index level names to join on. These must be found in both DataFrames. If on is None and not merging on indexes then this defaults to the intersection of the columns in both DataFrames. how : {‘left’, ‘outer’, ‘inner’}, default ‘inner’ Type of merge to be performed. - left : use only keys from left frame, similar to a SQL left outer join. - right : not supported. - outer : use union of keys from both frames, similar to a SQL full outer join. - inner: use intersection of keys from both frames, similar to a SQL inner join. left_on : label or list, or array-like Column or index level names to join on in the left DataFrame. Can also be an array or list of arrays of the length of the left DataFrame. These arrays are treated as if they are columns. right_on : label or list, or array-like Column or index level names to join on in the right DataFrame. Can also be an array or list of arrays of the length of the right DataFrame. These arrays are treated as if they are columns. left_index : bool, default False Use the index from the left DataFrame as the join key(s). right_index : bool, default False Use the index from the right DataFrame as the join key. sort : bool, default False Sort the resulting dataframe by the columns that were merged on, starting from the left. suffixes: Tuple[str, str], defaults to ('_x', '_y') Suffixes applied to overlapping column names on the left and right sides method : {‘hash’, ‘sort’}, default ‘hash’ The implementation method to be used for the operation. Returns ------- merged : DataFrame Notes ----- **DataFrames merges in cuDF result in non-deterministic row ordering.** Examples -------- >>> import cudf >>> df_a = cudf.DataFrame() >>> df_a['key'] = [0, 1, 2, 3, 4] >>> df_a['vals_a'] = [float(i + 10) for i in range(5)] >>> df_b = cudf.DataFrame() >>> df_b['key'] = [1, 2, 4] >>> df_b['vals_b'] = [float(i+10) for i in range(3)] >>> df_merged = df_a.merge(df_b, on=['key'], how='left') >>> df_merged.sort_values('key') # doctest: +SKIP key vals_a vals_b 3 0 10.0 0 1 11.0 10.0 1 2 12.0 11.0 4 3 13.0 2 4 14.0 12.0 """ if indicator: raise NotImplementedError( "Only indicator=False is currently supported" ) if lsuffix or rsuffix: raise ValueError( "The lsuffix and rsuffix keywords have been replaced with the " "``suffixes=`` keyword. " "Please provide the following instead: \n\n" " suffixes=('%s', '%s')" % (lsuffix or "_x", rsuffix or "_y") ) else: lsuffix, rsuffix = suffixes lhs = self.copy(deep=False) rhs = right.copy(deep=False) # Compute merge gdf_result = super(DataFrame, lhs)._merge( rhs, on=on, left_on=left_on, right_on=right_on, left_index=left_index, right_index=right_index, how=how, sort=sort, lsuffix=lsuffix, rsuffix=rsuffix, method=method, indicator=indicator, suffixes=suffixes, ) return gdf_result @annotate("JOIN", color="blue", domain="cudf_python") def join( self, other, on=None, how="left", lsuffix="", rsuffix="", sort=False, method="hash", ): """Join columns with other DataFrame on index or on a key column. Parameters ---------- other : DataFrame how : str Only accepts "left", "right", "inner", "outer" lsuffix, rsuffix : str The suffices to add to the left (*lsuffix*) and right (*rsuffix*) column names when avoiding conflicts. sort : bool Set to True to ensure sorted ordering. Returns ------- joined : DataFrame Notes ----- Difference from pandas: - *other* must be a single DataFrame for now. - *on* is not supported yet due to lack of multi-index support. """ lhs = self rhs = other df = lhs.merge( rhs, left_index=True, right_index=True, how=how, suffixes=(lsuffix, rsuffix), method=method, sort=sort, ) df.index.name = ( None if lhs.index.name != rhs.index.name else lhs.index.name ) return df @copy_docstring(DataFrameGroupBy.__init__) def groupby( self, by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, observed=False, dropna=True, ): if axis not in (0, "index"): raise NotImplementedError("axis parameter is not yet implemented") if group_keys is not True: raise NotImplementedError( "The group_keys keyword is not yet implemented" ) if squeeze is not False: raise NotImplementedError( "squeeze parameter is not yet implemented" ) if observed is not False: raise NotImplementedError( "observed parameter is not yet implemented" ) if by is None and level is None: raise TypeError( "groupby() requires either by or level to be specified." ) return DataFrameGroupBy( self, by=by, level=level, as_index=as_index, dropna=dropna, sort=sort, ) @copy_docstring(Rolling) def rolling( self, window, min_periods=None, center=False, axis=0, win_type=None ): return Rolling( self, window, min_periods=min_periods, center=center, axis=axis, win_type=win_type, ) def query(self, expr, local_dict=None): """ Query with a boolean expression using Numba to compile a GPU kernel. See pandas.DataFrame.query. Parameters ---------- expr : str A boolean expression. Names in expression refer to columns. `index` can be used instead of index name, but this is not supported for MultiIndex. Names starting with `@` refer to Python variables. An output value will be `null` if any of the input values are `null` regardless of expression. local_dict : dict Containing the local variable to be used in query. Returns ------- filtered : DataFrame Examples -------- >>> import cudf >>> a = ('a', [1, 2, 2]) >>> b = ('b', [3, 4, 5]) >>> df = cudf.DataFrame([a, b]) >>> expr = "(a == 2 and b == 4) or (b == 3)" >>> df.query(expr) a b 0 1 3 1 2 4 DateTime conditionals: >>> import numpy as np >>> import datetime >>> df = cudf.DataFrame() >>> data = np.array(['2018-10-07', '2018-10-08'], dtype='datetime64') >>> df['datetimes'] = data >>> search_date = datetime.datetime.strptime('2018-10-08', '%Y-%m-%d') >>> df.query('datetimes==@search_date') datetimes 1 2018-10-08T00:00:00.000 Using local_dict: >>> import numpy as np >>> import datetime >>> df = cudf.DataFrame() >>> data = np.array(['2018-10-07', '2018-10-08'], dtype='datetime64') >>> df['datetimes'] = data >>> search_date2 = datetime.datetime.strptime('2018-10-08', '%Y-%m-%d') >>> df.query('datetimes==@search_date', ... local_dict={'search_date':search_date2}) datetimes 1 2018-10-08T00:00:00.000 """ # can't use `annotate` decorator here as we inspect the calling # environment. with annotate("QUERY", color="purple", domain="cudf_python"): if local_dict is None: local_dict = {} if self.empty: return self.copy() if not isinstance(local_dict, dict): raise TypeError( f"local_dict type: expected dict but found " f"{type(local_dict)}" ) # Get calling environment callframe = inspect.currentframe().f_back callenv = { "locals": callframe.f_locals, "globals": callframe.f_globals, "local_dict": local_dict, } # Run query boolmask = queryutils.query_execute(self, expr, callenv) return self._apply_boolean_mask(boolmask) @applyutils.doc_apply() def apply_rows( self, func, incols, outcols, kwargs, pessimistic_nulls=True, cache_key=None, ): """ Apply a row-wise user defined function. Parameters ---------- {params} Examples -------- The user function should loop over the columns and set the output for each row. Loop execution order is arbitrary, so each iteration of the loop **MUST** be independent of each other. When ``func`` is invoked, the array args corresponding to the input/output are strided so as to improve GPU parallelism. The loop in the function resembles serial code, but executes concurrently in multiple threads. >>> import cudf >>> import numpy as np >>> df = cudf.DataFrame() >>> nelem = 3 >>> df['in1'] = np.arange(nelem) >>> df['in2'] = np.arange(nelem) >>> df['in3'] = np.arange(nelem) Define input columns for the kernel >>> in1 = df['in1'] >>> in2 = df['in2'] >>> in3 = df['in3'] >>> def kernel(in1, in2, in3, out1, out2, kwarg1, kwarg2): ... for i, (x, y, z) in enumerate(zip(in1, in2, in3)): ... out1[i] = kwarg2 * x - kwarg1 * y ... out2[i] = y - kwarg1 * z Call ``.apply_rows`` with the name of the input columns, the name and dtype of the output columns, and, optionally, a dict of extra arguments. >>> df.apply_rows(kernel, ... incols=['in1', 'in2', 'in3'], ... outcols=dict(out1=np.float64, out2=np.float64), ... kwargs=dict(kwarg1=3, kwarg2=4)) in1 in2 in3 out1 out2 0 0 0 0 0.0 0.0 1 1 1 1 1.0 -2.0 2 2 2 2 2.0 -4.0 """ for col in incols: current_col_dtype = self._data[col].dtype if is_string_dtype(current_col_dtype) or is_categorical_dtype( current_col_dtype ): raise TypeError( "User defined functions are currently not " "supported on Series with dtypes `str` and `category`." ) return applyutils.apply_rows( self, func, incols, outcols, kwargs, pessimistic_nulls, cache_key=cache_key, ) @applyutils.doc_applychunks() def apply_chunks( self, func, incols, outcols, kwargs=None, pessimistic_nulls=True, chunks=None, blkct=None, tpb=None, ): """ Transform user-specified chunks using the user-provided function. Parameters ---------- {params} {params_chunks} Examples -------- For ``tpb > 1``, ``func`` is executed by ``tpb`` number of threads concurrently. To access the thread id and count, use ``numba.cuda.threadIdx.x`` and ``numba.cuda.blockDim.x``, respectively (See `numba CUDA kernel documentation`_). .. _numba CUDA kernel documentation:\ http://numba.pydata.org/numba-doc/latest/cuda/kernels.html In the example below, the *kernel* is invoked concurrently on each specified chunk. The *kernel* computes the corresponding output for the chunk. By looping over the range ``range(cuda.threadIdx.x, in1.size, cuda.blockDim.x)``, the *kernel* function can be used with any *tpb* in an efficient manner. >>> from numba import cuda >>> @cuda.jit ... def kernel(in1, in2, in3, out1): ... for i in range(cuda.threadIdx.x, in1.size, cuda.blockDim.x): ... x = in1[i] ... y = in2[i] ... z = in3[i] ... out1[i] = x * y + z See also -------- DataFrame.apply_rows """ if kwargs is None: kwargs = {} if chunks is None: raise ValueError("*chunks* must be defined") return applyutils.apply_chunks( self, func, incols, outcols, kwargs, pessimistic_nulls, chunks, tpb=tpb, ) def hash_columns(self, columns=None): """Hash the given *columns* and return a new device array Parameters ---------- columns : sequence of str; optional Sequence of column names. If columns is *None* (unspecified), all columns in the frame are used. """ if columns is None: table_to_hash = self else: cols = [self[k]._column for k in columns] table_to_hash = Frame(data=OrderedColumnDict(zip(columns, cols))) return Series(table_to_hash._hash()).values def partition_by_hash(self, columns, nparts, keep_index=True): """Partition the dataframe by the hashed value of data in *columns*. Parameters ---------- columns : sequence of str The names of the columns to be hashed. Must have at least one name. nparts : int Number of output partitions keep_index : boolean Whether to keep the index or drop it Returns ------- partitioned: list of DataFrame """ idx = ( 0 if (self._index is None or keep_index is False) else self._index._num_columns ) key_indices = [self._data.names.index(k) + idx for k in columns] outdf, offsets = self._hash_partition(key_indices, nparts, keep_index) # Slice into partition return [outdf[s:e] for s, e in zip(offsets, offsets[1:] + [None])] def replace( self, to_replace=None, value=None, inplace=False, limit=None, regex=False, method=None, ): """ Replace values given in *to_replace* with *replacement*. Parameters ---------- to_replace : numeric, str, list-like or dict Value(s) to replace. * numeric or str: - values equal to *to_replace* will be replaced with *replacement* * list of numeric or str: - If *replacement* is also list-like, *to_replace* and *replacement* must be of same length. * dict: - Dicts can be used to replace different values in different columns. For example, `{'a': 1, 'z': 2}` specifies that the value 1 in column `a` and the value 2 in column `z` should be replaced with replacement*. value : numeric, str, list-like, or dict Value(s) to replace `to_replace` with. If a dict is provided, then its keys must match the keys in *to_replace*, and corresponding values must be compatible (e.g., if they are lists, then they must match in length). inplace : bool, default False If True, in place. Returns ------- result : DataFrame DataFrame after replacement. Examples -------- >>> import cudf >>> df = cudf.DataFrame() >>> df['id']= [0, 1, 2, -1, 4, -1, 6] >>> df['id']= df['id'].replace(-1, None) >>> df id 0 0 1 1 2 2 3 <NA> 4 4 5 <NA> 6 6 Notes ----- Parameters that are currently not supported are: `limit`, `regex`, `method` """ if limit is not None: raise NotImplementedError("limit parameter is not implemented yet") if regex: raise NotImplementedError("regex parameter is not implemented yet") if method not in ("pad", None): raise NotImplementedError( "method parameter is not implemented yet" ) outdf = super().replace(to_replace=to_replace, replacement=value) return self._mimic_inplace(outdf, inplace=inplace) def info( self, verbose=None, buf=None, max_cols=None, memory_usage=None, null_counts=None, ): """ Print a concise summary of a DataFrame. This method prints information about a DataFrame including the index dtype and column dtypes, non-null values and memory usage. Parameters ---------- verbose : bool, optional Whether to print the full summary. By default, the setting in ``pandas.options.display.max_info_columns`` is followed. buf : writable buffer, defaults to sys.stdout Where to send the output. By default, the output is printed to sys.stdout. Pass a writable buffer if you need to further process the output. max_cols : int, optional When to switch from the verbose to the truncated output. If the DataFrame has more than `max_cols` columns, the truncated output is used. By default, the setting in ``pandas.options.display.max_info_columns`` is used. memory_usage : bool, str, optional Specifies whether total memory usage of the DataFrame elements (including the index) should be displayed. By default, this follows the ``pandas.options.display.memory_usage`` setting. True always show memory usage. False never shows memory usage. A value of 'deep' is equivalent to "True with deep introspection". Memory usage is shown in human-readable units (base-2 representation). Without deep introspection a memory estimation is made based in column dtype and number of rows assuming values consume the same memory amount for corresponding dtypes. With deep memory introspection, a real memory usage calculation is performed at the cost of computational resources. null_counts : bool, optional Whether to show the non-null counts. By default, this is shown only if the frame is smaller than ``pandas.options.display.max_info_rows`` and ``pandas.options.display.max_info_columns``. A value of True always shows the counts, and False never shows the counts. Returns ------- None This method prints a summary of a DataFrame and returns None. See Also -------- DataFrame.describe: Generate descriptive statistics of DataFrame columns. DataFrame.memory_usage: Memory usage of DataFrame columns. Examples -------- >>> import cudf >>> int_values = [1, 2, 3, 4, 5] >>> text_values = ['alpha', 'beta', 'gamma', 'delta', 'epsilon'] >>> float_values = [0.0, 0.25, 0.5, 0.75, 1.0] >>> df = cudf.DataFrame({"int_col": int_values, ... "text_col": text_values, ... "float_col": float_values}) >>> df int_col text_col float_col 0 1 alpha 0.00 1 2 beta 0.25 2 3 gamma 0.50 3 4 delta 0.75 4 5 epsilon 1.00 Prints information of all columns: >>> df.info(verbose=True) <class 'cudf.core.dataframe.DataFrame'> RangeIndex: 5 entries, 0 to 4 Data columns (total 3 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 int_col 5 non-null int64 1 text_col 5 non-null object 2 float_col 5 non-null float64 dtypes: float64(1), int64(1), object(1) memory usage: 130.0+ bytes Prints a summary of columns count and its dtypes but not per column information: >>> df.info(verbose=False) <class 'cudf.core.dataframe.DataFrame'> RangeIndex: 5 entries, 0 to 4 Columns: 3 entries, int_col to float_col dtypes: float64(1), int64(1), object(1) memory usage: 130.0+ bytes Pipe output of DataFrame.info to buffer instead of sys.stdout, get buffer content and writes to a text file: >>> import io >>> buffer = io.StringIO() >>> df.info(buf=buffer) >>> s = buffer.getvalue() >>> with open("df_info.txt", "w", ... encoding="utf-8") as f: ... f.write(s) ... 369 The `memory_usage` parameter allows deep introspection mode, specially useful for big DataFrames and fine-tune memory optimization: >>> import numpy as np >>> random_strings_array = np.random.choice(['a', 'b', 'c'], 10 ** 6) >>> df = cudf.DataFrame({ ... 'column_1': np.random.choice(['a', 'b', 'c'], 10 ** 6), ... 'column_2': np.random.choice(['a', 'b', 'c'], 10 ** 6), ... 'column_3': np.random.choice(['a', 'b', 'c'], 10 ** 6) ... }) >>> df.info(memory_usage='deep') <class 'cudf.core.dataframe.DataFrame'> RangeIndex: 1000000 entries, 0 to 999999 Data columns (total 3 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 column_1 1000000 non-null object 1 column_2 1000000 non-null object 2 column_3 1000000 non-null object dtypes: object(3) memory usage: 14.3 MB """ if buf is None: buf = sys.stdout lines = [str(type(self))] index_name = type(self._index).__name__ if len(self._index) > 0: entries_summary = f", {self._index[0]} to {self._index[-1]}" else: entries_summary = "" index_summary = ( f"{index_name}: {len(self._index)} entries{entries_summary}" ) lines.append(index_summary) if len(self.columns) == 0: lines.append(f"Empty {type(self).__name__}") cudf.utils.ioutils.buffer_write_lines(buf, lines) return cols = self.columns col_count = len(self.columns) if max_cols is None: max_cols = pd.options.display.max_info_columns max_rows = pd.options.display.max_info_rows if null_counts is None: show_counts = (col_count <= max_cols) and (len(self) < max_rows) else: show_counts = null_counts exceeds_info_cols = col_count > max_cols def _put_str(s, space): return str(s)[:space].ljust(space) def _verbose_repr(): lines.append(f"Data columns (total {len(self.columns)} columns):") id_head = " # " column_head = "Column" col_space = 2 max_col = max(len(pprint_thing(k)) for k in cols) len_column = len(pprint_thing(column_head)) space = max(max_col, len_column) + col_space max_id = len(pprint_thing(col_count)) len_id = len(pprint_thing(id_head)) space_num = max(max_id, len_id) + col_space counts = None header = _put_str(id_head, space_num) + _put_str( column_head, space ) if show_counts: counts = self.count().to_pandas().tolist() if len(cols) != len(counts): raise AssertionError( f"Columns must equal " f"counts ({len(cols)} != {len(counts)})" ) count_header = "Non-Null Count" len_count = len(count_header) non_null = " non-null" max_count = max(len(pprint_thing(k)) for k in counts) + len( non_null ) space_count = max(len_count, max_count) + col_space count_temp = "{count}" + non_null else: count_header = "" space_count = len(count_header) len_count = space_count count_temp = "{count}" dtype_header = "Dtype" len_dtype = len(dtype_header) max_dtypes = max(len(pprint_thing(k)) for k in self.dtypes) space_dtype = max(len_dtype, max_dtypes) header += ( _put_str(count_header, space_count) + _put_str(dtype_header, space_dtype).rstrip() ) lines.append(header) lines.append( _put_str("-" * len_id, space_num) + _put_str("-" * len_column, space) + _put_str("-" * len_count, space_count) + _put_str("-" * len_dtype, space_dtype).rstrip() ) for i, col in enumerate(self.columns): dtype = self.dtypes.iloc[i] col = pprint_thing(col) line_no = _put_str(" {num}".format(num=i), space_num) count = "" if show_counts: count = counts[i] lines.append( line_no + _put_str(col, space) + _put_str(count_temp.format(count=count), space_count) + _put_str(dtype, space_dtype).rstrip() ) def _non_verbose_repr(): if len(self.columns) > 0: entries_summary = f", {self.columns[0]} to {self.columns[-1]}" else: entries_summary = "" columns_summary = ( f"Columns: {len(self.columns)} entries{entries_summary}" ) lines.append(columns_summary) def _sizeof_fmt(num, size_qualifier): # returns size in human readable format for x in ["bytes", "KB", "MB", "GB", "TB"]: if num < 1024.0: return f"{num:3.1f}{size_qualifier} {x}" num /= 1024.0 return f"{num:3.1f}{size_qualifier} PB" if verbose: _verbose_repr() elif verbose is False: # specifically set to False, not nesc None _non_verbose_repr() else: if exceeds_info_cols: _non_verbose_repr() else: _verbose_repr() dtype_counts = defaultdict(int) for col in self._data: dtype_counts[self._data[col].dtype.name] += 1 dtypes = [f"{k[0]}({k[1]:d})" for k in sorted(dtype_counts.items())] lines.append(f"dtypes: {", ".join(dtypes)}") if memory_usage is None: memory_usage = pd.options.display.memory_usage if memory_usage: # append memory usage of df to display size_qualifier = "" if memory_usage == "deep": deep = True else: deep = False if "object" in dtype_counts or self.index.dtype == "object": size_qualifier = "+" mem_usage = self.memory_usage(index=True, deep=deep).sum() lines.append( f"memory usage: {_sizeof_fmt(mem_usage, size_qualifier)}\n" ) cudf.utils.ioutils.buffer_write_lines(buf, lines) @docutils.doc_describe() def describe( self, percentiles=None, include=None, exclude=None, datetime_is_numeric=False, ): """{docstring}""" if not include and not exclude: default_include = [np.number] if datetime_is_numeric: default_include.append("datetime") data_to_describe = self.select_dtypes(include=default_include) if len(data_to_describe.columns) == 0: data_to_describe = self elif include == "all": if exclude is not None: raise ValueError("exclude must be None when include is 'all'") data_to_describe = self else: data_to_describe = self.select_dtypes( include=include, exclude=exclude ) if data_to_describe.empty: raise ValueError("No data of included types.") describe_series_list = [ data_to_describe[col].describe(percentiles=percentiles) for col in data_to_describe.columns ] if len(describe_series_list) == 1: return describe_series_list[0].to_frame() else: ldesc_indexes = sorted( (x.index for x in describe_series_list), key=len ) names = OrderedDict.fromkeys( [ name for idxnames in ldesc_indexes for name in idxnames.to_pandas() ], None, ) return cudf.concat( [ series.reindex(names, copy=False) for series in describe_series_list ], axis=1, sort=False, ) def to_pandas(self, nullable=False, **kwargs): """ Convert to a Pandas DataFrame. Parameters ---------- nullable : Boolean, Default False If ``nullable`` is ``True``, the resulting columns in the dataframe will be having a corresponding nullable Pandas dtype. If ``nullable`` is ``False``, the resulting columns will either convert null values to ``np.nan`` or ``None`` depending on the dtype. Returns ------- out : Pandas DataFrame Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [0, 1, 2], 'b': [-3, 2, 0]}) >>> pdf = df.to_pandas() >>> pdf a b 0 0 -3 1 1 2 2 2 0 >>> type(pdf) <class 'pandas.core.frame.DataFrame'> ``nullable`` parameter can be used to control whether dtype can be Pandas Nullable or not: >>> df = cudf.DataFrame({'a': [0, None, 2], 'b': [True, False, None]}) >>> df a b 0 0 True 1 <NA> False 2 2 <NA> >>> pdf = df.to_pandas(nullable=True) >>> pdf a b 0 0 True 1 <NA> False 2 2 <NA> >>> pdf.dtypes a Int64 b boolean dtype: object >>> pdf = df.to_pandas(nullable=False) >>> pdf a b 0 0.0 True 1 NaN False 2 2.0 None >>> pdf.dtypes a float64 b object dtype: object """ out_data = {} out_index = self.index.to_pandas() if not isinstance(self.columns, pd.Index): out_columns = self.columns.to_pandas() else: out_columns = self.columns for i, col_key in enumerate(self._data): out_data[i] = self._data[col_key].to_pandas( index=out_index, nullable=nullable ) if isinstance(self.columns, Index): out_columns = self.columns.to_pandas() if isinstance(self.columns, cudf.core.multiindex.MultiIndex): if self.columns.names is not None: out_columns.names = self.columns.names else: out_columns.name = self.columns.name out_df = pd.DataFrame(out_data, index=out_index) out_df.columns = out_columns return out_df @classmethod def from_pandas(cls, dataframe, nan_as_null=None): """ Convert from a Pandas DataFrame. Parameters ---------- dataframe : Pandas DataFrame object A Pandads DataFrame object which has to be converted to cuDF DataFrame. nan_as_null : bool, Default True If ``True``, converts ``np.nan`` values to ``null`` values. If ``False``, leaves ``np.nan`` values as is. Raises ------ TypeError for invalid input type. Examples -------- >>> import cudf >>> import pandas as pd >>> data = [[0,1], [1,2], [3,4]] >>> pdf = pd.DataFrame(data, columns=['a', 'b'], dtype=int) >>> cudf.from_pandas(pdf) a b 0 0 1 1 1 2 2 3 4 """ if not isinstance(dataframe, pd.DataFrame): raise TypeError("not a pandas.DataFrame") if not dataframe.columns.is_unique: raise ValueError("Duplicate column names are not allowed") df = cls() # Set columns for col_name, col_value in dataframe.iteritems(): # necessary because multi-index can return multiple # columns for a single key if len(col_value.shape) == 1: df[col_name] = column.as_column( col_value.array, nan_as_null=nan_as_null ) else: vals = col_value.values.T if vals.shape[0] == 1: df[col_name] = column.as_column( vals.flatten(), nan_as_null=nan_as_null ) else: if isinstance(col_name, tuple): col_name = str(col_name) for idx in range(len(vals.shape)): df[col_name] = column.as_column( vals[idx], nan_as_null=nan_as_null ) # Set columns only if it is a MultiIndex if isinstance(dataframe.columns, pd.MultiIndex): df.columns = dataframe.columns # Set index index = cudf.from_pandas(dataframe.index, nan_as_null=nan_as_null) result = df.set_index(index) return result @classmethod def from_arrow(cls, table): """ Convert from PyArrow Table to DataFrame. Parameters ---------- table : PyArrow Table Object PyArrow Table Object which has to be converted to cudf DataFrame. Raises ------ TypeError for invalid input type. Returns ------- cudf DataFrame Notes ----- - Does not support automatically setting index column(s) similar to how ``to_pandas`` works for PyArrow Tables. Examples -------- >>> import cudf >>> import pyarrow as pa >>> data = pa.table({"a":[1, 2, 3], "b":[4, 5, 6]}) >>> cudf.DataFrame.from_arrow(data) a b 0 1 4 1 2 5 2 3 6 """ index_col = None if isinstance(table, pa.Table) and isinstance( table.schema.pandas_metadata, dict ): index_col = table.schema.pandas_metadata["index_columns"] out = super().from_arrow(table) if index_col: if isinstance(index_col[0], dict): out = out.set_index( cudf.RangeIndex( index_col[0]["start"], index_col[0]["stop"], name=index_col[0]["name"], ) ) else: out = out.set_index(index_col[0]) return out def to_arrow(self, preserve_index=True): """ Convert to a PyArrow Table. Parameters ---------- preserve_index : bool, default True whether index column and its meta data needs to be saved or not Returns ------- PyArrow Table Examples -------- >>> import cudf >>> df = cudf.DataFrame( ... {"a":[1, 2, 3], "b":[4, 5, 6]}, index=[1, 2, 3]) >>> df.to_arrow() pyarrow.Table a: int64 b: int64 index: int64 >>> df.to_arrow(preserve_index=False) pyarrow.Table a: int64 b: int64 """ data = self.copy(deep=False) index_descr = [] if preserve_index: if isinstance(self.index, cudf.RangeIndex): descr = { "kind": "range", "name": self.index.name, "start": self.index._start, "stop": self.index._stop, "step": 1, } else: if isinstance(self.index, cudf.MultiIndex): gen_names = tuple( f"level_{i}" for i, _ in enumerate(self.index._data.names) ) else: gen_names = ( self.index.names if self.index.name is not None else ("index",) ) for gen_name, col_name in zip( gen_names, self.index._data.names ): data.insert( data.shape[1], gen_name, self.index._data[col_name] ) descr = gen_names[0] index_descr.append(descr) out = super(DataFrame, data).to_arrow() metadata = pa.pandas_compat.construct_metadata( self, out.schema.names, [self.index], index_descr, preserve_index, types=out.schema.types, ) return out.replace_schema_metadata(metadata) def to_records(self, index=True): """Convert to a numpy recarray Parameters ---------- index : bool Whether to include the index in the output. Returns ------- numpy recarray """ members = [("index", self.index.dtype)] if index else [] members += [(col, self[col].dtype) for col in self._data.names] dtype = np.dtype(members) ret = np.recarray(len(self), dtype=dtype) if index: ret["index"] = self.index.to_array() for col in self._data.names: ret[col] = self[col].to_array() return ret @classmethod def from_records(cls, data, index=None, columns=None, nan_as_null=False): """ Convert structured or record ndarray to DataFrame. Parameters ---------- data : numpy structured dtype or recarray of ndim=2 index : str, array-like The name of the index column in *data*. If None, the default index is used. columns : list of str List of column names to include. Returns ------- DataFrame """ if data.ndim != 1 and data.ndim != 2: raise ValueError( f"records dimension expected 1 or 2 but found {data.ndim}" ) num_cols = len(data[0]) if columns is None and data.dtype.names is None: names = [i for i in range(num_cols)] elif data.dtype.names is not None: names = data.dtype.names else: if len(columns) != num_cols: raise ValueError( f"columns length expected {num_cols} " f"but found {len(columns)}" ) names = columns df = DataFrame() if data.ndim == 2: for i, k in enumerate(names): df._data[k] = column.as_column( data[:, i], nan_as_null=nan_as_null ) elif data.ndim == 1: for k in names: df._data[k] = column.as_column( data[k], nan_as_null=nan_as_null ) if index is None: df._index = RangeIndex(start=0, stop=len(data)) elif is_scalar(index): df._index = RangeIndex(start=0, stop=len(data)) df = df.set_index(index) else: df._index = as_index(index) return df @classmethod def _from_arrays(cls, data, index=None, columns=None, nan_as_null=False): """Convert a numpy/cupy array to DataFrame. Parameters ---------- data : numpy/cupy array of ndim 1 or 2, dimensions greater than 2 are not supported yet. index : Index or array-like Index to use for resulting frame. Will default to RangeIndex if no indexing information part of input data and no index provided. columns : list of str List of column names to include. Returns ------- DataFrame """ data = cupy.asarray(data) if data.ndim != 1 and data.ndim != 2: raise ValueError( f"records dimension expected 1 or 2 but found: {data.ndim}" ) if data.ndim == 2: num_cols = len(data[0]) else: # Since we validate ndim to be either 1 or 2 above, # this case can be assumed to be ndim == 1. num_cols = 1 if columns is None: names = [i for i in range(num_cols)] else: if len(columns) != num_cols: raise ValueError( f"columns length expected {num_cols} but " f"found {len(columns)}" ) names = columns df = cls() if data.ndim == 2: for i, k in enumerate(names): df._data[k] = column.as_column( data[:, i], nan_as_null=nan_as_null ) elif data.ndim == 1: df._data[names[0]] = column.as_column( data, nan_as_null=nan_as_null ) if index is None: df._index = RangeIndex(start=0, stop=len(data)) else: df._index = as_index(index) return df @classmethod def _from_columns(cls, cols, index=None, columns=None): """ Construct a DataFrame from a list of Columns """ if columns is not None: data = dict(zip(columns, cols)) else: data = dict(enumerate(cols)) return cls(data=data, index=index,) def quantile( self, q=0.5, axis=0, numeric_only=True, interpolation="linear", columns=None, exact=True, ): """ Return values at the given quantile. Parameters ---------- q : float or array-like 0 <= q <= 1, the quantile(s) to compute axis : int axis is a NON-FUNCTIONAL parameter numeric_only : bool, default True If False, the quantile of datetime and timedelta data will be computed as well. interpolation : {`linear`, `lower`, `higher`, `midpoint`, `nearest`} This parameter specifies the interpolation method to use, when the desired quantile lies between two data points i and j. Default ``linear``. columns : list of str List of column names to include. exact : boolean Whether to use approximate or exact quantile algorithm. Returns ------- Series or DataFrame If q is an array or numeric_only is set to False, a DataFrame will be returned where index is q, the columns are the columns of self, and the values are the quantile. If q is a float, a Series will be returned where the index is the columns of self and the values are the quantiles. Notes ----- One notable difference from Pandas is when DataFrame is of non-numeric types and result is expected to be a Series in case of Pandas. cuDF will return a DataFrame as it doesn't support mixed types under Series. """ if axis not in (0, None): raise NotImplementedError("axis is not implemented yet") if numeric_only: data_df = self.select_dtypes( include=[np.number], exclude=["datetime64", "timedelta64"] ) else: data_df = self if columns is None: columns = data_df._data.names result = DataFrame() for k in data_df._data.names: if k in columns: res = data_df[k].quantile( q, interpolation=interpolation, exact=exact, quant_index=False, ) if ( not isinstance( res, (numbers.Number, pd.Timestamp, pd.Timedelta) ) and len(res) == 0 ): res = column.column_empty_like( q, dtype=data_df[k].dtype, masked=True, newsize=len(q) ) result[k] = column.as_column(res) if isinstance(q, numbers.Number) and numeric_only: result = result.fillna(np.nan) result = result.iloc[0] result.index = as_index(data_df.columns) result.name = q return result else: q = list(map(float, [q] if isinstance(q, numbers.Number) else q)) result.index = q return result def quantiles(self, q=0.5, interpolation="nearest"): """ Return values at the given quantile. Parameters ---------- q : float or array-like 0 <= q <= 1, the quantile(s) to compute interpolation : {`lower`, `higher`, `nearest`} This parameter specifies the interpolation method to use, when the desired quantile lies between two data points i and j. Default 'nearest'. Returns ------- DataFrame """ if isinstance(q, numbers.Number): q_is_number = True q = [float(q)] elif pd.api.types.is_list_like(q): q_is_number = False else: msg = "`q` must be either a single element or list" raise TypeError(msg) result = self._quantiles(q, interpolation.upper()) if q_is_number: result = result.transpose() return Series( data=result._columns[0], index=result.index, name=q[0] ) else: result.index = as_index(q) return result def isin(self, values): """ Whether each element in the DataFrame is contained in values. Parameters ---------- values : iterable, Series, DataFrame or dict The result will only be true at a location if all the labels match. If values is a Series, that’s the index. If values is a dict, the keys must be the column names, which must match. If values is a DataFrame, then both the index and column labels must match. Returns ------- DataFrame: DataFrame of booleans showing whether each element in the DataFrame is contained in values. """ if isinstance(values, dict): result_df = DataFrame() for col in self._data.names: if col in values: val = values[col] result_df[col] = self._data[col].isin(val) else: result_df[col] = column.full( size=len(self), fill_value=False, dtype="bool" ) result_df.index = self.index return result_df elif isinstance(values, Series): values = values.reindex(self.index) result = DataFrame() for col in self._data.names: if isinstance( self[col]._column, cudf.core.column.CategoricalColumn ) and isinstance( values._column, cudf.core.column.CategoricalColumn ): res = self._data[col] == values._column result[col] = res elif ( isinstance( self[col]._column, cudf.core.column.CategoricalColumn ) or np.issubdtype(self[col].dtype, np.dtype("object")) ) or ( isinstance( values._column, cudf.core.column.CategoricalColumn ) or np.issubdtype(values.dtype, np.dtype("object")) ): result[col] = utils.scalar_broadcast_to(False, len(self)) else: result[col] = self._data[col] == values._column result.index = self.index return result elif isinstance(values, DataFrame): values = values.reindex(self.index) result = DataFrame() for col in self._data.names: if col in values.columns: result[col] = self._data[col] == values[col]._column else: result[col] = utils.scalar_broadcast_to(False, len(self)) result.index = self.index return result else: if not is_list_like(values): raise TypeError( f"only list-like or dict-like objects are " f"allowed to be passed to DataFrame.isin(), " f"you passed a " f"'{type(values).__name__}'" ) result_df = DataFrame() for col in self._data.names: result_df[col] = self._data[col].isin(values) result_df.index = self.index return result_df # # Stats # def _prepare_for_rowwise_op(self, method, skipna): """Prepare a DataFrame for CuPy-based row-wise operations. """ if method not in _cupy_nan_methods_map and any( col.nullable for col in self._columns ): msg = ( f"Row-wise operations to calculate '{method}' is not " f"currently support columns with null values. " f"Consider removing them with .dropna() " f"or using .fillna()." ) raise ValueError(msg) is_pure_dt = all(is_datetime_dtype(dt) for dt in self.dtypes) if not is_pure_dt: filtered = self.select_dtypes(include=[np.number, np.bool]) else: filtered = self.copy(deep=False) common_dtype = find_common_type(filtered.dtypes) if filtered._num_columns < self._num_columns: msg = ( "Row-wise operations currently only support int, float " "and bool dtypes. Non numeric columns are ignored." ) warnings.warn(msg) if not skipna and any(col.nullable for col in filtered._columns): mask = cudf.DataFrame( { name: filtered._data[name]._get_mask_as_column() if filtered._data[name].nullable else column.full(len(filtered._data[name]), True) for name in filtered._data.names } ) mask = mask.all(axis=1) else: mask = None coerced = filtered.astype(common_dtype, copy=False) if is_pure_dt: # Further convert into cupy friendly types coerced = coerced.astype("int64", copy=False) return coerced, mask, common_dtype def count(self, axis=0, level=None, numeric_only=False, **kwargs): """ Count ``non-NA`` cells for each column or row. The values ``None``, ``NaN``, ``NaT`` are considered ``NA``. Returns ------- Series For each column/row the number of non-NA/null entries. Notes ----- Parameters currently not supported are `axis`, `level`, `numeric_only`. Examples -------- >>> import cudf >>> import numpy as np >>> df = cudf.DataFrame({"Person": ... ["John", "Myla", "Lewis", "John", "Myla"], ... "Age": [24., np.nan, 21., 33, 26], ... "Single": [False, True, True, True, False]}) >>> df.count() Person 5 Age 4 Single 5 dtype: int64 """ if axis not in (0, "index", None): raise NotImplementedError("Only axis=0 is currently supported.") return self._apply_support_method( "count", axis=axis, level=level, numeric_only=numeric_only, **kwargs, ) def min( self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs, ): """ Return the minimum of the values in the DataFrame. Parameters ---------- axis: {index (0), columns(1)} Axis for the function to be applied on. skipna: bool, default True Exclude NA/null values when computing the result. level: int or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series. numeric_only: bool, default None Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Returns ------- Series Notes ----- Parameters currently not supported are `level`, `numeric_only`. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.min() a 1 b 7 dtype: int64 """ return self._apply_support_method( "min", axis=axis, skipna=skipna, level=level, numeric_only=numeric_only, **kwargs, ) def max( self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs, ): """ Return the maximum of the values in the DataFrame. Parameters ---------- axis: {index (0), columns(1)} Axis for the function to be applied on. skipna: bool, default True Exclude NA/null values when computing the result. level: int or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series. numeric_only: bool, default None Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Returns ------- Series Notes ----- Parameters currently not supported are `level`, `numeric_only`. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.max() a 4 b 10 dtype: int64 """ return self._apply_support_method( "max", axis=axis, skipna=skipna, level=level, numeric_only=numeric_only, **kwargs, ) def sum( self, axis=None, skipna=None, dtype=None, level=None, numeric_only=None, min_count=0, **kwargs, ): """ Return sum of the values in the DataFrame. Parameters ---------- axis: {index (0), columns(1)} Axis for the function to be applied on. skipna: bool, default True Exclude NA/null values when computing the result. dtype: data type Data type to cast the result to. min_count: int, default 0 The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA. The default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty Series is 1. Returns ------- Series Notes ----- Parameters currently not supported are `level`, `numeric_only`. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.sum() a 10 b 34 dtype: int64 """ return self._apply_support_method( "sum", axis=axis, skipna=skipna, dtype=dtype, level=level, numeric_only=numeric_only, min_count=min_count, **kwargs, ) def product( self, axis=None, skipna=None, dtype=None, level=None, numeric_only=None, min_count=0, **kwargs, ): """ Return product of the values in the DataFrame. Parameters ---------- axis: {index (0), columns(1)} Axis for the function to be applied on. skipna: bool, default True Exclude NA/null values when computing the result. dtype: data type Data type to cast the result to. min_count: int, default 0 The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA. The default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty Series is 1. Returns ------- Series Notes ----- Parameters currently not supported are level`, `numeric_only`. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.product() a 24 b 5040 dtype: int64 """ return self._apply_support_method( "prod", axis=axis, skipna=skipna, dtype=dtype, level=level, numeric_only=numeric_only, min_count=min_count, **kwargs, ) def prod( self, axis=None, skipna=None, dtype=None, level=None, numeric_only=None, min_count=0, **kwargs, ): """ Return product of the values in the DataFrame. Parameters ---------- axis: {index (0), columns(1)} Axis for the function to be applied on. skipna: bool, default True Exclude NA/null values when computing the result. dtype: data type Data type to cast the result to. min_count: int, default 0 The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA. The default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty Series is 1. Returns ------- scalar Notes ----- Parameters currently not supported are `level`, `numeric_only`. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.prod() a 24 b 5040 dtype: int64 """ return self.product( axis=axis, skipna=skipna, dtype=dtype, level=level, numeric_only=numeric_only, min_count=min_count, **kwargs, ) def cummin(self, axis=None, skipna=True, *args, **kwargs): """ Return cumulative minimum of the DataFrame. Parameters ---------- skipna: bool, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. Returns ------- DataFrame Notes ----- Parameters currently not supported is `axis` Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.cummin() a b 0 1 7 1 1 7 2 1 7 3 1 7 """ if axis not in (0, "index", None): raise NotImplementedError("Only axis=0 is currently supported.") return self._apply_support_method( "cummin", axis=axis, skipna=skipna, *args, **kwargs ) def cummax(self, axis=None, skipna=True, *args, **kwargs): """ Return cumulative maximum of the DataFrame. Parameters ---------- skipna: bool, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. Returns ------- DataFrame Notes ----- Parameters currently not supported is `axis` Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.cummax() a b 0 1 7 1 2 8 2 3 9 3 4 10 """ if axis not in (0, "index", None): raise NotImplementedError("Only axis=0 is currently supported.") return self._apply_support_method( "cummax", axis=axis, skipna=skipna, *args, **kwargs ) def cumsum(self, axis=None, skipna=True, *args, **kwargs): """ Return cumulative sum of the DataFrame. Parameters ---------- skipna: bool, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. Returns ------- DataFrame Notes ----- Parameters currently not supported is `axis` Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> s.cumsum() a b 0 1 7 1 3 15 2 6 24 3 10 34 """ if axis not in (0, "index", None): raise NotImplementedError("Only axis=0 is currently supported.") return self._apply_support_method( "cumsum", axis=axis, skipna=skipna, *args, **kwargs ) def cumprod(self, axis=None, skipna=True, *args, **kwargs): """ Return cumulative product of the DataFrame. Parameters ---------- skipna: bool, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. Returns ------- DataFrame Notes ----- Parameters currently not supported is `axis` Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> s.cumprod() a b 0 1 7 1 2 56 2 6 504 3 24 5040 """ if axis not in (0, "index", None): raise NotImplementedError("Only axis=0 is currently supported.") return self._apply_support_method( "cumprod", axis=axis, skipna=skipna, *args, **kwargs ) def mean( self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs ): """ Return the mean of the values for the requested axis. Parameters ---------- axis : {0 or 'index', 1 or 'columns'} Axis for the function to be applied on. skipna : bool, default True Exclude NA/null values when computing the result. level : int or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series. numeric_only : bool, default None Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. **kwargs Additional keyword arguments to be passed to the function. Returns ------- mean : Series or DataFrame (if level specified) Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.mean() a 2.5 b 8.5 dtype: float64 """ return self._apply_support_method( "mean", axis=axis, skipna=skipna, level=level, numeric_only=numeric_only, **kwargs, ) def mode(self, axis=0, numeric_only=False, dropna=True): """ Get the mode(s) of each element along the selected axis. The mode of a set of values is the value that appears most often. It can be multiple values. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to iterate over while searching for the mode: - 0 or 'index' : get mode of each column - 1 or 'columns' : get mode of each row. numeric_only : bool, default False If True, only apply to numeric columns. dropna : bool, default True Don't consider counts of NA/NaN/NaT. Returns ------- DataFrame The modes of each column or row. See Also -------- cudf.core.series.Series.mode : Return the highest frequency value in a Series. cudf.core.series.Series.value_counts : Return the counts of values in a Series. Notes ----- ``axis`` parameter is currently not supported. Examples -------- >>> import cudf >>> df = cudf.DataFrame({ ... "species": ["bird", "mammal", "arthropod", "bird"], ... "legs": [2, 4, 8, 2], ... "wings": [2.0, None, 0.0, None] ... }) >>> df species legs wings 0 bird 2 2.0 1 mammal 4 <NA> 2 arthropod 8 0.0 3 bird 2 <NA> By default, missing values are not considered, and the mode of wings are both 0 and 2. The second row of species and legs contains ``NA``, because they have only one mode, but the DataFrame has two rows. >>> df.mode() species legs wings 0 bird 2 0.0 1 <NA> <NA> 2.0 Setting ``dropna=False``, ``NA`` values are considered and they can be the mode (like for wings). >>> df.mode(dropna=False) species legs wings 0 bird 2 <NA> Setting ``numeric_only=True``, only the mode of numeric columns is computed, and columns of other types are ignored. >>> df.mode(numeric_only=True) legs wings 0 2 0.0 1 <NA> 2.0 """ if axis not in (0, "index"): raise NotImplementedError("Only axis=0 is currently supported") if numeric_only: data_df = self.select_dtypes( include=[np.number], exclude=["datetime64", "timedelta64"] ) else: data_df = self mode_results = [ data_df[col].mode(dropna=dropna) for col in data_df._data ] if len(mode_results) == 0: df = DataFrame(index=self.index) return df df = cudf.concat(mode_results, axis=1) if isinstance(df, Series): df = df.to_frame() df.columns = data_df.columns return df def std( self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs, ): """ Return sample standard deviation of the DataFrame. Normalized by N-1 by default. This can be changed using the `ddof` argument Parameters ---------- axis: {index (0), columns(1)} Axis for the function to be applied on. skipna: bool, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. ddof: int, default 1 Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. Returns ------- Series Notes ----- Parameters currently not supported are `level` and `numeric_only` Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.std() a 1.290994 b 1.290994 dtype: float64 """ return self._apply_support_method( "std", axis=axis, skipna=skipna, level=level, ddof=ddof, numeric_only=numeric_only, **kwargs, ) def var( self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs, ): """ Return unbiased variance of the DataFrame. Normalized by N-1 by default. This can be changed using the ddof argument Parameters ---------- axis: {index (0), columns(1)} Axis for the function to be applied on. skipna: bool, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. ddof: int, default 1 Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. Returns ------- scalar Notes ----- Parameters currently not supported are `level` and `numeric_only` Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.var() a 1.666667 b 1.666667 dtype: float64 """ return self._apply_support_method( "var", axis=axis, skipna=skipna, level=level, ddof=ddof, numeric_only=numeric_only, **kwargs, ) def kurtosis( self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs ): """ Return Fisher's unbiased kurtosis of a sample. Kurtosis obtained using Fisher’s definition of kurtosis (kurtosis of normal == 0.0). Normalized by N-1. Parameters ---------- skipna: bool, default True Exclude NA/null values when computing the result. Returns ------- Series Notes ----- Parameters currently not supported are `axis`, `level` and `numeric_only` Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.kurt() a -1.2 b -1.2 dtype: float64 """ if axis not in (0, "index", None): raise NotImplementedError("Only axis=0 is currently supported.") if numeric_only not in (None, True): msg = "Kurtosis only supports int, float, and bool dtypes." raise NotImplementedError(msg) self = self.select_dtypes(include=[np.number, np.bool]) return self._apply_support_method( "kurtosis", axis=axis, skipna=skipna, level=level, numeric_only=numeric_only, **kwargs, ) # Alias for kurtosis. kurt = kurtosis def skew( self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs ): """ Return unbiased Fisher-Pearson skew of a sample. Parameters ---------- skipna: bool, default True Exclude NA/null values when computing the result. Returns ------- Series Notes ----- Parameters currently not supported are `axis`, `level` and `numeric_only` Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [3, 2, 3, 4], 'b': [7, 8, 10, 10]}) >>> df.skew() a 0.00000 b -0.37037 dtype: float64 """ if axis not in (0, "index", None): raise NotImplementedError("Only axis=0 is currently supported.") if numeric_only not in (None, True): msg = "Skew only supports int, float, and bool dtypes." raise NotImplementedError(msg) self = self.select_dtypes(include=[np.number, np.bool]) return self._apply_support_method( "skew", axis=axis, skipna=skipna, level=level, numeric_only=numeric_only, **kwargs, ) def all(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): """ Return whether all elements are True in DataFrame. Parameters ---------- skipna: bool, default True Exclude NA/null values. If the entire row/column is NA and skipna is True, then the result will be True, as for an empty row/column. If skipna is False, then NA are treated as True, because these are not equal to zero. Returns ------- Series Notes ----- Parameters currently not supported are `axis`, `bool_only`, `level`. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [3, 2, 3, 4], 'b': [7, 0, 10, 10]}) >>> df.all() a True b False dtype: bool """ if bool_only: return self.select_dtypes(include="bool")._apply_support_method( "all", axis=axis, bool_only=bool_only, skipna=skipna, level=level, **kwargs, ) return self._apply_support_method( "all", axis=axis, bool_only=bool_only, skipna=skipna, level=level, **kwargs, ) def any(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): """ Return whether any elements is True in DataFrame. Parameters ---------- skipna: bool, default True Exclude NA/null values. If the entire row/column is NA and skipna is True, then the result will be False, as for an empty row/column. If skipna is False, then NA are treated as True, because these are not equal to zero. Returns ------- Series Notes ----- Parameters currently not supported are `axis`, `bool_only`, `level`. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [3, 2, 3, 4], 'b': [7, 0, 10, 10]}) >>> df.any() a True b True dtype: bool """ if bool_only: return self.select_dtypes(include="bool")._apply_support_method( "any", axis=axis, bool_only=bool_only, skipna=skipna, level=level, **kwargs, ) return self._apply_support_method( "any", axis=axis, bool_only=bool_only, skipna=skipna, level=level, **kwargs, ) def _apply_support_method(self, method, axis=0, *args, **kwargs): assert axis in (None, 0, 1) if axis in (None, 0): result = [ getattr(self[col], method)(*args, **kwargs) for col in self._data.names ] if isinstance(result[0], Series): support_result = result result = DataFrame(index=support_result[0].index) for idx, col in enumerate(self._data.names): result[col] = support_result[idx] else: result = Series(result) result = result.set_index(self._data.names) return result elif axis == 1: # for dask metadata compatibility skipna = kwargs.pop("skipna", None) if method not in _cupy_nan_methods_map and skipna not in ( None, True, 1, ): raise NotImplementedError( f"Row-wise operation to calculate '{method}'" f" currently do not support `skipna=False`." ) level = kwargs.pop("level", None) if level not in (None,): raise NotImplementedError( "Row-wise operations currently do not support `level`." ) numeric_only = kwargs.pop("numeric_only", None) if numeric_only not in (None, True): raise NotImplementedError( "Row-wise operations currently do not " "support `numeric_only=False`." ) min_count = kwargs.pop("min_count", None) if min_count not in (None, 0): raise NotImplementedError( "Row-wise operations currently do not " "support `min_count`." ) bool_only = kwargs.pop("bool_only", None) if bool_only not in (None, True): raise NotImplementedError( "Row-wise operations currently do not " "support `bool_only`." ) prepared, mask, common_dtype = self._prepare_for_rowwise_op( method, skipna ) for col in prepared._data.names: if prepared._data[col].nullable: prepared._data[col] = ( prepared._data[col] .astype( cudf.utils.dtypes.get_min_float_dtype( prepared._data[col] ) if not is_datetime_dtype(common_dtype) else np.dtype("float64") ) .fillna(np.nan) ) arr = cupy.asarray(prepared.as_gpu_matrix()) if skipna is not False and method in _cupy_nan_methods_map: method = _cupy_nan_methods_map[method] result = getattr(cupy, method)(arr, axis=1, **kwargs) if result.ndim == 1: type_coerced_methods = { "count", "min", "max", "sum", "prod", "cummin", "cummax", "cumsum", "cumprod", } result_dtype = ( common_dtype if method in type_coerced_methods or is_datetime_dtype(common_dtype) else None ) result = column.as_column(result, dtype=result_dtype) if mask is not None: result = result.set_mask( cudf._lib.transform.bools_to_mask(mask._column) ) return Series(result, index=self.index, dtype=result_dtype,) else: result_df = DataFrame(result).set_index(self.index) result_df.columns = prepared.columns return result_df def _columns_view(self, columns): """ Return a subset of the DataFrame's columns as a view. """ result_columns = OrderedDict({}) for col in columns: result_columns[col] = self._data[col] return DataFrame(result_columns, index=self.index) def select_dtypes(self, include=None, exclude=None): """Return a subset of the DataFrame’s columns based on the column dtypes. Parameters ---------- include : str or list which columns to include based on dtypes exclude : str or list which columns to exclude based on dtypes Returns ------- DataFrame The subset of the frame including the dtypes in ``include`` and excluding the dtypes in ``exclude``. Raises ------ ValueError - If both of ``include`` and ``exclude`` are empty - If ``include`` and ``exclude`` have overlapping elements Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2] * 3, ... 'b': [True, False] * 3, ... 'c': [1.0, 2.0] * 3}) >>> df a b c 0 1 True 1.0 1 2 False 2.0 2 1 True 1.0 3 2 False 2.0 4 1 True 1.0 5 2 False 2.0 >>> df.select_dtypes(include='bool') b 0 True 1 False 2 True 3 False 4 True 5 False >>> df.select_dtypes(include=['float64']) c 0 1.0 1 2.0 2 1.0 3 2.0 4 1.0 5 2.0 >>> df.select_dtypes(exclude=['int']) b c 0 True 1.0 1 False 2.0 2 True 1.0 3 False 2.0 4 True 1.0 5 False 2.0 """ # code modified from: # https://github.com/pandas-dev/pandas/blob/master/pandas/core/frame.py#L3196 if not isinstance(include, (list, tuple)): include = (include,) if include is not None else () if not isinstance(exclude, (list, tuple)): exclude = (exclude,) if exclude is not None else () df = DataFrame(index=self.index) # cudf_dtype_from_pydata_dtype can distinguish between # np.float and np.number selection = tuple(map(frozenset, (include, exclude))) if not any(selection): raise ValueError( "at least one of include or exclude must be nonempty" ) include, exclude = map( lambda x: frozenset(map(cudf_dtype_from_pydata_dtype, x)), selection, ) # can't both include AND exclude! if not include.isdisjoint(exclude): raise ValueError( f"include and exclude overlap on {(include & exclude)}" ) # include all subtypes include_subtypes = set() for dtype in self.dtypes: for i_dtype in include: # category handling if is_categorical_dtype(i_dtype): include_subtypes.add(i_dtype) elif issubclass(dtype.type, i_dtype): include_subtypes.add(dtype.type) # exclude all subtypes exclude_subtypes = set() for dtype in self.dtypes: for e_dtype in exclude: # category handling if is_categorical_dtype(e_dtype): exclude_subtypes.add(e_dtype) elif issubclass(dtype.type, e_dtype): exclude_subtypes.add(dtype.type) include_all = set( [cudf_dtype_from_pydata_dtype(d) for d in self.dtypes] ) if include: inclusion = include_all & include_subtypes elif exclude: inclusion = include_all else: inclusion = set() # remove all exclude types inclusion = inclusion - exclude_subtypes for k, col in self._data.items(): infered_type = cudf_dtype_from_pydata_dtype(col.dtype) if infered_type in inclusion: df.insert(len(df._data), k, col) return df @ioutils.doc_to_parquet() def to_parquet(self, path, *args, **kwargs): """{docstring}""" from cudf.io import parquet as pq return pq.to_parquet(self, path, *args, **kwargs) @ioutils.doc_to_feather() def to_feather(self, path, *args, **kwargs): """{docstring}""" from cudf.io import feather as feather feather.to_feather(self, path, *args, **kwargs) @ioutils.doc_to_json() def to_json(self, path_or_buf=None, *args, **kwargs): """{docstring}""" from cudf.io import json as json return json.to_json(self, path_or_buf=path_or_buf, *args, **kwargs) @ioutils.doc_to_hdf() def to_hdf(self, path_or_buf, key, *args, **kwargs): """{docstring}""" from cudf.io import hdf as hdf hdf.to_hdf(path_or_buf, key, self, *args, **kwargs) @ioutils.doc_to_dlpack() def to_dlpack(self): """{docstring}""" from cudf.io import dlpack as dlpack return dlpack.to_dlpack(self) @ioutils.doc_dataframe_to_csv() def to_csv( self, path_or_buf=None, sep=",", na_rep="", columns=None, header=True, index=True, line_terminator="\n", chunksize=None, ): """{docstring}""" from cudf.io import csv as csv return csv.to_csv( self, path_or_buf=path_or_buf, sep=sep, na_rep=na_rep, columns=columns, header=header, index=index, line_terminator=line_terminator, chunksize=chunksize, ) @ioutils.doc_to_orc() def to_orc(self, fname, compression=None, *args, **kwargs): """{docstring}""" from cudf.io import orc as orc orc.to_orc(self, fname, compression, *args, **kwargs) def stack(self, level=-1, dropna=True): """Stack the prescribed level(s) from columns to index Return a reshaped Series Parameters ---------- dropna : bool, default True Whether to drop rows in the resulting Series with missing values. Returns ------- The stacked cudf.Series Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a':[0,1,3], 'b':[1,2,4]}) >>> df.stack() 0 a 0 b 1 1 a 1 b 2 2 a 3 b 4 dtype: int64 """ assert level in (None, -1) repeated_index = self.index.repeat(self.shape[1]) name_index = Frame({0: self._column_names}).tile(self.shape[0]) new_index = list(repeated_index._columns) + [name_index._columns[0]] new_index = cudf.core.multiindex.MultiIndex.from_frame( DataFrame(dict(zip(range(0, len(new_index)), new_index))) ) # Collect datatypes and cast columns as that type common_type = np.result_type(*self.dtypes) homogenized = DataFrame( { c: ( self._data[c].astype(common_type) if not np.issubdtype(self._data[c].dtype, common_type) else self._data[c] ) for c in self._data } ) data_col = libcudf.reshape.interleave_columns(homogenized) result = Series(data=data_col, index=new_index) if dropna: return result.dropna() else: return result def cov(self, **kwargs): """Compute the covariance matrix of a DataFrame. Parameters ---------- **kwargs Keyword arguments to be passed to cupy.cov Returns ------- cov : DataFrame """ cov = cupy.cov(self.values, rowvar=False) df = DataFrame(cupy.asfortranarray(cov)).set_index(self.columns) df.columns = self.columns return df def corr(self): """Compute the correlation matrix of a DataFrame. """ corr = cupy.corrcoef(self.values, rowvar=False) df = DataFrame(cupy.asfortranarray(corr)).set_index(self.columns) df.columns = self.columns return df def to_dict(self, orient="dict", into=dict): raise TypeError( "cuDF does not support conversion to host memory " "via `to_dict()` method. Consider using " "`.to_pandas().to_dict()` to construct a Python dictionary." ) def keys(self): """ Get the columns. This is index for Series, columns for DataFrame. Returns ------- Index Columns of DataFrame. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'one' : [1, 2, 3], 'five' : ['a', 'b', 'c']}) >>> df one five 0 1 a 1 2 b 2 3 c >>> df.keys() Index(['one', 'five'], dtype='object') >>> df = cudf.DataFrame(columns=[0, 1, 2, 3]) >>> df Empty DataFrame Columns: [0, 1, 2, 3] Index: [] >>> df.keys() Int64Index([0, 1, 2, 3], dtype='int64') """ return self.columns def itertuples(self, index=True, name="Pandas"): raise TypeError( "cuDF does not support iteration of DataFrame " "via itertuples. Consider using " "`.to_pandas().itertuples()` " "if you wish to iterate over namedtuples." ) def iterrows(self): raise TypeError( "cuDF does not support iteration of DataFrame " "via iterrows. Consider using " "`.to_pandas().iterrows()` " "if you wish to iterate over each row." ) def append( self, other, ignore_index=False, verify_integrity=False, sort=False ): """ Append rows of `other` to the end of caller, returning a new object. Columns in `other` that are not in the caller are added as new columns. Parameters ---------- other : DataFrame or Series/dict-like object, or list of these The data to append. ignore_index : bool, default False If True, do not use the index labels. sort : bool, default False Sort columns ordering if the columns of `self` and `other` are not aligned. verify_integrity : bool, default False This Parameter is currently not supported. Returns ------- DataFrame See Also -------- cudf.core.reshape.concat : General function to concatenate DataFrame or objects. Notes ----- If a list of dict/series is passed and the keys are all contained in the DataFrame's index, the order of the columns in the resulting DataFrame will be unchanged. Iteratively appending rows to a cudf DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once. `verify_integrity` parameter is not supported yet. Examples -------- >>> import cudf >>> df = cudf.DataFrame([[1, 2], [3, 4]], columns=list('AB')) >>> df A B 0 1 2 1 3 4 >>> df2 = cudf.DataFrame([[5, 6], [7, 8]], columns=list('AB')) >>> df2 A B 0 5 6 1 7 8 >>> df.append(df2) A B 0 1 2 1 3 4 0 5 6 1 7 8 With `ignore_index` set to True: >>> df.append(df2, ignore_index=True) A B 0 1 2 1 3 4 2 5 6 3 7 8 The following, while not recommended methods for generating DataFrames, show two ways to generate a DataFrame from multiple data sources. Less efficient: >>> df = cudf.DataFrame(columns=['A']) >>> for i in range(5): ... df = df.append({'A': i}, ignore_index=True) >>> df A 0 0 1 1 2 2 3 3 4 4 More efficient than above: >>> cudf.concat([cudf.DataFrame([i], columns=['A']) for i in range(5)], ... ignore_index=True) A 0 0 1 1 2 2 3 3 4 4 """ if verify_integrity not in (None, False): raise NotImplementedError( "verify_integrity parameter is not supported yet." ) if isinstance(other, dict): if not ignore_index: raise TypeError("Can only append a dict if ignore_index=True") other = DataFrame(other) result = cudf.concat( [self, other], ignore_index=ignore_index, sort=sort ) return result elif isinstance(other, Series): if other.name is None and not ignore_index: raise TypeError( "Can only append a Series if ignore_index=True " "or if the Series has a name" ) current_cols = self.columns combined_columns = other.index.to_pandas() if len(current_cols): if cudf.utils.dtypes.is_mixed_with_object_dtype( current_cols, combined_columns ): raise TypeError( "cudf does not support mixed types, please type-cast " "the column index of dataframe and index of series " "to same dtypes." ) combined_columns = current_cols.union( combined_columns, sort=False ) if sort: combined_columns = combined_columns.sort_values() other = other.reindex(combined_columns, copy=False).to_frame().T if not current_cols.equals(combined_columns): self = self.reindex(columns=combined_columns) elif isinstance(other, list): if not other: pass elif not isinstance(other[0], cudf.DataFrame): other = cudf.DataFrame(other) if (self.columns.get_indexer(other.columns) >= 0).all(): other = other.reindex(columns=self.columns) if is_list_like(other): to_concat = [self, *other] else: to_concat = [self, other] return cudf.concat(to_concat, ignore_index=ignore_index, sort=sort) @copy_docstring(reshape.pivot) def pivot(self, index, columns, values=None): return cudf.core.reshape.pivot( self, index=index, columns=columns, values=values ) @copy_docstring(reshape.unstack) def unstack(self, level=-1, fill_value=None): return cudf.core.reshape.unstack( self, level=level, fill_value=fill_value ) def equals(self, other): if not isinstance(other, DataFrame): return False for self_name, other_name in zip(self._data.names, other._data.names): if self_name != other_name: return False return super().equals(other) _accessors = set() def from_pandas(obj, nan_as_null=None): """ Convert certain Pandas objects into the cudf equivalent. Supports DataFrame, Series, Index, or MultiIndex. Returns ------- DataFrame/Series/Index/MultiIndex Return type depends on the passed input. Raises ------ TypeError for invalid input type. Examples -------- >>> import cudf >>> import pandas as pd >>> data = [[0, 1], [1, 2], [3, 4]] >>> pdf = pd.DataFrame(data, columns=['a', 'b'], dtype=int) >>> pdf a b 0 0 1 1 1 2 2 3 4 >>> gdf = cudf.from_pandas(pdf) >>> gdf a b 0 0 1 1 1 2 2 3 4 >>> type(gdf) <class 'cudf.core.dataframe.DataFrame'> >>> type(pdf) <class 'pandas.core.frame.DataFrame'> Converting a Pandas Series to cuDF Series: >>> psr = pd.Series(['a', 'b', 'c', 'd'], name='apple') >>> psr 0 a 1 b 2 c 3 d Name: apple, dtype: object >>> gsr = cudf.from_pandas(psr) >>> gsr 0 a 1 b 2 c 3 d Name: apple, dtype: object >>> type(gsr) <class 'cudf.core.series.Series'> >>> type(psr) <class 'pandas.core.series.Series'> Converting a Pandas Index to cuDF Index: >>> pidx = pd.Index([1, 2, 10, 20]) >>> pidx Int64Index([1, 2, 10, 20], dtype='int64') >>> gidx = cudf.from_pandas(pidx) >>> gidx Int64Index([1, 2, 10, 20], dtype='int64') >>> type(gidx) <class 'cudf.core.index.Int64Index'> >>> type(pidx) <class 'pandas.core.indexes.numeric.Int64Index'> Converting a Pandas MultiIndex to cuDF MultiIndex: >>> pmidx = pd.MultiIndex( ... levels=[[1, 3, 4, 5], [1, 2, 5]], ... codes=[[0, 0, 1, 2, 3], [0, 2, 1, 1, 0]], ... names=["x", "y"], ... ) >>> pmidx MultiIndex([(1, 1), (1, 5), (3, 2), (4, 2), (5, 1)], names=['x', 'y']) >>> gmidx = cudf.from_pandas(pmidx) >>> gmidx MultiIndex([(1, 1), (1, 5), (3, 2), (4, 2), (5, 1)], names=['x', 'y']) >>> type(gmidx) <class 'cudf.core.multiindex.MultiIndex'> >>> type(pmidx) <class 'pandas.core.indexes.multi.MultiIndex'> """ if isinstance(obj, pd.DataFrame): return DataFrame.from_pandas(obj, nan_as_null=nan_as_null) elif isinstance(obj, pd.Series): return Series.from_pandas(obj, nan_as_null=nan_as_null) elif isinstance(obj, pd.MultiIndex): return cudf.MultiIndex.from_pandas(obj, nan_as_null=nan_as_null) elif isinstance(obj, pd.RangeIndex): return cudf.core.index.RangeIndex( start=obj.start, stop=obj.stop, step=obj.step, name=obj.name ) elif isinstance(obj, pd.Index): return cudf.Index.from_pandas(obj, nan_as_null=nan_as_null) elif isinstance(obj, pd.CategoricalDtype): return cudf.CategoricalDtype.from_pandas(obj) else: raise TypeError( "from_pandas only accepts Pandas Dataframes, Series, " "Index, RangeIndex and MultiIndex objects. " "Got %s" % type(obj) ) def merge(left, right, *args, **kwargs): return left.merge(right, *args, **kwargs) # a bit of fanciness to inject docstring with left parameter merge_doc = DataFrame.merge.__doc__ idx = merge_doc.find("right") merge.__doc__ = "".join( [merge_doc[:idx], "\n\tleft : DataFrame\n\t", merge_doc[idx:]] ) def _align_indices(lhs, rhs): """ Internal util to align the indices of two DataFrames. Returns a tuple of the aligned dataframes, or the original arguments if the indices are the same, or if rhs isn't a DataFrame. """ lhs_out, rhs_out = lhs, rhs if isinstance(rhs, DataFrame) and not lhs.index.equals(rhs.index): df = lhs.merge( rhs, sort=True, how="outer", left_index=True, right_index=True, suffixes=("_x", "_y"), ) df = df.sort_index() lhs_out = DataFrame(index=df.index) rhs_out = DataFrame(index=df.index) common = set(lhs.columns) & set(rhs.columns) common_x = set(["{}_x".format(x) for x in common]) common_y = set(["{}_y".format(x) for x in common]) for col in df.columns: if col in common_x: lhs_out[col[:-2]] = df[col] elif col in common_y: rhs_out[col[:-2]] = df[col] elif col in lhs: lhs_out[col] = df[col] elif col in rhs: rhs_out[col] = df[col] return lhs_out, rhs_out def _setitem_with_dataframe(input_df, replace_df, input_cols=None, mask=None): """ This function sets item dataframes relevant columns with replacement df :param input_df: Dataframe to be modified inplace :param replace_df: Replacement DataFrame to replace values with :param input_cols: columns to replace in the input dataframe :param mask: boolean mask in case of masked replacing """ if input_cols is None: input_cols = input_df.columns if len(input_cols) != len(replace_df.columns): raise ValueError( "Number of Input Columns must be same replacement Dataframe" ) for col_1, col_2 in zip(input_cols, replace_df.columns): if col_1 in input_df.columns: if mask is not None: input_df._data[col_1][mask] = column.as_column( replace_df[col_2] ) else: input_df._data[col_1] = column.as_column(replace_df[col_2]) else: if mask is not None: raise ValueError("Can not insert new column with a bool mask") else: # handle append case input_df.insert(len(input_df._data), col_1, replace_df[col_2]) def extract_col(df, col): """ Extract column from dataframe `df` with their name `col`. If `col` is index and there are no columns with name `index`, then this will return index column. """ try: return df._data[col] except KeyError: if ( col == "index" and col not in df.index._data and not isinstance(df.index, cudf.MultiIndex) ): return df.index._data.columns[0] return df.index._data[col] def _get_union_of_indices(indexes): if len(indexes) == 1: return indexes[0] else: merged_index = cudf.core.Index._concat(indexes) merged_index = merged_index.drop_duplicates() _, inds = merged_index._values.sort_by_values() return merged_index.take(inds) def _get_union_of_series_names(series_list): names_list = [] unnamed_count = 0 for series in series_list: if series.name is None: names_list.append(f"Unnamed {unnamed_count}") unnamed_count += 1 else: names_list.append(series.name) if unnamed_count == len(series_list): names_list = [*range(len(series_list))] return names_list def _drop_columns(df, columns, errors): for c in columns: try: df._drop_column(c) except KeyError as e: if errors == "ignore": pass else: raise e def _get_host_unique(array): if isinstance( array, (cudf.Series, cudf.Index, cudf.core.column.ColumnBase) ): return array.unique.to_pandas() elif isinstance(array, (str, numbers.Number)): return [array] else: return set(array)
# Copyright (c) 2018-2020, NVIDIA CORPORATION. from __future__ import division import inspect import itertools import numbers import pickle import sys import warnings from collections import OrderedDict, defaultdict from collections.abc import Iterable, Mapping, Sequence import cupy import numpy as np import pandas as pd import pyarrow as pa from numba import cuda from nvtx import annotate from pandas._config import get_option from pandas.api.types import is_dict_like from pandas.io.formats import console from pandas.io.formats.printing import pprint_thing import cudf from cudf import _lib as libcudf from cudf._lib.null_mask import MaskState, create_null_mask from cudf.core import column, reshape from cudf.core.abc import Serializable from cudf.core.column import as_column, column_empty from cudf.core.column_accessor import ColumnAccessor from cudf.core.frame import Frame from cudf.core.groupby.groupby import DataFrameGroupBy from cudf.core.index import Index, RangeIndex, as_index from cudf.core.indexing import _DataFrameIlocIndexer, _DataFrameLocIndexer from cudf.core.series import Series from cudf.core.window import Rolling from cudf.utils import applyutils, docutils, ioutils, queryutils, utils from cudf.utils.docutils import copy_docstring from cudf.utils.dtypes import ( cudf_dtype_from_pydata_dtype, find_common_type, is_categorical_dtype, is_column_like, is_datetime_dtype, is_list_dtype, is_list_like, is_scalar, is_string_dtype, is_struct_dtype, numeric_normalize_types, ) from cudf.utils.utils import OrderedColumnDict def _unique_name(existing_names, suffix="_unique_name"): ret = suffix i = 1 while ret in existing_names: ret = "%s_%d" % (suffix, i) i += 1 return ret def _reverse_op(fn): return { "add": "radd", "radd": "add", "sub": "rsub", "rsub": "sub", "mul": "rmul", "rmul": "mul", "mod": "rmod", "rmod": "mod", "pow": "rpow", "rpow": "pow", "floordiv": "rfloordiv", "rfloordiv": "floordiv", "truediv": "rtruediv", "rtruediv": "truediv", "__add__": "__radd__", "__radd__": "__add__", "__sub__": "__rsub__", "__rsub__": "__sub__", "__mul__": "__rmul__", "__rmul__": "__mul__", "__mod__": "__rmod__", "__rmod__": "__mod__", "__pow__": "__rpow__", "__rpow__": "__pow__", "__floordiv__": "__rfloordiv__", "__rfloordiv__": "__floordiv__", "__truediv__": "__rtruediv__", "__rtruediv__": "__truediv__", }[fn] _cupy_nan_methods_map = { "min": "nanmin", "max": "nanmax", "sum": "nansum", "prod": "nanprod", "mean": "nanmean", "std": "nanstd", "var": "nanvar", } class DataFrame(Frame, Serializable): _internal_names = {"_data", "_index"} @annotate("DATAFRAME_INIT", color="blue", domain="cudf_python") def __init__(self, data=None, index=None, columns=None, dtype=None): """ A GPU Dataframe object. Parameters ---------- data : array-like, Iterable, dict, or DataFrame. Dict can contain Series, arrays, constants, or list-like objects. index : Index or array-like Index to use for resulting frame. Will default to RangeIndex if no indexing information part of input data and no index provided. columns : Index or array-like Column labels to use for resulting frame. Will default to RangeIndex (0, 1, 2, …, n) if no column labels are provided. dtype : dtype, default None Data type to force. Only a single dtype is allowed. If None, infer. Examples -------- Build dataframe with ``__setitem__``: >>> import cudf >>> df = cudf.DataFrame() >>> df['key'] = [0, 1, 2, 3, 4] >>> df['val'] = [float(i + 10) for i in range(5)] # insert column >>> df key val 0 0 10.0 1 1 11.0 2 2 12.0 3 3 13.0 4 4 14.0 Build DataFrame via dict of columns: >>> import numpy as np >>> from datetime import datetime, timedelta >>> t0 = datetime.strptime('2018-10-07 12:00:00', '%Y-%m-%d %H:%M:%S') >>> n = 5 >>> df = cudf.DataFrame({ ... 'id': np.arange(n), ... 'datetimes': np.array( ... [(t0+ timedelta(seconds=x)) for x in range(n)]) ... }) >>> df id datetimes 0 0 2018-10-07T12:00:00.000 1 1 2018-10-07T12:00:01.000 2 2 2018-10-07T12:00:02.000 3 3 2018-10-07T12:00:03.000 4 4 2018-10-07T12:00:04.000 Build DataFrame via list of rows as tuples: >>> df = cudf.DataFrame([ ... (5, "cats", "jump", np.nan), ... (2, "dogs", "dig", 7.5), ... (3, "cows", "moo", -2.1, "occasionally"), ... ]) >>> df 0 1 2 3 4 0 5 cats jump <NA> <NA> 1 2 dogs dig 7.5 <NA> 2 3 cows moo -2.1 occasionally Convert from a Pandas DataFrame: >>> import pandas as pd >>> pdf = pd.DataFrame({'a': [0, 1, 2, 3],'b': [0.1, 0.2, None, 0.3]}) >>> pdf a b 0 0 0.1 1 1 0.2 2 2 NaN 3 3 0.3 >>> df = cudf.from_pandas(pdf) >>> df a b 0 0 0.1 1 1 0.2 2 2 <NA> 3 3 0.3 """ super().__init__() if isinstance(columns, (Series, cudf.Index)): columns = columns.to_pandas() if isinstance(data, ColumnAccessor): if index is None: index = as_index(range(data.nrows)) else: index = as_index(index) self._index = index if columns is not None: self._data = data self._reindex(columns=columns, deep=True, inplace=True) else: self._data = data elif isinstance(data, (DataFrame, pd.DataFrame)): if isinstance(data, pd.DataFrame): data = self.from_pandas(data) if index is not None: if not data.index.equals(index): data = data.reindex(index) index = data._index else: index = as_index(index) else: index = data._index self._index = index if columns is not None: self._data = data._data self._reindex( columns=columns, index=index, deep=False, inplace=True ) else: self._data = data._data self.columns = data.columns elif data is None: if index is None: self._index = RangeIndex(0) else: self._index = as_index(index) if columns is not None: self._data = ColumnAccessor( OrderedDict.fromkeys( columns, column.column_empty( len(self), dtype="object", masked=True ), ) ) elif hasattr(data, "__cuda_array_interface__"): arr_interface = data.__cuda_array_interface__ # descr is an optional field of the _cuda_ary_iface_ if "descr" in arr_interface: if len(arr_interface["descr"]) == 1: new_df = self._from_arrays( data, index=index, columns=columns ) else: new_df = self.from_records( data, index=index, columns=columns ) else: new_df = self._from_arrays(data, index=index, columns=columns) self._data = new_df._data self.index = new_df._index self.columns = new_df.columns elif hasattr(data, "__array_interface__"): arr_interface = data.__array_interface__ if len(arr_interface["descr"]) == 1: # not record arrays new_df = self._from_arrays(data, index=index, columns=columns) else: new_df = self.from_records(data, index=index, columns=columns) self._data = new_df._data self.index = new_df._index self.columns = new_df.columns else: if is_list_like(data): if len(data) > 0 and is_scalar(data[0]): new_df = self._from_columns( [data], index=index, columns=columns ) self._data = new_df._data self.index = new_df._index self.columns = new_df.columns elif len(data) > 0 and isinstance(data[0], Series): self._init_from_series_list( data=data, columns=columns, index=index ) else: self._init_from_list_like( data, index=index, columns=columns ) else: if not is_dict_like(data): raise TypeError("data must be list or dict-like") self._init_from_dict_like(data, index=index, columns=columns) if dtype: self._data = self.astype(dtype)._data def _init_from_series_list(self, data, columns, index): if index is None: # When `index` is `None`, the final index of # resulting dataframe will be union of # all Series's names. final_index = as_index(_get_union_of_series_names(data)) else: # When an `index` is passed, the final index of # resulting dataframe will be whatever # index passed, but will need # shape validations - explained below data_length = len(data) index_length = len(index) if data_length != index_length: # If the passed `index` length doesn't match # length of Series objects in `data`, we must # check if `data` can be duplicated/expanded # to match the length of index. For that we # check if the length of index is a factor # of length of data. # # 1. If yes, we extend data # until length of data is equal to length of index. # 2. If no, we throw an error stating the # shape of resulting `data` and `index` # Simple example # >>> import pandas as pd # >>> s = pd.Series([1, 2, 3]) # >>> pd.DataFrame([s], index=['a', 'b']) # 0 1 2 # a 1 2 3 # b 1 2 3 # >>> pd.DataFrame([s], index=['a', 'b', 'c']) # 0 1 2 # a 1 2 3 # b 1 2 3 # c 1 2 3 if index_length % data_length == 0: initial_data = data data = [] for _ in range(int(index_length / data_length)): data.extend([o for o in initial_data]) else: raise ValueError( f"Shape of passed values is " f"{(data_length, len(data[0]))}, " f"indices imply {(index_length, len(data[0]))}" ) final_index = as_index(index) series_lengths = list(map(lambda x: len(x), data)) data = numeric_normalize_types(*data) if series_lengths.count(series_lengths[0]) == len(series_lengths): # Calculating the final dataframe columns by # getting union of all `index` of the Series objects. final_columns = _get_union_of_indices([d.index for d in data]) for idx, series in enumerate(data): if not series.index.is_unique: raise ValueError( "Reindexing only valid with uniquely valued Index " "objects" ) if not series.index.equals(final_columns): series = series.reindex(final_columns) self._data[idx] = column.as_column(series._column) # Setting `final_columns` to self._index so # that the resulting `transpose` will be have # columns set to `final_columns` self._index = final_columns transpose = self.T else: concat_df = cudf.concat(data, axis=1) if concat_df.columns.dtype == "object": concat_df.columns = concat_df.columns.astype("str") transpose = concat_df.T transpose._index = final_index self._data = transpose._data self._index = transpose._index # If `columns` is passed, the result dataframe # contain a dataframe with only the # specified `columns` in the same order. if columns: for col_name in columns: if col_name not in self._data: self._data[col_name] = column.column_empty( row_count=len(self), dtype=None, masked=True ) self._data = self._data.select_by_label(columns) def _init_from_list_like(self, data, index=None, columns=None): if index is None: index = RangeIndex(start=0, stop=len(data)) else: index = as_index(index) self._index = as_index(index) # list-of-dicts case if len(data) > 0 and isinstance(data[0], dict): data = DataFrame.from_pandas(pd.DataFrame(data)) self._data = data._data else: data = list(itertools.zip_longest(*data)) if columns is not None and len(data) == 0: data = [ cudf.core.column.column_empty(row_count=0, dtype=None) for _ in columns ] for col_name, col in enumerate(data): self._data[col_name] = column.as_column(col) if columns: self.columns = columns def _init_from_dict_like(self, data, index=None, columns=None): data = data.copy() num_rows = 0 if columns is not None: # remove all entries in `data` that are # not in `columns` keys = [key for key in data.keys() if key in columns] data = {key: data[key] for key in keys} extra_cols = [col for col in columns if col not in data.keys()] if keys: # if keys is non-empty, # add null columns for all values # in `columns` that don't exist in `keys`: data.update({key: None for key in extra_cols}) else: # if keys is empty, # it means that none of the actual keys in `data` # matches with `columns`. # Hence only assign `data` with `columns` as keys # and their values as empty columns. data = { key: cudf.core.column.column_empty(row_count=0, dtype=None) for key in extra_cols } data, index = self._align_input_series_indices(data, index=index) if index is None: if data: col_name = next(iter(data)) if is_scalar(data[col_name]): num_rows = num_rows or 1 else: data[col_name] = column.as_column(data[col_name]) num_rows = len(data[col_name]) self._index = RangeIndex(0, num_rows) else: self._index = as_index(index) if len(data): self._data.multiindex = True for (i, col_name) in enumerate(data): self._data.multiindex = self._data.multiindex and isinstance( col_name, tuple ) self.insert(i, col_name, data[col_name]) if columns is not None: self.columns = columns @classmethod def _from_table(cls, table, index=None): if index is None: if table._index is not None: index = Index._from_table(table._index) else: index = RangeIndex(table._num_rows) out = cls.__new__(cls) out._data = table._data out._index = index return out @staticmethod def _align_input_series_indices(data, index): data = data.copy() input_series = [ Series(val) for val in data.values() if isinstance(val, (pd.Series, Series)) ] if input_series: if index is not None: aligned_input_series = [ sr._align_to_index(index, how="right", sort=False) for sr in input_series ] else: aligned_input_series = cudf.core.series._align_indices( input_series ) index = aligned_input_series[0].index for name, val in data.items(): if isinstance(val, (pd.Series, Series)): data[name] = aligned_input_series.pop(0) return data, index @property def _constructor(self): return DataFrame @property def _constructor_sliced(self): return Series @property def _constructor_expanddim(self): raise NotImplementedError( "_constructor_expanddim not supported for DataFrames!" ) def serialize(self): header = {} frames = [] header["type-serialized"] = pickle.dumps(type(self)) header["index"], index_frames = self._index.serialize() header["index_frame_count"] = len(index_frames) frames.extend(index_frames) # Use the column directly to avoid duplicating the index # need to pickle column names to handle numpy integer columns header["column_names"] = pickle.dumps(tuple(self._data.names)) column_header, column_frames = column.serialize_columns(self._columns) header["columns"] = column_header frames.extend(column_frames) return header, frames @classmethod def deserialize(cls, header, frames): # Reconstruct the index index_frames = frames[: header["index_frame_count"]] idx_typ = pickle.loads(header["index"]["type-serialized"]) index = idx_typ.deserialize(header["index"], index_frames) # Reconstruct the columns column_frames = frames[header["index_frame_count"] :] column_names = pickle.loads(header["column_names"]) columns = column.deserialize_columns(header["columns"], column_frames) return cls(dict(zip(column_names, columns)), index=index) @property def dtypes(self): """Return the dtypes in this object.""" return pd.Series( [x.dtype for x in self._data.columns], index=self._data.names ) @property def shape(self): """Returns a tuple representing the dimensionality of the DataFrame. """ return self._num_rows, self._num_columns @property def ndim(self): """Dimension of the data. DataFrame ndim is always 2. """ return 2 def __dir__(self): o = set(dir(type(self))) o.update(self.__dict__) o.update( c for c in self.columns if isinstance(c, str) and c.isidentifier() ) return list(o) def __setattr__(self, key, col): # if an attribute already exists, set it. try: object.__getattribute__(self, key) object.__setattr__(self, key, col) return except AttributeError: pass # if a column already exists, set it. if key not in self._internal_names: try: self[key] # __getitem__ to verify key exists self[key] = col return except KeyError: pass object.__setattr__(self, key, col) def __getattr__(self, key): if key in self._internal_names: return object.__getattribute__(self, key) else: if key in self: return self[key] raise AttributeError("'DataFrame' object has no attribute %r" % key) @annotate("DATAFRAME_GETITEM", color="blue", domain="cudf_python") def __getitem__(self, arg): """ If *arg* is a ``str`` or ``int`` type, return the column Series. If *arg* is a ``slice``, return a new DataFrame with all columns sliced to the specified range. If *arg* is an ``array`` containing column names, return a new DataFrame with the corresponding columns. If *arg* is a ``dtype.bool array``, return the rows marked True Examples -------- >>> df = DataFrame([('a', list(range(20))), ... ('b', list(range(20))), ... ('c', list(range(20)))]) >>> df[:4] # get first 4 rows of all columns a b c 0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 >>> df[-5:] # get last 5 rows of all columns a b c 15 15 15 15 16 16 16 16 17 17 17 17 18 18 18 18 19 19 19 19 >>> df[['a', 'c']] # get columns a and c a c 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 8 8 8 9 9 9 >>> df[[True, False, True, False]] # mask the entire dataframe, # returning the rows specified in the boolean mask """ if is_scalar(arg) or isinstance(arg, tuple): return self._get_columns_by_label(arg, downcast=True) elif isinstance(arg, slice): return self._slice(arg) elif isinstance( arg, ( list, cupy.ndarray, np.ndarray, pd.Series, Series, Index, pd.Index, ), ): mask = arg if isinstance(mask, list): mask = pd.Series(mask) if mask.dtype == "bool": return self._apply_boolean_mask(mask) else: return self._get_columns_by_label(mask) elif isinstance(arg, DataFrame): return self.where(arg) else: raise TypeError( f"__getitem__ on type {type(arg)} is not supported" ) @annotate("DATAFRAME_SETITEM", color="blue", domain="cudf_python") def __setitem__(self, arg, value): """Add/set column by *arg or DataFrame* """ if isinstance(arg, DataFrame): # not handling set_item where arg = df & value = df if isinstance(value, DataFrame): raise TypeError( f"__setitem__ with arg = {type(value)} and " f"value = {type(arg)} is not supported" ) else: for col_name in self._data: scatter_map = arg[col_name] if is_scalar(value): self._data[col_name][scatter_map] = value else: self._data[col_name][scatter_map] = column.as_column( value )[scatter_map] elif is_scalar(arg) or isinstance(arg, tuple): if isinstance(value, DataFrame): _setitem_with_dataframe( input_df=self, replace_df=value, input_cols=[arg], mask=None, ) else: if arg in self._data: if len(self) == 0: if isinstance(value, (pd.Series, Series)): self._index = as_index(value.index) elif len(value) > 0: self._index = RangeIndex(start=0, stop=len(value)) value = column.as_column(value) new_data = self._data.__class__() for key in self._data: if key == arg: new_data[key] = value else: new_data[key] = column.column_empty_like( self._data[key], masked=True, newsize=len(value), ) self._data = new_data return elif isinstance(value, (pd.Series, Series)): value = Series(value)._align_to_index( self._index, how="right", sort=False, allow_non_unique=True, ) if is_scalar(value): self._data[arg][:] = value else: value = as_column(value) self._data[arg] = value else: # disc. with pandas here # pandas raises key error here self.insert(len(self._data), arg, value) elif isinstance( arg, (list, np.ndarray, pd.Series, Series, Index, pd.Index) ): mask = arg if isinstance(mask, list): mask = np.array(mask) if mask.dtype == "bool": mask = column.as_column(arg) if isinstance(value, DataFrame): _setitem_with_dataframe( input_df=self, replace_df=value, input_cols=None, mask=mask, ) else: if not is_scalar(value): value = column.as_column(value)[mask] for col_name in self._data: self._data[col_name][mask] = value else: if isinstance(value, DataFrame): _setitem_with_dataframe( input_df=self, replace_df=value, input_cols=arg, mask=None, ) else: for col in arg: if is_scalar(value): self._data[col] = column.full( size=len(self), fill_value=value ) else: self._data[col] = column.as_column(value) else: raise TypeError( f"__setitem__ on type {type(arg)} is not supported" ) def __delitem__(self, name): """ Drop the given column by *name*. """ self._drop_column(name) def __sizeof__(self): columns = sum(col.__sizeof__() for col in self._data.columns) index = self._index.__sizeof__() return columns + index def memory_usage(self, index=True, deep=False): """ Return the memory usage of each column in bytes. The memory usage can optionally include the contribution of the index and elements of `object` dtype. Parameters ---------- index : bool, default True Specifies whether to include the memory usage of the DataFrame's index in returned Series. If ``index=True``, the memory usage of the index is the first item in the output. deep : bool, default False If True, introspect the data deeply by interrogating `object` dtypes for system-level memory consumption, and include it in the returned values. Returns ------- Series A Series whose index is the original column names and whose values is the memory usage of each column in bytes. Examples -------- >>> dtypes = ['int64', 'float64', 'object', 'bool'] >>> data = dict([(t, np.ones(shape=5000).astype(t)) ... for t in dtypes]) >>> df = cudf.DataFrame(data) >>> df.head() int64 float64 object bool 0 1 1.0 1.0 True 1 1 1.0 1.0 True 2 1 1.0 1.0 True 3 1 1.0 1.0 True 4 1 1.0 1.0 True >>> df.memory_usage(index=False) int64 40000 float64 40000 object 40000 bool 5000 dtype: int64 Use a Categorical for efficient storage of an object-dtype column with many repeated values. >>> df['object'].astype('category').memory_usage(deep=True) 5048 """ ind = list(self.columns) sizes = [col._memory_usage(deep=deep) for col in self._data.columns] if index: ind.append("Index") ind = cudf.Index(ind, dtype="str") sizes.append(self.index.memory_usage(deep=deep)) return Series(sizes, index=ind) def __len__(self): """ Returns the number of rows """ return len(self.index) def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): import cudf if method == "__call__" and hasattr(cudf, ufunc.__name__): func = getattr(cudf, ufunc.__name__) return func(self) else: return NotImplemented def __array_function__(self, func, types, args, kwargs): cudf_df_module = DataFrame cudf_series_module = Series for submodule in func.__module__.split(".")[1:]: # point cudf to the correct submodule if hasattr(cudf_df_module, submodule): cudf_df_module = getattr(cudf_df_module, submodule) else: return NotImplemented fname = func.__name__ handled_types = [cudf_df_module, cudf_series_module] for t in types: if t not in handled_types: return NotImplemented if hasattr(cudf_df_module, fname): cudf_func = getattr(cudf_df_module, fname) # Handle case if cudf_func is same as numpy function if cudf_func is func: return NotImplemented else: return cudf_func(*args, **kwargs) else: return NotImplemented @property def values(self): """ Return a CuPy representation of the DataFrame. Only the values in the DataFrame will be returned, the axes labels will be removed. Returns ------- out: cupy.ndarray The values of the DataFrame. """ return cupy.asarray(self.as_gpu_matrix()) def __array__(self, dtype=None): raise TypeError( "Implicit conversion to a host NumPy array via __array__ is not " "allowed, To explicitly construct a GPU matrix, consider using " ".as_gpu_matrix()\nTo explicitly construct a host " "matrix, consider using .as_matrix()" ) def __arrow_array__(self, type=None): raise TypeError( "Implicit conversion to a host PyArrow Table via __arrow_array__ " "is not allowed, To explicitly construct a PyArrow Table, " "consider using .to_arrow()" ) def _get_numeric_data(self): """ Return a dataframe with only numeric data types """ columns = [ c for c, dt in self.dtypes.items() if dt != object and not is_categorical_dtype(dt) ] return self[columns] def assign(self, **kwargs): """ Assign columns to DataFrame from keyword arguments. Examples -------- >>> import cudf >>> df = cudf.DataFrame() >>> df = df.assign(a=[0, 1, 2], b=[3, 4, 5]) >>> df a b 0 0 3 1 1 4 2 2 5 """ new = self.copy() for k, v in kwargs.items(): new[k] = v return new def head(self, n=5): """ Returns the first n rows as a new DataFrame Examples -------- >>> import cudf >>> df = cudf.DataFrame() >>> df['key'] = [0, 1, 2, 3, 4] >>> df['val'] = [float(i + 10) for i in range(5)] # insert column >>> df.head(2) key val 0 0 10.0 1 1 11.0 """ return self.iloc[:n] def tail(self, n=5): """ Returns the last n rows as a new DataFrame Examples -------- >>> import cudf >>> df = cudf.DataFrame() >>> df['key'] = [0, 1, 2, 3, 4] >>> df['val'] = [float(i + 10) for i in range(5)] # insert column >>> df.tail(2) key val 3 3 13.0 4 4 14.0 """ if n == 0: return self.iloc[0:0] return self.iloc[-n:] def to_string(self): """ Convert to string cuDF uses Pandas internals for efficient string formatting. Set formatting options using pandas string formatting options and cuDF objects will print identically to Pandas objects. cuDF supports `null/None` as a value in any column type, which is transparently supported during this output process. Examples -------- >>> import cudf >>> df = cudf.DataFrame() >>> df['key'] = [0, 1, 2] >>> df['val'] = [float(i + 10) for i in range(3)] >>> df.to_string() ' key val\\n0 0 10.0\\n1 1 11.0\\n2 2 12.0' """ return self.__repr__() def __str__(self): return self.to_string() def astype(self, dtype, copy=False, errors="raise", **kwargs): """ Cast the DataFrame to the given dtype Parameters ---------- dtype : data type, or dict of column name -> data type Use a numpy.dtype or Python type to cast entire DataFrame object to the same type. Alternatively, use ``{col: dtype, ...}``, where col is a column label and dtype is a numpy.dtype or Python type to cast one or more of the DataFrame's columns to column-specific types. copy : bool, default False Return a deep-copy when ``copy=True``. Note by default ``copy=False`` setting is used and hence changes to values then may propagate to other cudf objects. errors : {'raise', 'ignore', 'warn'}, default 'raise' Control raising of exceptions on invalid data for provided dtype. - ``raise`` : allow exceptions to be raised - ``ignore`` : suppress exceptions. On error return original object. - ``warn`` : prints last exceptions as warnings and return original object. **kwargs : extra arguments to pass on to the constructor Returns ------- casted : DataFrame """ result = DataFrame(index=self.index) if is_dict_like(dtype): current_cols = self._data.names if len(set(dtype.keys()) - set(current_cols)) > 0: raise KeyError( "Only a column name can be used for the " "key in a dtype mappings argument." ) for col_name in current_cols: if col_name in dtype: result._data[col_name] = self._data[col_name].astype( dtype=dtype[col_name], errors=errors, copy=copy, **kwargs, ) else: result._data[col_name] = ( self._data[col_name].copy(deep=True) if copy else self._data[col_name] ) else: for col in self._data: result._data[col] = self._data[col].astype( dtype=dtype, **kwargs ) return result def _repr_pandas025_formatting(self, ncols, nrows, dtype=None): """ With Pandas > 0.25 there are some new conditional formatting for some datatypes and column/row configurations. This fixes most of them in context to match the expected Pandas repr of the same content. Examples -------- >>> gdf.__repr__() 0 ... 19 0 46 ... 48 .. .. ... .. 19 40 ... 29 [20 rows x 20 columns] >>> nrows, ncols = _repr_pandas025_formatting(2, 2, dtype="category") >>> pd.options.display.max_rows = nrows >>> pd.options.display.max_columns = ncols >>> gdf.__repr__() 0 ... 19 0 46 ... 48 .. .. ... .. 19 40 ... 29 [20 rows x 20 columns] """ ncols = 1 if ncols in [0, 2] and dtype == "datetime64[ns]" else ncols ncols = ( 1 if ncols == 0 and nrows == 1 and dtype in ["int8", "str", "category"] else ncols ) ncols = ( 1 if nrows == 1 and dtype in ["int8", "int16", "int64", "str", "category"] else ncols ) ncols = 0 if ncols == 2 else ncols ncols = 19 if ncols in [20, 21] else ncols return ncols, nrows def _clean_renderable_dataframe(self, output): """ This method takes in partial/preprocessed dataframe and returns correct representation of it with correct dimensions (rows x columns) """ max_rows = get_option("display.max_rows") min_rows = get_option("display.min_rows") max_cols = get_option("display.max_columns") max_colwidth = get_option("display.max_colwidth") show_dimensions = get_option("display.show_dimensions") if get_option("display.expand_frame_repr"): width, _ = console.get_console_size() else: width = None output = output.to_pandas().to_string( max_rows=max_rows, min_rows=min_rows, max_cols=max_cols, line_width=width, max_colwidth=max_colwidth, show_dimensions=show_dimensions, ) lines = output.split("\n") if lines[-1].startswith("["): lines = lines[:-1] lines.append( "[%d rows x %d columns]" % (len(self), len(self._data.names)) ) return "\n".join(lines) def _clean_nulls_from_dataframe(self, df): """ This function converts all ``null`` values to ``<NA>`` for representation as a string in `__repr__`. Since we utilize Pandas `__repr__` at all places in our code for formatting purposes, we convert columns to `str` dtype for filling with `<NA>` values. """ for col in df._data: if is_list_dtype(df._data[col]) or is_struct_dtype(df._data[col]): # TODO we need to handle this pass elif df._data[col].has_nulls: df[col] = df._data[col].astype("str").fillna(cudf._NA_REP) else: df[col] = df._data[col] return df def _get_renderable_dataframe(self): """ takes rows and columns from pandas settings or estimation from size. pulls quadrents based off of some known parameters then style for multiindex as well producing an efficient representative string for printing with the dataframe. """ max_rows = pd.options.display.max_rows nrows = np.max([len(self) if max_rows is None else max_rows, 1]) if pd.options.display.max_rows == 0: nrows = len(self) ncols = ( pd.options.display.max_columns if pd.options.display.max_columns else pd.options.display.width / 2 ) if len(self) <= nrows and len(self._data.names) <= ncols: output = self.copy(deep=False) elif self.empty and len(self.index) > 0: max_seq_items = pd.options.display.max_seq_items # Incase of Empty DataFrame with index, Pandas prints # first `pd.options.display.max_seq_items` index values # followed by ... To obtain ... at the end of index list, # adding 1 extra value. # If `pd.options.display.max_seq_items` is None, # entire sequence/Index is to be printed. # Note : Pandas truncates the dimensions at the end of # the resulting dataframe when `display.show_dimensions` # is set to truncate. Hence to display the dimensions we # need to extract maximum of `max_seq_items` and `nrows` # and have 1 extra value for ... to show up in the output # string. if max_seq_items is not None: output = self.head(max(max_seq_items, nrows) + 1) else: output = self.copy(deep=False) else: left_cols = len(self._data.names) right_cols = 0 upper_rows = len(self) lower_rows = 0 if len(self) > nrows and nrows > 0: upper_rows = int(nrows / 2.0) + 1 lower_rows = upper_rows + (nrows % 2) if len(self._data.names) > ncols: right_cols = len(self._data.names) - int(ncols / 2.0) # adjust right columns for output if multiindex. right_cols = ( right_cols - 1 if isinstance(self.index, cudf.MultiIndex) else right_cols ) left_cols = int(ncols / 2.0) + 1 if right_cols > 0: # Pick ncols - left_cols number of columns # from the right side/from the end. right_cols = -(int(ncols) - left_cols + 1) else: # If right_cols is 0 or negative, it means # self has lesser number of columns than ncols. # Hence assign len(self._data.names) which # will result in empty `*_right` quadrants. # This is because `*_left` quadrants will # contain all columns. right_cols = len(self._data.names) upper_left = self.head(upper_rows).iloc[:, :left_cols] upper_right = self.head(upper_rows).iloc[:, right_cols:] lower_left = self.tail(lower_rows).iloc[:, :left_cols] lower_right = self.tail(lower_rows).iloc[:, right_cols:] upper = cudf.concat([upper_left, upper_right], axis=1) lower = cudf.concat([lower_left, lower_right], axis=1) output = cudf.concat([upper, lower]) output = self._clean_nulls_from_dataframe(output) output._index = output._index._clean_nulls_from_index() return output def __repr__(self): output = self._get_renderable_dataframe() return self._clean_renderable_dataframe(output) def _repr_html_(self): lines = ( self._get_renderable_dataframe() .to_pandas() ._repr_html_() .split("\n") ) if lines[-2].startswith("<p>"): lines = lines[:-2] lines.append( "<p>%d rows × %d columns</p>" % (len(self), len(self._data.names)) ) lines.append("</div>") return "\n".join(lines) def _repr_latex_(self): return self._get_renderable_dataframe().to_pandas()._repr_latex_() # unary, binary, rbinary, orderedcompare, unorderedcompare def _apply_op(self, fn, other=None, fill_value=None): result = DataFrame(index=self.index) def op(lhs, rhs): if fill_value is None: return getattr(lhs, fn)(rhs) else: return getattr(lhs, fn)(rhs, fill_value) if other is None: for col in self._data: result[col] = getattr(self[col], fn)() return result elif isinstance(other, Sequence): for k, col in enumerate(self._data): result[col] = getattr(self[col], fn)(other[k]) elif isinstance(other, DataFrame): if fn in cudf.utils.utils._EQUALITY_OPS: if not self.index.equals(other.index): raise ValueError( "Can only compare identically-labeled " "DataFrame objects" ) lhs, rhs = _align_indices(self, other) result.index = lhs.index max_num_rows = max(lhs.shape[0], rhs.shape[0]) def fallback(col, fn): if fill_value is None: return Series.from_masked_array( data=column_empty(max_num_rows, dtype="float64"), mask=create_null_mask( max_num_rows, state=MaskState.ALL_NULL ), ).set_index(col.index) else: return getattr(col, fn)(fill_value) for col in lhs._data: if col not in rhs._data: result[col] = fallback(lhs[col], fn) else: result[col] = op(lhs[col], rhs[col]) for col in rhs._data: if col not in lhs._data: result[col] = fallback(rhs[col], _reverse_op(fn)) elif isinstance(other, Series): other_cols = other.to_pandas().to_dict() other_cols_keys = list(other_cols.keys()) result_cols = list(self.columns) df_cols = list(result_cols) for new_col in other_cols.keys(): if new_col not in result_cols: result_cols.append(new_col) for col in result_cols: if col in df_cols and col in other_cols_keys: l_opr = self[col] r_opr = other_cols[col] else: if col not in df_cols: r_opr = other_cols[col] l_opr = Series( column_empty( len(self), masked=True, dtype=other.dtype ) ) if col not in other_cols_keys: r_opr = None l_opr = self[col] result[col] = op(l_opr, r_opr) elif isinstance(other, (numbers.Number, cudf.Scalar)) or ( isinstance(other, np.ndarray) and other.ndim == 0 ): for col in self._data: result[col] = op(self[col], other) else: raise NotImplementedError( "DataFrame operations with " + str(type(other)) + " not " "supported at this time." ) return result def add(self, other, axis="columns", level=None, fill_value=None): """ Get Addition of dataframe and other, element-wise (binary operator `add`). Equivalent to ``dataframe + other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `radd`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> df + 1 angles degrees circle 1 361 triangle 4 181 rectangle 5 361 >>> df.add(1) angles degrees circle 1 361 triangle 4 181 rectangle 5 361 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("add", other, fill_value) def __add__(self, other): return self._apply_op("__add__", other) def radd(self, other, axis=1, level=None, fill_value=None): """ Get Addition of dataframe and other, element-wise (binary operator `radd`). Equivalent to ``other + dataframe``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `add`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> df + 1 angles degrees circle 1 361 triangle 4 181 rectangle 5 361 >>> df.radd(1) angles degrees circle 1 361 triangle 4 181 rectangle 5 361 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("radd", other, fill_value) def __radd__(self, other): return self._apply_op("__radd__", other) def sub(self, other, axis="columns", level=None, fill_value=None): """ Get Subtraction of dataframe and other, element-wise (binary operator `sub`). Equivalent to ``dataframe - other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `rsub`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> df.sub(1) angles degrees circle -1 359 triangle 2 179 rectangle 3 359 >>> df.sub([1, 2]) angles degrees circle -1 358 triangle 2 178 rectangle 3 358 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("sub", other, fill_value) def __sub__(self, other): return self._apply_op("__sub__", other) def rsub(self, other, axis="columns", level=None, fill_value=None): """ Get Subtraction of dataframe and other, element-wise (binary operator `rsub`). Equivalent to ``other - dataframe``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `sub`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> df angles degrees circle 0 360 triangle 3 180 rectangle 4 360 >>> df.rsub(1) angles degrees circle 1 -359 triangle -2 -179 rectangle -3 -359 >>> df.rsub([1, 2]) angles degrees circle 1 -358 triangle -2 -178 rectangle -3 -358 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("rsub", other, fill_value) def __rsub__(self, other): return self._apply_op("__rsub__", other) def mul(self, other, axis="columns", level=None, fill_value=None): """ Get Multiplication of dataframe and other, element-wise (binary operator `mul`). Equivalent to ``dataframe * other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `rmul`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> other = cudf.DataFrame({'angles': [0, 3, 4]}, ... index=['circle', 'triangle', 'rectangle']) >>> df * other angles degrees circle 0 <NA> triangle 9 <NA> rectangle 16 <NA> >>> df.mul(other, fill_value=0) angles degrees circle 0 0 triangle 9 0 rectangle 16 0 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("mul", other, fill_value) def __mul__(self, other): return self._apply_op("__mul__", other) def rmul(self, other, axis="columns", level=None, fill_value=None): """ Get Multiplication of dataframe and other, element-wise (binary operator `rmul`). Equivalent to ``other * dataframe``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `mul`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> other = cudf.DataFrame({'angles': [0, 3, 4]}, ... index=['circle', 'triangle', 'rectangle']) >>> other * df angles degrees circle 0 <NA> triangle 9 <NA> rectangle 16 <NA> >>> df.rmul(other, fill_value=0) angles degrees circle 0 0 triangle 9 0 rectangle 16 0 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("rmul", other, fill_value) def __rmul__(self, other): return self._apply_op("__rmul__", other) def mod(self, other, axis="columns", level=None, fill_value=None): """ Get Modulo division of dataframe and other, element-wise (binary operator `mod`). Equivalent to ``dataframe % other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `rmod`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> df % 100 angles degrees circle 0 60 triangle 3 80 rectangle 4 60 >>> df.mod(100) angles degrees circle 0 60 triangle 3 80 rectangle 4 60 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("mod", other, fill_value) def __mod__(self, other): return self._apply_op("__mod__", other) def rmod(self, other, axis="columns", level=None, fill_value=None): """ Get Modulo division of dataframe and other, element-wise (binary operator `rmod`). Equivalent to ``other % dataframe``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `mod`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [1, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> 100 % df angles degrees circle 0 100 triangle 1 100 rectangle 0 100 >>> df.rmod(100) angles degrees circle 0 100 triangle 1 100 rectangle 0 100 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("rmod", other, fill_value) def __rmod__(self, other): return self._apply_op("__rmod__", other) def pow(self, other, axis="columns", level=None, fill_value=None): """ Get Exponential power of dataframe and other, element-wise (binary operator `pow`). Equivalent to ``dataframe ** other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `rpow`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [1, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> df ** 2 angles degrees circle 0 129600 triangle 9 32400 rectangle 16 129600 >>> df.pow(2) angles degrees circle 0 129600 triangle 9 32400 rectangle 16 129600 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("pow", other, fill_value) def __pow__(self, other): return self._apply_op("__pow__", other) def rpow(self, other, axis="columns", level=None, fill_value=None): """ Get Exponential power of dataframe and other, element-wise (binary operator `pow`). Equivalent to ``other ** dataframe``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `pow`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [1, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> 1 ** df angles degrees circle 1 1 triangle 1 1 rectangle 1 1 >>> df.rpow(1) angles degrees circle 1 1 triangle 1 1 rectangle 1 1 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("rpow", other, fill_value) def __rpow__(self, other): return self._apply_op("__pow__", other) def floordiv(self, other, axis="columns", level=None, fill_value=None): """ Get Integer division of dataframe and other, element-wise (binary operator `floordiv`). Equivalent to ``dataframe // other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `rfloordiv`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [1, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> df.floordiv(2) angles degrees circle 0 180 triangle 1 90 rectangle 2 180 >>> df // 2 angles degrees circle 0 180 triangle 1 90 rectangle 2 180 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("floordiv", other, fill_value) def __floordiv__(self, other): return self._apply_op("__floordiv__", other) def rfloordiv(self, other, axis="columns", level=None, fill_value=None): """ Get Integer division of dataframe and other, element-wise (binary operator `rfloordiv`). Equivalent to ``other // dataframe``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `floordiv`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'col1': [10, 11, 23], ... 'col2': [101, 122, 321]}) >>> df col1 col2 0 10 101 1 11 122 2 23 321 >>> df.rfloordiv(df) col1 col2 0 1 1 1 1 1 2 1 1 >>> df.rfloordiv(200) col1 col2 0 20 1 1 18 1 2 8 0 >>> df.rfloordiv(100) col1 col2 0 10 0 1 9 0 2 4 0 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("rfloordiv", other, fill_value) def __rfloordiv__(self, other): return self._apply_op("__rfloordiv__", other) def truediv(self, other, axis="columns", level=None, fill_value=None): """ Get Floating division of dataframe and other, element-wise (binary operator `truediv`). Equivalent to ``dataframe / other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `rtruediv`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> df.truediv(10) angles degrees circle 0.0 36.0 triangle 0.3 18.0 rectangle 0.4 36.0 >>> df.div(10) angles degrees circle 0.0 36.0 triangle 0.3 18.0 rectangle 0.4 36.0 >>> df / 10 angles degrees circle 0.0 36.0 triangle 0.3 18.0 rectangle 0.4 36.0 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("truediv", other, fill_value) # Alias for truediv div = truediv def __truediv__(self, other): return self._apply_op("__truediv__", other) def rtruediv(self, other, axis="columns", level=None, fill_value=None): """ Get Floating division of dataframe and other, element-wise (binary operator `rtruediv`). Equivalent to ``other / dataframe``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `truediv`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> df angles degrees circle 0 360 triangle 3 180 rectangle 4 360 >>> df.rtruediv(10) angles degrees circle inf 0.027778 triangle 3.333333 0.055556 rectangle 2.500000 0.027778 >>> df.rdiv(10) angles degrees circle inf 0.027778 triangle 3.333333 0.055556 rectangle 2.500000 0.027778 >>> 10 / df angles degrees circle inf 0.027778 triangle 3.333333 0.055556 rectangle 2.500000 0.027778 """ if axis not in (1, "columns"): raise NotImplementedError("Only axis=1 supported at this time.") if level is not None: raise NotImplementedError("level parameter is not supported yet.") return self._apply_op("rtruediv", other, fill_value) # Alias for rtruediv rdiv = rtruediv def __rtruediv__(self, other): return self._apply_op("__rtruediv__", other) __div__ = __truediv__ def __and__(self, other): return self._apply_op("__and__", other) def __or__(self, other): return self._apply_op("__or__", other) def __xor__(self, other): return self._apply_op("__xor__", other) def __eq__(self, other): return self._apply_op("__eq__", other) def __ne__(self, other): return self._apply_op("__ne__", other) def __lt__(self, other): return self._apply_op("__lt__", other) def __le__(self, other): return self._apply_op("__le__", other) def __gt__(self, other): return self._apply_op("__gt__", other) def __ge__(self, other): return self._apply_op("__ge__", other) def __invert__(self): return self._apply_op("__invert__") def __neg__(self): return self._apply_op("__neg__") def __abs__(self): return self._apply_op("__abs__") def __iter__(self): return iter(self.columns) def iteritems(self): """ Iterate over column names and series pairs """ for k in self: yield (k, self[k]) @property @annotate("DATAFRAME_LOC", color="blue", domain="cudf_python") def loc(self): """ Selecting rows and columns by label or boolean mask. Examples -------- DataFrame with string index. >>> df a b a 0 5 b 1 6 c 2 7 d 3 8 e 4 9 Select a single row by label. >>> df.loc['a'] a 0 b 5 Name: a, dtype: int64 Select multiple rows and a single column. >>> df.loc[['a', 'c', 'e'], 'b'] a 5 c 7 e 9 Name: b, dtype: int64 Selection by boolean mask. >>> df.loc[df.a > 2] a b d 3 8 e 4 9 Setting values using loc. >>> df.loc[['a', 'c', 'e'], 'a'] = 0 >>> df a b a 0 5 b 1 6 c 0 7 d 3 8 e 0 9 See also -------- DataFrame.iloc Notes ----- One notable difference from Pandas is when DataFrame is of mixed types and result is expected to be a Series in case of Pandas. cuDF will return a DataFrame as it doesn't support mixed types under Series yet. Mixed dtype single row output as a dataframe (pandas results in Series) >>> import cudf >>> df = cudf.DataFrame({"a":[1, 2, 3], "b":["a", "b", "c"]}) >>> df.loc[0] a b 0 1 a """ return _DataFrameLocIndexer(self) @property def iloc(self): """ Selecting rows and column by position. Examples -------- >>> df = cudf.DataFrame({'a': range(20), ... 'b': range(20), ... 'c': range(20)}) Select a single row using an integer index. >>> df.iloc[1] a 1 b 1 c 1 Name: 1, dtype: int64 Select multiple rows using a list of integers. >>> df.iloc[[0, 2, 9, 18]] a b c 0 0 0 0 2 2 2 2 9 9 9 9 18 18 18 18 Select rows using a slice. >>> df.iloc[3:10:2] a b c 3 3 3 3 5 5 5 5 7 7 7 7 9 9 9 9 Select both rows and columns. >>> df.iloc[[1, 3, 5, 7], 2] 1 1 3 3 5 5 7 7 Name: c, dtype: int64 Setting values in a column using iloc. >>> df.iloc[:4] = 0 >>> df a b c 0 0 0 0 1 0 0 0 2 0 0 0 3 0 0 0 4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7 8 8 8 8 9 9 9 9 [10 more rows] See also -------- DataFrame.loc Notes ----- One notable difference from Pandas is when DataFrame is of mixed types and result is expected to be a Series in case of Pandas. cuDF will return a DataFrame as it doesn't support mixed types under Series yet. Mixed dtype single row output as a dataframe (pandas results in Series) >>> import cudf >>> df = cudf.DataFrame({"a":[1, 2, 3], "b":["a", "b", "c"]}) >>> df.iloc[0] a b 0 1 a """ return _DataFrameIlocIndexer(self) @property def iat(self): """ Alias for ``DataFrame.iloc``; provided for compatibility with Pandas. """ return self.iloc @property def at(self): """ Alias for ``DataFrame.loc``; provided for compatibility with Pandas. """ return self.loc @property @annotate("DATAFRAME_COLUMNS_GETTER", color="yellow", domain="cudf_python") def columns(self): """Returns a tuple of columns """ return self._data.to_pandas_index() @columns.setter @annotate("DATAFRAME_COLUMNS_SETTER", color="yellow", domain="cudf_python") def columns(self, columns): if isinstance(columns, (cudf.MultiIndex, cudf.Index)): columns = columns.to_pandas() if columns is None: columns = pd.Index(range(len(self._data.columns))) is_multiindex = isinstance(columns, pd.MultiIndex) if isinstance( columns, (Series, cudf.Index, cudf.core.column.ColumnBase) ): columns = pd.Index(columns.to_array(), tupleize_cols=is_multiindex) elif not isinstance(columns, pd.Index): columns = pd.Index(columns, tupleize_cols=is_multiindex) if not len(columns) == len(self._data.names): raise ValueError( f"Length mismatch: expected {len(self._data.names)} elements ," f"got {len(columns)} elements" ) data = dict(zip(columns, self._data.columns)) if len(columns) != len(data): raise ValueError("Duplicate column names are not allowed") self._data = ColumnAccessor( data, multiindex=is_multiindex, level_names=columns.names, ) def _rename_columns(self, new_names): old_cols = iter(self._data.names) l_old_cols = len(self._data) l_new_cols = len(new_names) if l_new_cols != l_old_cols: msg = ( f"Length of new column names: {l_new_cols} does not " "match length of previous column names: {l_old_cols}" ) raise ValueError(msg) mapper = dict(zip(old_cols, new_names)) self.rename(mapper=mapper, inplace=True, axis=1) @property def index(self): """Returns the index of the DataFrame """ return self._index @index.setter def index(self, value): old_length = ( self._num_rows if self._index is None else len(self._index) ) if isinstance(value, cudf.core.multiindex.MultiIndex): if len(self._data) > 0 and len(value) != old_length: msg = ( f"Length mismatch: Expected axis has {old_length} " f"elements, new values have {len(value)} elements" ) raise ValueError(msg) self._index = value return new_length = len(value) if len(self._data) > 0 and new_length != old_length: msg = ( f"Length mismatch: Expected axis has {old_length} elements, " f"new values have {new_length} elements" ) raise ValueError(msg) # try to build an index from generic _index idx = as_index(value) self._index = idx def reindex( self, labels=None, axis=0, index=None, columns=None, copy=True ): """ Return a new DataFrame whose axes conform to a new index ``DataFrame.reindex`` supports two calling conventions: - ``(index=index_labels, columns=column_names)`` - ``(labels, axis={0 or 'index', 1 or 'columns'})`` Parameters ---------- labels : Index, Series-convertible, optional, default None axis : {0 or 'index', 1 or 'columns'}, optional, default 0 index : Index, Series-convertible, optional, default None Shorthand for ``df.reindex(labels=index_labels, axis=0)`` columns : array-like, optional, default None Shorthand for ``df.reindex(labels=column_names, axis=1)`` copy : boolean, optional, default True Returns ------- A DataFrame whose axes conform to the new index(es) Examples -------- >>> import cudf >>> df = cudf.DataFrame() >>> df['key'] = [0, 1, 2, 3, 4] >>> df['val'] = [float(i + 10) for i in range(5)] >>> df_new = df.reindex(index=[0, 3, 4, 5], ... columns=['key', 'val', 'sum']) >>> df key val 0 0 10.0 1 1 11.0 2 2 12.0 3 3 13.0 4 4 14.0 >>> df_new key val sum 0 0 10.0 NaN 3 3 13.0 NaN 4 4 14.0 NaN 5 -1 NaN NaN """ if labels is None and index is None and columns is None: return self.copy(deep=copy) df = self cols = columns dtypes = OrderedDict(df.dtypes) idx = labels if index is None and axis in (0, "index") else index cols = labels if cols is None and axis in (1, "columns") else cols df = df if cols is None else df[list(set(df.columns) & set(cols))] result = df._reindex( columns=cols, dtypes=dtypes, deep=copy, index=idx, inplace=False ) return result def _set_index( self, index, to_drop=None, inplace=False, verify_integrity=False, ): """Helper for `.set_index` Parameters ---------- index : Index The new index to set. to_drop : list optional, default None A list of labels indicating columns to drop. inplace : boolean, default False Modify the DataFrame in place (do not create a new object). verify_integrity : boolean, default False Check for duplicates in the new index. """ if not isinstance(index, Index): raise ValueError("Parameter index should be type `Index`.") df = self if inplace else self.copy(deep=True) if verify_integrity and not index.is_unique: raise ValueError(f"Values in Index are not unique: {index}") if to_drop: df.drop(columns=to_drop, inplace=True) df.index = index return df if not inplace else None def set_index( self, keys, drop=True, append=False, inplace=False, verify_integrity=False, ): """Return a new DataFrame with a new index Parameters ---------- keys : Index, Series-convertible, label-like, or list Index : the new index. Series-convertible : values for the new index. Label-like : Label of column to be used as index. List : List of items from above. drop : boolean, default True Whether to drop corresponding column for str index argument append : boolean, default True Whether to append columns to the existing index, resulting in a MultiIndex. inplace : boolean, default False Modify the DataFrame in place (do not create a new object). verify_integrity : boolean, default False Check for duplicates in the new index. Examples -------- >>> df = cudf.DataFrame({ ... "a": [1, 2, 3, 4, 5], ... "b": ["a", "b", "c", "d","e"], ... "c": [1.0, 2.0, 3.0, 4.0, 5.0] ... }) >>> df a b c 0 1 a 1.0 1 2 b 2.0 2 3 c 3.0 3 4 d 4.0 4 5 e 5.0 Set the index to become the ‘b’ column: >>> df.set_index('b') a c b a 1 1.0 b 2 2.0 c 3 3.0 d 4 4.0 e 5 5.0 Create a MultiIndex using columns ‘a’ and ‘b’: >>> df.set_index(["a", "b"]) c a b 1 a 1.0 2 b 2.0 3 c 3.0 4 d 4.0 5 e 5.0 Set new Index instance as index: >>> df.set_index(cudf.RangeIndex(10, 15)) a b c 10 1 a 1.0 11 2 b 2.0 12 3 c 3.0 13 4 d 4.0 14 5 e 5.0 Setting `append=True` will combine current index with column `a`: >>> df.set_index("a", append=True) b c a 0 1 a 1.0 1 2 b 2.0 2 3 c 3.0 3 4 d 4.0 4 5 e 5.0 `set_index` supports `inplace` parameter too: >>> df.set_index("a", inplace=True) >>> df b c a 1 a 1.0 2 b 2.0 3 c 3.0 4 d 4.0 5 e 5.0 """ if not isinstance(keys, list): keys = [keys] # Preliminary type check col_not_found = [] columns_to_add = [] names = [] to_drop = [] for i, col in enumerate(keys): # Is column label if is_scalar(col) or isinstance(col, tuple): if col in self.columns: columns_to_add.append(self[col]) names.append(col) if drop: to_drop.append(col) else: col_not_found.append(col) else: # Try coerce into column if not is_column_like(col): try: col = as_column(col) except TypeError: msg = f"{col} cannot be converted to column-like." raise TypeError(msg) if isinstance(col, (cudf.MultiIndex, pd.MultiIndex)): col = ( cudf.from_pandas(col) if isinstance(col, pd.MultiIndex) else col ) cols = [col._data[x] for x in col._data] columns_to_add.extend(cols) names.extend(col.names) else: if isinstance(col, (pd.RangeIndex, cudf.RangeIndex)): # Corner case: RangeIndex does not need to instantiate columns_to_add.append(col) else: # For pandas obj, convert to gpu obj columns_to_add.append(as_column(col)) if isinstance( col, (cudf.Series, cudf.Index, pd.Series, pd.Index) ): names.append(col.name) else: names.append(None) if col_not_found: raise KeyError(f"None of {col_not_found} are in the columns") if append: idx_cols = [self.index._data[x] for x in self.index._data] if isinstance(self.index, cudf.MultiIndex): idx_names = self.index.names else: idx_names = [self.index.name] columns_to_add = idx_cols + columns_to_add names = idx_names + names if len(columns_to_add) == 0: raise ValueError("No valid columns to be added to index.") elif len(columns_to_add) == 1: idx = cudf.Index(columns_to_add[0], name=names[0]) else: idf = cudf.DataFrame() for i, col in enumerate(columns_to_add): idf[i] = col idx = cudf.MultiIndex.from_frame(idf, names=names) return self._set_index( index=idx, to_drop=to_drop, inplace=inplace, verify_integrity=verify_integrity, ) def reset_index( self, level=None, drop=False, inplace=False, col_level=0, col_fill="" ): """ Reset the index. Reset the index of the DataFrame, and use the default one instead. Parameters ---------- drop : bool, default False Do not try to insert index into dataframe columns. This resets the index to the default integer index. inplace : bool, default False Modify the DataFrame in place (do not create a new object). Returns ------- DataFrame or None DataFrame with the new index or None if ``inplace=True``. Examples -------- >>> df = cudf.DataFrame([('bird', 389.0), ... ('bird', 24.0), ... ('mammal', 80.5), ... ('mammal', np.nan)], ... index=['falcon', 'parrot', 'lion', 'monkey'], ... columns=('class', 'max_speed')) >>> df class max_speed falcon bird 389.0 parrot bird 24.0 lion mammal 80.5 monkey mammal <NA> >>> df.reset_index() index class max_speed 0 falcon bird 389.0 1 parrot bird 24.0 2 lion mammal 80.5 3 monkey mammal <NA> >>> df.reset_index(drop=True) class max_speed 0 bird 389.0 1 bird 24.0 2 mammal 80.5 3 mammal <NA> """ if level is not None: raise NotImplementedError("level parameter is not supported yet.") if col_level != 0: raise NotImplementedError( "col_level parameter is not supported yet." ) if col_fill != "": raise NotImplementedError( "col_fill parameter is not supported yet." ) if inplace: result = self else: result = self.copy() if all(name is None for name in self.index.names): if isinstance(self.index, cudf.MultiIndex): names = tuple( f"level_{i}" for i, _ in enumerate(self.index.names) ) else: names = ("index",) else: names = self.index.names if not drop: index_columns = self.index._data.columns for name, index_column in zip( reversed(names), reversed(index_columns) ): result.insert(0, name, index_column) result.index = RangeIndex(len(self)) if inplace: return else: return result def take(self, positions, keep_index=True): """ Return a new DataFrame containing the rows specified by *positions* Parameters ---------- positions : array-like Integer or boolean array-like specifying the rows of the output. If integer, each element represents the integer index of a row. If boolean, *positions* must be of the same length as *self*, and represents a boolean mask. Returns ------- out : DataFrame New DataFrame Examples -------- >>> a = cudf.DataFrame({'a': [1.0, 2.0, 3.0], ... 'b': cudf.Series(['a', 'b', 'c'])}) >>> a.take([0, 2, 2]) a b 0 1.0 a 2 3.0 c 2 3.0 c >>> a.take([True, False, True]) a b 0 1.0 a 2 3.0 c """ positions = as_column(positions) if pd.api.types.is_bool_dtype(positions): return self._apply_boolean_mask(positions) out = self._gather(positions, keep_index=keep_index) out.columns = self.columns return out @annotate("DATAFRAME_COPY", color="cyan", domain="cudf_python") def copy(self, deep=True): """ Returns a copy of this dataframe Parameters ---------- deep: bool Make a full copy of Series columns and Index at the GPU level, or create a new allocation with references. """ out = DataFrame(data=self._data.copy(deep=deep)) out.index = self.index.copy(deep=deep) return out def __copy__(self): return self.copy(deep=True) def __deepcopy__(self, memo=None): """ Parameters ---------- memo, default None Standard signature. Unused """ if memo is None: memo = {} return self.copy(deep=True) @annotate("INSERT", color="green", domain="cudf_python") def insert(self, loc, name, value): """ Add a column to DataFrame at the index specified by loc. Parameters ---------- loc : int location to insert by index, cannot be greater then num columns + 1 name : number or string name or label of column to be inserted value : Series or array-like """ num_cols = len(self._data) if name in self._data: raise NameError(f"duplicated column name {name}") if loc < 0: loc = num_cols + loc + 1 if not (0 <= loc <= num_cols): raise ValueError( f"insert location must be within range " f"{-(num_cols + 1) * (num_cols > 0)}, " f"{num_cols * (num_cols > 0)}" ) if is_scalar(value): value = utils.scalar_broadcast_to(value, len(self)) if len(self) == 0: if isinstance(value, (pd.Series, Series)): self._index = as_index(value.index) elif len(value) > 0: self._index = RangeIndex(start=0, stop=len(value)) new_data = self._data.__class__() if num_cols != 0: for col_name in self._data: new_data[col_name] = column.column_empty_like( self._data[col_name], masked=True, newsize=len(value), ) self._data = new_data elif isinstance(value, (pd.Series, Series)): value = Series(value)._align_to_index( self._index, how="right", sort=False ) value = column.as_column(value) self._data.insert(name, value, loc=loc) def drop( self, labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors="raise", ): """ Drop specified labels from rows or columns. Remove rows or columns by specifying label names and corresponding axis, or by specifying directly index or column names. When using a multi-index, labels on different levels can be removed by specifying the level. Parameters ---------- labels : single label or list-like Index or column labels to drop. axis : {0 or 'index', 1 or 'columns'}, default 0 Whether to drop labels from the index (0 or 'index') or columns (1 or 'columns'). index : single label or list-like Alternative to specifying axis (``labels, axis=0`` is equivalent to ``index=labels``). columns : single label or list-like Alternative to specifying axis (``labels, axis=1`` is equivalent to ``columns=labels``). level : int or level name, optional For MultiIndex, level from which the labels will be removed. inplace : bool, default False If False, return a copy. Otherwise, do operation inplace and return None. errors : {'ignore', 'raise'}, default 'raise' If 'ignore', suppress error and only existing labels are dropped. Returns ------- DataFrame DataFrame without the removed index or column labels. Raises ------ KeyError If any of the labels is not found in the selected axis. See Also -------- DataFrame.loc : Label-location based indexer for selection by label. DataFrame.dropna : Return DataFrame with labels on given axis omitted where (all or any) data are missing. DataFrame.drop_duplicates : Return DataFrame with duplicate rows removed, optionally only considering certain columns. Examples -------- >>> import cudf >>> df = cudf.DataFrame({"A": [1, 2, 3, 4], ... "B": [5, 6, 7, 8], ... "C": [10, 11, 12, 13], ... "D": [20, 30, 40, 50]}) >>> df A B C D 0 1 5 10 20 1 2 6 11 30 2 3 7 12 40 3 4 8 13 50 Drop columns >>> df.drop(['B', 'C'], axis=1) A D 0 1 20 1 2 30 2 3 40 3 4 50 >>> df.drop(columns=['B', 'C']) A D 0 1 20 1 2 30 2 3 40 3 4 50 Drop a row by index >>> df.drop([0, 1]) A B C D 2 3 7 12 40 3 4 8 13 50 Drop columns and/or rows of MultiIndex DataFrame >>> midx = cudf.MultiIndex(levels=[['lama', 'cow', 'falcon'], ... ['speed', 'weight', 'length']], ... codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2], ... [0, 1, 2, 0, 1, 2, 0, 1, 2]]) >>> df = cudf.DataFrame(index=midx, columns=['big', 'small'], ... data=[[45, 30], [200, 100], [1.5, 1], [30, 20], ... [250, 150], [1.5, 0.8], [320, 250], ... [1, 0.8], [0.3, 0.2]]) >>> df big small lama speed 45.0 30.0 weight 200.0 100.0 length 1.5 1.0 cow speed 30.0 20.0 weight 250.0 150.0 length 1.5 0.8 falcon speed 320.0 250.0 weight 1.0 0.8 length 0.3 0.2 >>> df.drop(index='cow', columns='small') big lama speed 45.0 weight 200.0 length 1.5 falcon speed 320.0 weight 1.0 length 0.3 >>> df.drop(index='length', level=1) big small lama speed 45.0 30.0 weight 200.0 100.0 cow speed 30.0 20.0 weight 250.0 150.0 falcon speed 320.0 250.0 weight 1.0 0.8 """ if labels is not None: if index is not None or columns is not None: raise ValueError( "Cannot specify both 'labels' and 'index'/'columns'" ) target = labels elif index is not None: target = index axis = 0 elif columns is not None: target = columns axis = 1 else: raise ValueError( "Need to specify at least one of 'labels', " "'index' or 'columns'" ) if inplace: outdf = self else: outdf = self.copy() if axis in (1, "columns"): target = _get_host_unique(target) _drop_columns(outdf, target, errors) elif axis in (0, "index"): if not isinstance(target, (cudf.Series, cudf.Index)): target = column.as_column(target) if isinstance(self._index, cudf.MultiIndex): if level is None: level = 0 levels_index = outdf.index.get_level_values(level) if errors == "raise" and not target.isin(levels_index).all(): raise KeyError("One or more values not found in axis") # TODO : Could use anti-join as a future optimization sliced_df = outdf.take(~levels_index.isin(target)) sliced_df._index.names = self._index.names else: if errors == "raise" and not target.isin(outdf.index).all(): raise KeyError("One or more values not found in axis") sliced_df = outdf.join( cudf.DataFrame(index=target), how="leftanti" ) if columns is not None: columns = _get_host_unique(columns) _drop_columns(sliced_df, columns, errors) outdf._data = sliced_df._data outdf._index = sliced_df._index if not inplace: return outdf def _drop_column(self, name): """Drop a column by *name* """ if name not in self._data: raise KeyError(f"column '{name}' does not exist") del self._data[name] def drop_duplicates( self, subset=None, keep="first", inplace=False, ignore_index=False ): """ Return DataFrame with duplicate rows removed, optionally only considering certain subset of columns. """ outdf = super().drop_duplicates( subset=subset, keep=keep, ignore_index=ignore_index ) return self._mimic_inplace(outdf, inplace=inplace) def pop(self, item): """Return a column and drop it from the DataFrame. """ popped = self[item] del self[item] return popped def rename( self, mapper=None, index=None, columns=None, axis=0, copy=True, inplace=False, level=None, errors="ignore", ): """Alter column and index labels. Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don’t throw an error. ``DataFrame.rename`` supports two calling conventions: - ``(index=index_mapper, columns=columns_mapper, ...)`` - ``(mapper, axis={0/'index' or 1/'column'}, ...)`` We highly recommend using keyword arguments to clarify your intent. Parameters ---------- mapper : dict-like or function, default None optional dict-like or functions transformations to apply to the index/column values depending on selected ``axis``. index : dict-like, default None Optional dict-like transformations to apply to the index axis' values. Does not support functions for axis 0 yet. columns : dict-like or function, default None optional dict-like or functions transformations to apply to the columns axis' values. axis : int, default 0 Axis to rename with mapper. 0 or 'index' for index 1 or 'columns' for columns copy : boolean, default True Also copy underlying data inplace : boolean, default False Return new DataFrame. If True, assign columns without copy level : int or level name, default None In case of a MultiIndex, only rename labels in the specified level. errors : {'raise', 'ignore', 'warn'}, default 'ignore' *Only 'ignore' supported* Control raising of exceptions on invalid data for provided dtype. - ``raise`` : allow exceptions to be raised - ``ignore`` : suppress exceptions. On error return original object. - ``warn`` : prints last exceptions as warnings and return original object. Returns ------- DataFrame Notes ----- Difference from pandas: * Not supporting: level Rename will not overwite column names. If a list with duplicates is passed, column names will be postfixed with a number. """ if errors != "ignore": raise NotImplementedError( "Only errors='ignore' is currently supported" ) if level: raise NotImplementedError( "Only level=False is currently supported" ) if mapper is None and index is None and columns is None: return self.copy(deep=copy) index = mapper if index is None and axis in (0, "index") else index columns = ( mapper if columns is None and axis in (1, "columns") else columns ) if index: if ( any(type(item) == str for item in index.values()) and type(self.index) != cudf.core.index.StringIndex ): raise NotImplementedError( "Implicit conversion of index to " "mixed type is not yet supported." ) out = DataFrame( index=self.index.replace( to_replace=list(index.keys()), replacement=list(index.values()), ) ) else: out = DataFrame(index=self.index) if columns: postfix = 1 if isinstance(columns, Mapping): # It is possible for DataFrames with a MultiIndex columns # object to have columns with the same name. The following # use of _cols.items and ("_1", "_2"... allows the use of # rename in this case for key, col in self._data.items(): if key in columns: if columns[key] in out._data: out_column = columns[key] + "_" + str(postfix) postfix += 1 else: out_column = columns[key] out[out_column] = col else: out[key] = col elif callable(columns): for key, col in self._data.items(): out[columns(key)] = col else: out._data = self._data.copy(deep=copy) if inplace: self._data = out._data else: return out.copy(deep=copy) def nans_to_nulls(self): """ Convert nans (if any) to nulls. """ df = self.copy() for col in df.columns: df[col] = df[col].nans_to_nulls() return df def as_gpu_matrix(self, columns=None, order="F"): """Convert to a matrix in device memory. Parameters ---------- columns : sequence of str List of a column names to be extracted. The order is preserved. If None is specified, all columns are used. order : 'F' or 'C' Optional argument to determine whether to return a column major (Fortran) matrix or a row major (C) matrix. Returns ------- A (nrow x ncol) numba device ndarray """ if columns is None: columns = self._data.names cols = [self._data[k] for k in columns] ncol = len(cols) nrow = len(self) if ncol < 1: # This is the case for empty dataframe - construct empty cupy array matrix = cupy.empty( shape=(0, 0), dtype=np.dtype("float64"), order=order ) return cuda.as_cuda_array(matrix) if any( (is_categorical_dtype(c) or np.issubdtype(c, np.dtype("object"))) for c in cols ): raise TypeError("non-numeric data not yet supported") dtype = find_common_type([col.dtype for col in cols]) for k, c in self._data.items(): if c.has_nulls: raise ValueError( f"column '{k}' has null values. " f"hint: use .fillna() to replace null values" ) cupy_dtype = dtype if np.issubdtype(cupy_dtype, np.datetime64): cupy_dtype = np.dtype("int64") if order not in ("F", "C"): raise ValueError( "order parameter should be 'C' for row major or 'F' for" "column major GPU matrix" ) matrix = cupy.empty(shape=(nrow, ncol), dtype=cupy_dtype, order=order) for colidx, inpcol in enumerate(cols): dense = inpcol.astype(cupy_dtype) matrix[:, colidx] = cupy.asarray(dense) return cuda.as_cuda_array(matrix).view(dtype) def as_matrix(self, columns=None): """Convert to a matrix in host memory. Parameters ---------- columns : sequence of str List of a column names to be extracted. The order is preserved. If None is specified, all columns are used. Returns ------- A (nrow x ncol) numpy ndarray in "F" order. """ return self.as_gpu_matrix(columns=columns).copy_to_host() def one_hot_encoding( self, column, prefix, cats, prefix_sep="_", dtype="float64" ): """ Expand a column with one-hot-encoding. Parameters ---------- column : str the source column with binary encoding for the data. prefix : str the new column name prefix. cats : sequence of ints the sequence of categories as integers. prefix_sep : str the separator between the prefix and the category. dtype : the dtype for the outputs; defaults to float64. Returns ------- a new dataframe with new columns append for each category. Examples -------- >>> import pandas as pd >>> import cudf >>> pet_owner = [1, 2, 3, 4, 5] >>> pet_type = ['fish', 'dog', 'fish', 'bird', 'fish'] >>> df = pd.DataFrame({'pet_owner': pet_owner, 'pet_type': pet_type}) >>> df.pet_type = df.pet_type.astype('category') Create a column with numerically encoded category values >>> df['pet_codes'] = df.pet_type.cat.codes >>> gdf = cudf.from_pandas(df) Create the list of category codes to use in the encoding >>> codes = gdf.pet_codes.unique() >>> gdf.one_hot_encoding('pet_codes', 'pet_dummy', codes).head() pet_owner pet_type pet_codes pet_dummy_0 pet_dummy_1 pet_dummy_2 0 1 fish 2 0.0 0.0 1.0 1 2 dog 1 0.0 1.0 0.0 2 3 fish 2 0.0 0.0 1.0 3 4 bird 0 1.0 0.0 0.0 4 5 fish 2 0.0 0.0 1.0 """ if hasattr(cats, "to_arrow"): cats = cats.to_arrow().to_pylist() else: cats = pd.Series(cats, dtype="object") newnames = [ prefix_sep.join([prefix, "null" if cat is None else str(cat)]) for cat in cats ] newcols = self[column].one_hot_encoding(cats=cats, dtype=dtype) outdf = self.copy() for name, col in zip(newnames, newcols): outdf.insert(len(outdf._data), name, col) return outdf def label_encoding( self, column, prefix, cats, prefix_sep="_", dtype=None, na_sentinel=-1 ): """Encode labels in a column with label encoding. Parameters ---------- column : str the source column with binary encoding for the data. prefix : str the new column name prefix. cats : sequence of ints the sequence of categories as integers. prefix_sep : str the separator between the prefix and the category. dtype : the dtype for the outputs; see Series.label_encoding na_sentinel : number Value to indicate missing category. Returns ------- a new dataframe with a new column append for the coded values. """ newname = prefix_sep.join([prefix, "labels"]) newcol = self[column].label_encoding( cats=cats, dtype=dtype, na_sentinel=na_sentinel ) outdf = self.copy() outdf.insert(len(outdf._data), newname, newcol) return outdf @annotate("ARGSORT", color="yellow", domain="cudf_python") def argsort(self, ascending=True, na_position="last"): """ Sort by the values. Parameters ---------- ascending : bool or list of bool, default True If True, sort values in ascending order, otherwise descending. na_position : {‘first’ or ‘last’}, default ‘last’ Argument ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end. Returns ------- out_column_inds : cuDF Column of indices sorted based on input Notes ----- Difference from pandas: - Support axis='index' only. - Not supporting: inplace, kind - Ascending can be a list of bools to control per column """ return self._get_sorted_inds( ascending=ascending, na_position=na_position ) @annotate("SORT_INDEX", color="red", domain="cudf_python") def sort_index( self, axis=0, level=None, ascending=True, inplace=False, kind=None, na_position="last", sort_remaining=True, ignore_index=False, ): """Sort object by labels (along an axis). Parameters ---------- axis : {0 or ‘index’, 1 or ‘columns’}, default 0 The axis along which to sort. The value 0 identifies the rows, and 1 identifies the columns. level : int or level name or list of ints or list of level names If not None, sort on values in specified index level(s). This is only useful in the case of MultiIndex. ascending : bool, default True Sort ascending vs. descending. inplace : bool, default False If True, perform operation in-place. kind : sorting method such as `quick sort` and others. Not yet supported. na_position : {‘first’, ‘last’}, default ‘last’ Puts NaNs at the beginning if first; last puts NaNs at the end. sort_remaining : bool, default True Not yet supported ignore_index : bool, default False if True, index will be replaced with RangeIndex. Returns ------- DataFrame or None Examples -------- >>> df = cudf.DataFrame( ... {"b":[3, 2, 1], "a":[2, 1, 3]}, index=[1, 3, 2]) >>> df.sort_index(axis=0) b a 1 3 2 2 1 3 3 2 1 >>> df.sort_index(axis=1) a b 1 2 3 3 1 2 2 3 1 """ if kind is not None: raise NotImplementedError("kind is not yet supported") if not sort_remaining: raise NotImplementedError( "sort_remaining == False is not yet supported" ) if axis in (0, "index"): if level is not None and isinstance(self.index, cudf.MultiIndex): # Pandas currently don't handle na_position # in case of MultiIndex if ascending is True: na_position = "first" else: na_position = "last" if is_list_like(level): labels = [ self.index._get_level_label(lvl) for lvl in level ] else: labels = [self.index._get_level_label(level)] inds = self.index._source_data[labels].argsort( ascending=ascending, na_position=na_position ) else: inds = self.index.argsort( ascending=ascending, na_position=na_position ) outdf = self.take(inds) else: labels = sorted(self._data.names, reverse=not ascending) outdf = self[labels] if ignore_index is True: outdf = outdf.reset_index(drop=True) return self._mimic_inplace(outdf, inplace=inplace) def sort_values( self, by, axis=0, ascending=True, inplace=False, kind="quicksort", na_position="last", ignore_index=False, ): """ Sort by the values row-wise. Parameters ---------- by : str or list of str Name or list of names to sort by. ascending : bool or list of bool, default True Sort ascending vs. descending. Specify list for multiple sort orders. If this is a list of bools, must match the length of the by. na_position : {‘first’, ‘last’}, default ‘last’ 'first' puts nulls at the beginning, 'last' puts nulls at the end ignore_index : bool, default False If True, index will not be sorted. Returns ------- sorted_obj : cuDF DataFrame Notes ----- Difference from pandas: * Support axis='index' only. * Not supporting: inplace, kind Examples -------- >>> import cudf >>> a = ('a', [0, 1, 2]) >>> b = ('b', [-3, 2, 0]) >>> df = cudf.DataFrame([a, b]) >>> df.sort_values('b') a b 0 0 -3 2 2 0 1 1 2 """ if inplace: raise NotImplementedError("`inplace` not currently implemented.") if kind != "quicksort": raise NotImplementedError("`kind` not currently implemented.") if axis != 0: raise NotImplementedError("`axis` not currently implemented.") # argsort the `by` column return self.take( self[by].argsort(ascending=ascending, na_position=na_position), keep_index=not ignore_index, ) def agg(self, aggs, axis=None): """ Aggregate using one or more operations over the specified axis. Parameters ---------- aggs : Iterable (set, list, string, tuple or dict) Function to use for aggregating data. Accepted types are: * string name, e.g. ``"sum"`` * list of functions, e.g. ``["sum", "min", "max"]`` * dict of axis labels specified operations per column, e.g. ``{"a": "sum"}`` axis : not yet supported Returns ------- Aggregation Result : ``Series`` or ``DataFrame`` When ``DataFrame.agg`` is called with single agg, ``Series`` is returned. When ``DataFrame.agg`` is called with several aggs, ``DataFrame`` is returned. Notes ----- Difference from pandas: * Not supporting: ``axis``, ``*args``, ``**kwargs`` """ # TODO: Remove the typecasting below once issue #6846 is fixed # link <https://github.com/rapidsai/cudf/issues/6846> dtypes = [self[col].dtype for col in self._column_names] common_dtype = cudf.utils.dtypes.find_common_type(dtypes) df_normalized = self.astype(common_dtype) if any(is_string_dtype(dt) for dt in dtypes): raise NotImplementedError( "DataFrame.agg() is not supported for " "frames containing string columns" ) if axis == 0 or axis is not None: raise NotImplementedError("axis not implemented yet") if isinstance(aggs, Iterable) and not isinstance(aggs, (str, dict)): result = cudf.DataFrame() # TODO : Allow simultaneous pass for multi-aggregation as # a future optimization for agg in aggs: result[agg] = getattr(df_normalized, agg)() return result.T.sort_index(axis=1, ascending=True) elif isinstance(aggs, str): if not hasattr(df_normalized, aggs): raise AttributeError( f"{aggs} is not a valid function for " f"'DataFrame' object" ) result = cudf.DataFrame() result[aggs] = getattr(df_normalized, aggs)() result = result.iloc[:, 0] result.name = None return result elif isinstance(aggs, dict): cols = aggs.keys() if any([callable(val) for val in aggs.values()]): raise NotImplementedError( "callable parameter is not implemented yet" ) elif all([isinstance(val, str) for val in aggs.values()]): result = cudf.Series(index=cols) for key, value in aggs.items(): col = df_normalized[key] if not hasattr(col, value): raise AttributeError( f"{value} is not a valid function for " f"'Series' object" ) result[key] = getattr(col, value)() elif all([isinstance(val, Iterable) for val in aggs.values()]): idxs = set() for val in aggs.values(): if isinstance(val, Iterable): idxs.update(val) elif isinstance(val, str): idxs.add(val) idxs = sorted(list(idxs)) for agg in idxs: if agg is callable: raise NotImplementedError( "callable parameter is not implemented yet" ) result = cudf.DataFrame(index=idxs, columns=cols) for key in aggs.keys(): col = df_normalized[key] col_empty = column_empty( len(idxs), dtype=col.dtype, masked=True ) ans = cudf.Series(data=col_empty, index=idxs) if isinstance(aggs.get(key), Iterable): # TODO : Allow simultaneous pass for multi-aggregation # as a future optimization for agg in aggs.get(key): if not hasattr(col, agg): raise AttributeError( f"{agg} is not a valid function for " f"'Series' object" ) ans[agg] = getattr(col, agg)() elif isinstance(aggs.get(key), str): if not hasattr(col, aggs.get(key)): raise AttributeError( f"{aggs.get(key)} is not a valid function for " f"'Series' object" ) ans[aggs.get(key)] = getattr(col, agg)() result[key] = ans else: raise ValueError("values of dict must be a string or list") return result elif callable(aggs): raise NotImplementedError( "callable parameter is not implemented yet" ) else: raise ValueError("argument must be a string, list or dict") def nlargest(self, n, columns, keep="first"): """Get the rows of the DataFrame sorted by the n largest value of *columns* Notes ----- Difference from pandas: - Only a single column is supported in *columns* """ return self._n_largest_or_smallest("nlargest", n, columns, keep) def nsmallest(self, n, columns, keep="first"): """Get the rows of the DataFrame sorted by the n smallest value of *columns* Notes ----- Difference from pandas: - Only a single column is supported in *columns* """ return self._n_largest_or_smallest("nsmallest", n, columns, keep) def _n_largest_or_smallest(self, method, n, columns, keep): # Get column to operate on if not isinstance(columns, str): [column] = columns else: column = columns col = self[column].reset_index(drop=True) # Operate sorted_series = getattr(col, method)(n=n, keep=keep) df = DataFrame() new_positions = sorted_series.index.gpu_values for k in self._data.names: if k == column: df[k] = sorted_series else: df[k] = self[k].reset_index(drop=True).take(new_positions) return df.set_index(self.index.take(new_positions)) def transpose(self): """Transpose index and columns. Returns ------- a new (ncol x nrow) dataframe. self is (nrow x ncol) Notes ----- Difference from pandas: Not supporting *copy* because default and only behavior is copy=True """ # Never transpose a MultiIndex - remove the existing columns and # replace with a RangeIndex. Afterward, reassign. columns = self.index.copy(deep=False) index = self.columns.copy(deep=False) if self._num_columns == 0 or self._num_rows == 0: return DataFrame(index=index, columns=columns) # Cython renames the columns to the range [0...ncols] result = self.__class__._from_table(libcudf.transpose.transpose(self)) # Set the old column names as the new index result._index = as_index(index) # Set the old index as the new column names result.columns = columns return result @property def T(self): """ Transpose index and columns. Reflect the DataFrame over its main diagonal by writing rows as columns and vice-versa. The property T is an accessor to the method transpose(). Returns ------- out : DataFrame The transposed DataFrame. """ return self.transpose() def melt(self, **kwargs): """Unpivots a DataFrame from wide format to long format, optionally leaving identifier variables set. Parameters ---------- frame : DataFrame id_vars : tuple, list, or ndarray, optional Column(s) to use as identifier variables. default: None value_vars : tuple, list, or ndarray, optional Column(s) to unpivot. default: all columns that are not set as `id_vars`. var_name : scalar Name to use for the `variable` column. default: frame.columns.name or 'variable' value_name : str Name to use for the `value` column. default: 'value' Returns ------- out : DataFrame Melted result """ from cudf.core.reshape import melt return melt(self, **kwargs) @annotate("JOIN", color="blue", domain="cudf_python") def merge( self, right, on=None, left_on=None, right_on=None, left_index=False, right_index=False, how="inner", sort=False, lsuffix=None, rsuffix=None, method="hash", indicator=False, suffixes=("_x", "_y"), ): """Merge GPU DataFrame objects by performing a database-style join operation by columns or indexes. Parameters ---------- right : DataFrame on : label or list; defaults to None Column or index level names to join on. These must be found in both DataFrames. If on is None and not merging on indexes then this defaults to the intersection of the columns in both DataFrames. how : {‘left’, ‘outer’, ‘inner’}, default ‘inner’ Type of merge to be performed. - left : use only keys from left frame, similar to a SQL left outer join. - right : not supported. - outer : use union of keys from both frames, similar to a SQL full outer join. - inner: use intersection of keys from both frames, similar to a SQL inner join. left_on : label or list, or array-like Column or index level names to join on in the left DataFrame. Can also be an array or list of arrays of the length of the left DataFrame. These arrays are treated as if they are columns. right_on : label or list, or array-like Column or index level names to join on in the right DataFrame. Can also be an array or list of arrays of the length of the right DataFrame. These arrays are treated as if they are columns. left_index : bool, default False Use the index from the left DataFrame as the join key(s). right_index : bool, default False Use the index from the right DataFrame as the join key. sort : bool, default False Sort the resulting dataframe by the columns that were merged on, starting from the left. suffixes: Tuple[str, str], defaults to ('_x', '_y') Suffixes applied to overlapping column names on the left and right sides method : {‘hash’, ‘sort’}, default ‘hash’ The implementation method to be used for the operation. Returns ------- merged : DataFrame Notes ----- **DataFrames merges in cuDF result in non-deterministic row ordering.** Examples -------- >>> import cudf >>> df_a = cudf.DataFrame() >>> df_a['key'] = [0, 1, 2, 3, 4] >>> df_a['vals_a'] = [float(i + 10) for i in range(5)] >>> df_b = cudf.DataFrame() >>> df_b['key'] = [1, 2, 4] >>> df_b['vals_b'] = [float(i+10) for i in range(3)] >>> df_merged = df_a.merge(df_b, on=['key'], how='left') >>> df_merged.sort_values('key') # doctest: +SKIP key vals_a vals_b 3 0 10.0 0 1 11.0 10.0 1 2 12.0 11.0 4 3 13.0 2 4 14.0 12.0 """ if indicator: raise NotImplementedError( "Only indicator=False is currently supported" ) if lsuffix or rsuffix: raise ValueError( "The lsuffix and rsuffix keywords have been replaced with the " "``suffixes=`` keyword. " "Please provide the following instead: \n\n" " suffixes=('%s', '%s')" % (lsuffix or "_x", rsuffix or "_y") ) else: lsuffix, rsuffix = suffixes lhs = self.copy(deep=False) rhs = right.copy(deep=False) # Compute merge gdf_result = super(DataFrame, lhs)._merge( rhs, on=on, left_on=left_on, right_on=right_on, left_index=left_index, right_index=right_index, how=how, sort=sort, lsuffix=lsuffix, rsuffix=rsuffix, method=method, indicator=indicator, suffixes=suffixes, ) return gdf_result @annotate("JOIN", color="blue", domain="cudf_python") def join( self, other, on=None, how="left", lsuffix="", rsuffix="", sort=False, method="hash", ): """Join columns with other DataFrame on index or on a key column. Parameters ---------- other : DataFrame how : str Only accepts "left", "right", "inner", "outer" lsuffix, rsuffix : str The suffices to add to the left (*lsuffix*) and right (*rsuffix*) column names when avoiding conflicts. sort : bool Set to True to ensure sorted ordering. Returns ------- joined : DataFrame Notes ----- Difference from pandas: - *other* must be a single DataFrame for now. - *on* is not supported yet due to lack of multi-index support. """ lhs = self rhs = other df = lhs.merge( rhs, left_index=True, right_index=True, how=how, suffixes=(lsuffix, rsuffix), method=method, sort=sort, ) df.index.name = ( None if lhs.index.name != rhs.index.name else lhs.index.name ) return df @copy_docstring(DataFrameGroupBy.__init__) def groupby( self, by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, observed=False, dropna=True, ): if axis not in (0, "index"): raise NotImplementedError("axis parameter is not yet implemented") if group_keys is not True: raise NotImplementedError( "The group_keys keyword is not yet implemented" ) if squeeze is not False: raise NotImplementedError( "squeeze parameter is not yet implemented" ) if observed is not False: raise NotImplementedError( "observed parameter is not yet implemented" ) if by is None and level is None: raise TypeError( "groupby() requires either by or level to be specified." ) return DataFrameGroupBy( self, by=by, level=level, as_index=as_index, dropna=dropna, sort=sort, ) @copy_docstring(Rolling) def rolling( self, window, min_periods=None, center=False, axis=0, win_type=None ): return Rolling( self, window, min_periods=min_periods, center=center, axis=axis, win_type=win_type, ) def query(self, expr, local_dict=None): """ Query with a boolean expression using Numba to compile a GPU kernel. See pandas.DataFrame.query. Parameters ---------- expr : str A boolean expression. Names in expression refer to columns. `index` can be used instead of index name, but this is not supported for MultiIndex. Names starting with `@` refer to Python variables. An output value will be `null` if any of the input values are `null` regardless of expression. local_dict : dict Containing the local variable to be used in query. Returns ------- filtered : DataFrame Examples -------- >>> import cudf >>> a = ('a', [1, 2, 2]) >>> b = ('b', [3, 4, 5]) >>> df = cudf.DataFrame([a, b]) >>> expr = "(a == 2 and b == 4) or (b == 3)" >>> df.query(expr) a b 0 1 3 1 2 4 DateTime conditionals: >>> import numpy as np >>> import datetime >>> df = cudf.DataFrame() >>> data = np.array(['2018-10-07', '2018-10-08'], dtype='datetime64') >>> df['datetimes'] = data >>> search_date = datetime.datetime.strptime('2018-10-08', '%Y-%m-%d') >>> df.query('datetimes==@search_date') datetimes 1 2018-10-08T00:00:00.000 Using local_dict: >>> import numpy as np >>> import datetime >>> df = cudf.DataFrame() >>> data = np.array(['2018-10-07', '2018-10-08'], dtype='datetime64') >>> df['datetimes'] = data >>> search_date2 = datetime.datetime.strptime('2018-10-08', '%Y-%m-%d') >>> df.query('datetimes==@search_date', ... local_dict={'search_date':search_date2}) datetimes 1 2018-10-08T00:00:00.000 """ # can't use `annotate` decorator here as we inspect the calling # environment. with annotate("QUERY", color="purple", domain="cudf_python"): if local_dict is None: local_dict = {} if self.empty: return self.copy() if not isinstance(local_dict, dict): raise TypeError( f"local_dict type: expected dict but found " f"{type(local_dict)}" ) # Get calling environment callframe = inspect.currentframe().f_back callenv = { "locals": callframe.f_locals, "globals": callframe.f_globals, "local_dict": local_dict, } # Run query boolmask = queryutils.query_execute(self, expr, callenv) return self._apply_boolean_mask(boolmask) @applyutils.doc_apply() def apply_rows( self, func, incols, outcols, kwargs, pessimistic_nulls=True, cache_key=None, ): """ Apply a row-wise user defined function. Parameters ---------- {params} Examples -------- The user function should loop over the columns and set the output for each row. Loop execution order is arbitrary, so each iteration of the loop **MUST** be independent of each other. When ``func`` is invoked, the array args corresponding to the input/output are strided so as to improve GPU parallelism. The loop in the function resembles serial code, but executes concurrently in multiple threads. >>> import cudf >>> import numpy as np >>> df = cudf.DataFrame() >>> nelem = 3 >>> df['in1'] = np.arange(nelem) >>> df['in2'] = np.arange(nelem) >>> df['in3'] = np.arange(nelem) Define input columns for the kernel >>> in1 = df['in1'] >>> in2 = df['in2'] >>> in3 = df['in3'] >>> def kernel(in1, in2, in3, out1, out2, kwarg1, kwarg2): ... for i, (x, y, z) in enumerate(zip(in1, in2, in3)): ... out1[i] = kwarg2 * x - kwarg1 * y ... out2[i] = y - kwarg1 * z Call ``.apply_rows`` with the name of the input columns, the name and dtype of the output columns, and, optionally, a dict of extra arguments. >>> df.apply_rows(kernel, ... incols=['in1', 'in2', 'in3'], ... outcols=dict(out1=np.float64, out2=np.float64), ... kwargs=dict(kwarg1=3, kwarg2=4)) in1 in2 in3 out1 out2 0 0 0 0 0.0 0.0 1 1 1 1 1.0 -2.0 2 2 2 2 2.0 -4.0 """ for col in incols: current_col_dtype = self._data[col].dtype if is_string_dtype(current_col_dtype) or is_categorical_dtype( current_col_dtype ): raise TypeError( "User defined functions are currently not " "supported on Series with dtypes `str` and `category`." ) return applyutils.apply_rows( self, func, incols, outcols, kwargs, pessimistic_nulls, cache_key=cache_key, ) @applyutils.doc_applychunks() def apply_chunks( self, func, incols, outcols, kwargs=None, pessimistic_nulls=True, chunks=None, blkct=None, tpb=None, ): """ Transform user-specified chunks using the user-provided function. Parameters ---------- {params} {params_chunks} Examples -------- For ``tpb > 1``, ``func`` is executed by ``tpb`` number of threads concurrently. To access the thread id and count, use ``numba.cuda.threadIdx.x`` and ``numba.cuda.blockDim.x``, respectively (See `numba CUDA kernel documentation`_). .. _numba CUDA kernel documentation:\ http://numba.pydata.org/numba-doc/latest/cuda/kernels.html In the example below, the *kernel* is invoked concurrently on each specified chunk. The *kernel* computes the corresponding output for the chunk. By looping over the range ``range(cuda.threadIdx.x, in1.size, cuda.blockDim.x)``, the *kernel* function can be used with any *tpb* in an efficient manner. >>> from numba import cuda >>> @cuda.jit ... def kernel(in1, in2, in3, out1): ... for i in range(cuda.threadIdx.x, in1.size, cuda.blockDim.x): ... x = in1[i] ... y = in2[i] ... z = in3[i] ... out1[i] = x * y + z See also -------- DataFrame.apply_rows """ if kwargs is None: kwargs = {} if chunks is None: raise ValueError("*chunks* must be defined") return applyutils.apply_chunks( self, func, incols, outcols, kwargs, pessimistic_nulls, chunks, tpb=tpb, ) def hash_columns(self, columns=None): """Hash the given *columns* and return a new device array Parameters ---------- columns : sequence of str; optional Sequence of column names. If columns is *None* (unspecified), all columns in the frame are used. """ if columns is None: table_to_hash = self else: cols = [self[k]._column for k in columns] table_to_hash = Frame(data=OrderedColumnDict(zip(columns, cols))) return Series(table_to_hash._hash()).values def partition_by_hash(self, columns, nparts, keep_index=True): """Partition the dataframe by the hashed value of data in *columns*. Parameters ---------- columns : sequence of str The names of the columns to be hashed. Must have at least one name. nparts : int Number of output partitions keep_index : boolean Whether to keep the index or drop it Returns ------- partitioned: list of DataFrame """ idx = ( 0 if (self._index is None or keep_index is False) else self._index._num_columns ) key_indices = [self._data.names.index(k) + idx for k in columns] outdf, offsets = self._hash_partition(key_indices, nparts, keep_index) # Slice into partition return [outdf[s:e] for s, e in zip(offsets, offsets[1:] + [None])] def replace( self, to_replace=None, value=None, inplace=False, limit=None, regex=False, method=None, ): """ Replace values given in *to_replace* with *replacement*. Parameters ---------- to_replace : numeric, str, list-like or dict Value(s) to replace. * numeric or str: - values equal to *to_replace* will be replaced with *replacement* * list of numeric or str: - If *replacement* is also list-like, *to_replace* and *replacement* must be of same length. * dict: - Dicts can be used to replace different values in different columns. For example, `{'a': 1, 'z': 2}` specifies that the value 1 in column `a` and the value 2 in column `z` should be replaced with replacement*. value : numeric, str, list-like, or dict Value(s) to replace `to_replace` with. If a dict is provided, then its keys must match the keys in *to_replace*, and corresponding values must be compatible (e.g., if they are lists, then they must match in length). inplace : bool, default False If True, in place. Returns ------- result : DataFrame DataFrame after replacement. Examples -------- >>> import cudf >>> df = cudf.DataFrame() >>> df['id']= [0, 1, 2, -1, 4, -1, 6] >>> df['id']= df['id'].replace(-1, None) >>> df id 0 0 1 1 2 2 3 <NA> 4 4 5 <NA> 6 6 Notes ----- Parameters that are currently not supported are: `limit`, `regex`, `method` """ if limit is not None: raise NotImplementedError("limit parameter is not implemented yet") if regex: raise NotImplementedError("regex parameter is not implemented yet") if method not in ("pad", None): raise NotImplementedError( "method parameter is not implemented yet" ) outdf = super().replace(to_replace=to_replace, replacement=value) return self._mimic_inplace(outdf, inplace=inplace) def info( self, verbose=None, buf=None, max_cols=None, memory_usage=None, null_counts=None, ): """ Print a concise summary of a DataFrame. This method prints information about a DataFrame including the index dtype and column dtypes, non-null values and memory usage. Parameters ---------- verbose : bool, optional Whether to print the full summary. By default, the setting in ``pandas.options.display.max_info_columns`` is followed. buf : writable buffer, defaults to sys.stdout Where to send the output. By default, the output is printed to sys.stdout. Pass a writable buffer if you need to further process the output. max_cols : int, optional When to switch from the verbose to the truncated output. If the DataFrame has more than `max_cols` columns, the truncated output is used. By default, the setting in ``pandas.options.display.max_info_columns`` is used. memory_usage : bool, str, optional Specifies whether total memory usage of the DataFrame elements (including the index) should be displayed. By default, this follows the ``pandas.options.display.memory_usage`` setting. True always show memory usage. False never shows memory usage. A value of 'deep' is equivalent to "True with deep introspection". Memory usage is shown in human-readable units (base-2 representation). Without deep introspection a memory estimation is made based in column dtype and number of rows assuming values consume the same memory amount for corresponding dtypes. With deep memory introspection, a real memory usage calculation is performed at the cost of computational resources. null_counts : bool, optional Whether to show the non-null counts. By default, this is shown only if the frame is smaller than ``pandas.options.display.max_info_rows`` and ``pandas.options.display.max_info_columns``. A value of True always shows the counts, and False never shows the counts. Returns ------- None This method prints a summary of a DataFrame and returns None. See Also -------- DataFrame.describe: Generate descriptive statistics of DataFrame columns. DataFrame.memory_usage: Memory usage of DataFrame columns. Examples -------- >>> import cudf >>> int_values = [1, 2, 3, 4, 5] >>> text_values = ['alpha', 'beta', 'gamma', 'delta', 'epsilon'] >>> float_values = [0.0, 0.25, 0.5, 0.75, 1.0] >>> df = cudf.DataFrame({"int_col": int_values, ... "text_col": text_values, ... "float_col": float_values}) >>> df int_col text_col float_col 0 1 alpha 0.00 1 2 beta 0.25 2 3 gamma 0.50 3 4 delta 0.75 4 5 epsilon 1.00 Prints information of all columns: >>> df.info(verbose=True) <class 'cudf.core.dataframe.DataFrame'> RangeIndex: 5 entries, 0 to 4 Data columns (total 3 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 int_col 5 non-null int64 1 text_col 5 non-null object 2 float_col 5 non-null float64 dtypes: float64(1), int64(1), object(1) memory usage: 130.0+ bytes Prints a summary of columns count and its dtypes but not per column information: >>> df.info(verbose=False) <class 'cudf.core.dataframe.DataFrame'> RangeIndex: 5 entries, 0 to 4 Columns: 3 entries, int_col to float_col dtypes: float64(1), int64(1), object(1) memory usage: 130.0+ bytes Pipe output of DataFrame.info to buffer instead of sys.stdout, get buffer content and writes to a text file: >>> import io >>> buffer = io.StringIO() >>> df.info(buf=buffer) >>> s = buffer.getvalue() >>> with open("df_info.txt", "w", ... encoding="utf-8") as f: ... f.write(s) ... 369 The `memory_usage` parameter allows deep introspection mode, specially useful for big DataFrames and fine-tune memory optimization: >>> import numpy as np >>> random_strings_array = np.random.choice(['a', 'b', 'c'], 10 ** 6) >>> df = cudf.DataFrame({ ... 'column_1': np.random.choice(['a', 'b', 'c'], 10 ** 6), ... 'column_2': np.random.choice(['a', 'b', 'c'], 10 ** 6), ... 'column_3': np.random.choice(['a', 'b', 'c'], 10 ** 6) ... }) >>> df.info(memory_usage='deep') <class 'cudf.core.dataframe.DataFrame'> RangeIndex: 1000000 entries, 0 to 999999 Data columns (total 3 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 column_1 1000000 non-null object 1 column_2 1000000 non-null object 2 column_3 1000000 non-null object dtypes: object(3) memory usage: 14.3 MB """ if buf is None: buf = sys.stdout lines = [str(type(self))] index_name = type(self._index).__name__ if len(self._index) > 0: entries_summary = f", {self._index[0]} to {self._index[-1]}" else: entries_summary = "" index_summary = ( f"{index_name}: {len(self._index)} entries{entries_summary}" ) lines.append(index_summary) if len(self.columns) == 0: lines.append(f"Empty {type(self).__name__}") cudf.utils.ioutils.buffer_write_lines(buf, lines) return cols = self.columns col_count = len(self.columns) if max_cols is None: max_cols = pd.options.display.max_info_columns max_rows = pd.options.display.max_info_rows if null_counts is None: show_counts = (col_count <= max_cols) and (len(self) < max_rows) else: show_counts = null_counts exceeds_info_cols = col_count > max_cols def _put_str(s, space): return str(s)[:space].ljust(space) def _verbose_repr(): lines.append(f"Data columns (total {len(self.columns)} columns):") id_head = " # " column_head = "Column" col_space = 2 max_col = max(len(pprint_thing(k)) for k in cols) len_column = len(pprint_thing(column_head)) space = max(max_col, len_column) + col_space max_id = len(pprint_thing(col_count)) len_id = len(pprint_thing(id_head)) space_num = max(max_id, len_id) + col_space counts = None header = _put_str(id_head, space_num) + _put_str( column_head, space ) if show_counts: counts = self.count().to_pandas().tolist() if len(cols) != len(counts): raise AssertionError( f"Columns must equal " f"counts ({len(cols)} != {len(counts)})" ) count_header = "Non-Null Count" len_count = len(count_header) non_null = " non-null" max_count = max(len(pprint_thing(k)) for k in counts) + len( non_null ) space_count = max(len_count, max_count) + col_space count_temp = "{count}" + non_null else: count_header = "" space_count = len(count_header) len_count = space_count count_temp = "{count}" dtype_header = "Dtype" len_dtype = len(dtype_header) max_dtypes = max(len(pprint_thing(k)) for k in self.dtypes) space_dtype = max(len_dtype, max_dtypes) header += ( _put_str(count_header, space_count) + _put_str(dtype_header, space_dtype).rstrip() ) lines.append(header) lines.append( _put_str("-" * len_id, space_num) + _put_str("-" * len_column, space) + _put_str("-" * len_count, space_count) + _put_str("-" * len_dtype, space_dtype).rstrip() ) for i, col in enumerate(self.columns): dtype = self.dtypes.iloc[i] col = pprint_thing(col) line_no = _put_str(" {num}".format(num=i), space_num) count = "" if show_counts: count = counts[i] lines.append( line_no + _put_str(col, space) + _put_str(count_temp.format(count=count), space_count) + _put_str(dtype, space_dtype).rstrip() ) def _non_verbose_repr(): if len(self.columns) > 0: entries_summary = f", {self.columns[0]} to {self.columns[-1]}" else: entries_summary = "" columns_summary = ( f"Columns: {len(self.columns)} entries{entries_summary}" ) lines.append(columns_summary) def _sizeof_fmt(num, size_qualifier): # returns size in human readable format for x in ["bytes", "KB", "MB", "GB", "TB"]: if num < 1024.0: return f"{num:3.1f}{size_qualifier} {x}" num /= 1024.0 return f"{num:3.1f}{size_qualifier} PB" if verbose: _verbose_repr() elif verbose is False: # specifically set to False, not nesc None _non_verbose_repr() else: if exceeds_info_cols: _non_verbose_repr() else: _verbose_repr() dtype_counts = defaultdict(int) for col in self._data: dtype_counts[self._data[col].dtype.name] += 1 dtypes = [f"{k[0]}({k[1]:d})" for k in sorted(dtype_counts.items())] lines.append(f"dtypes: {', '.join(dtypes)}") if memory_usage is None: memory_usage = pd.options.display.memory_usage if memory_usage: # append memory usage of df to display size_qualifier = "" if memory_usage == "deep": deep = True else: deep = False if "object" in dtype_counts or self.index.dtype == "object": size_qualifier = "+" mem_usage = self.memory_usage(index=True, deep=deep).sum() lines.append( f"memory usage: {_sizeof_fmt(mem_usage, size_qualifier)}\n" ) cudf.utils.ioutils.buffer_write_lines(buf, lines) @docutils.doc_describe() def describe( self, percentiles=None, include=None, exclude=None, datetime_is_numeric=False, ): """{docstring}""" if not include and not exclude: default_include = [np.number] if datetime_is_numeric: default_include.append("datetime") data_to_describe = self.select_dtypes(include=default_include) if len(data_to_describe.columns) == 0: data_to_describe = self elif include == "all": if exclude is not None: raise ValueError("exclude must be None when include is 'all'") data_to_describe = self else: data_to_describe = self.select_dtypes( include=include, exclude=exclude ) if data_to_describe.empty: raise ValueError("No data of included types.") describe_series_list = [ data_to_describe[col].describe(percentiles=percentiles) for col in data_to_describe.columns ] if len(describe_series_list) == 1: return describe_series_list[0].to_frame() else: ldesc_indexes = sorted( (x.index for x in describe_series_list), key=len ) names = OrderedDict.fromkeys( [ name for idxnames in ldesc_indexes for name in idxnames.to_pandas() ], None, ) return cudf.concat( [ series.reindex(names, copy=False) for series in describe_series_list ], axis=1, sort=False, ) def to_pandas(self, nullable=False, **kwargs): """ Convert to a Pandas DataFrame. Parameters ---------- nullable : Boolean, Default False If ``nullable`` is ``True``, the resulting columns in the dataframe will be having a corresponding nullable Pandas dtype. If ``nullable`` is ``False``, the resulting columns will either convert null values to ``np.nan`` or ``None`` depending on the dtype. Returns ------- out : Pandas DataFrame Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [0, 1, 2], 'b': [-3, 2, 0]}) >>> pdf = df.to_pandas() >>> pdf a b 0 0 -3 1 1 2 2 2 0 >>> type(pdf) <class 'pandas.core.frame.DataFrame'> ``nullable`` parameter can be used to control whether dtype can be Pandas Nullable or not: >>> df = cudf.DataFrame({'a': [0, None, 2], 'b': [True, False, None]}) >>> df a b 0 0 True 1 <NA> False 2 2 <NA> >>> pdf = df.to_pandas(nullable=True) >>> pdf a b 0 0 True 1 <NA> False 2 2 <NA> >>> pdf.dtypes a Int64 b boolean dtype: object >>> pdf = df.to_pandas(nullable=False) >>> pdf a b 0 0.0 True 1 NaN False 2 2.0 None >>> pdf.dtypes a float64 b object dtype: object """ out_data = {} out_index = self.index.to_pandas() if not isinstance(self.columns, pd.Index): out_columns = self.columns.to_pandas() else: out_columns = self.columns for i, col_key in enumerate(self._data): out_data[i] = self._data[col_key].to_pandas( index=out_index, nullable=nullable ) if isinstance(self.columns, Index): out_columns = self.columns.to_pandas() if isinstance(self.columns, cudf.core.multiindex.MultiIndex): if self.columns.names is not None: out_columns.names = self.columns.names else: out_columns.name = self.columns.name out_df = pd.DataFrame(out_data, index=out_index) out_df.columns = out_columns return out_df @classmethod def from_pandas(cls, dataframe, nan_as_null=None): """ Convert from a Pandas DataFrame. Parameters ---------- dataframe : Pandas DataFrame object A Pandads DataFrame object which has to be converted to cuDF DataFrame. nan_as_null : bool, Default True If ``True``, converts ``np.nan`` values to ``null`` values. If ``False``, leaves ``np.nan`` values as is. Raises ------ TypeError for invalid input type. Examples -------- >>> import cudf >>> import pandas as pd >>> data = [[0,1], [1,2], [3,4]] >>> pdf = pd.DataFrame(data, columns=['a', 'b'], dtype=int) >>> cudf.from_pandas(pdf) a b 0 0 1 1 1 2 2 3 4 """ if not isinstance(dataframe, pd.DataFrame): raise TypeError("not a pandas.DataFrame") if not dataframe.columns.is_unique: raise ValueError("Duplicate column names are not allowed") df = cls() # Set columns for col_name, col_value in dataframe.iteritems(): # necessary because multi-index can return multiple # columns for a single key if len(col_value.shape) == 1: df[col_name] = column.as_column( col_value.array, nan_as_null=nan_as_null ) else: vals = col_value.values.T if vals.shape[0] == 1: df[col_name] = column.as_column( vals.flatten(), nan_as_null=nan_as_null ) else: if isinstance(col_name, tuple): col_name = str(col_name) for idx in range(len(vals.shape)): df[col_name] = column.as_column( vals[idx], nan_as_null=nan_as_null ) # Set columns only if it is a MultiIndex if isinstance(dataframe.columns, pd.MultiIndex): df.columns = dataframe.columns # Set index index = cudf.from_pandas(dataframe.index, nan_as_null=nan_as_null) result = df.set_index(index) return result @classmethod def from_arrow(cls, table): """ Convert from PyArrow Table to DataFrame. Parameters ---------- table : PyArrow Table Object PyArrow Table Object which has to be converted to cudf DataFrame. Raises ------ TypeError for invalid input type. Returns ------- cudf DataFrame Notes ----- - Does not support automatically setting index column(s) similar to how ``to_pandas`` works for PyArrow Tables. Examples -------- >>> import cudf >>> import pyarrow as pa >>> data = pa.table({"a":[1, 2, 3], "b":[4, 5, 6]}) >>> cudf.DataFrame.from_arrow(data) a b 0 1 4 1 2 5 2 3 6 """ index_col = None if isinstance(table, pa.Table) and isinstance( table.schema.pandas_metadata, dict ): index_col = table.schema.pandas_metadata["index_columns"] out = super().from_arrow(table) if index_col: if isinstance(index_col[0], dict): out = out.set_index( cudf.RangeIndex( index_col[0]["start"], index_col[0]["stop"], name=index_col[0]["name"], ) ) else: out = out.set_index(index_col[0]) return out def to_arrow(self, preserve_index=True): """ Convert to a PyArrow Table. Parameters ---------- preserve_index : bool, default True whether index column and its meta data needs to be saved or not Returns ------- PyArrow Table Examples -------- >>> import cudf >>> df = cudf.DataFrame( ... {"a":[1, 2, 3], "b":[4, 5, 6]}, index=[1, 2, 3]) >>> df.to_arrow() pyarrow.Table a: int64 b: int64 index: int64 >>> df.to_arrow(preserve_index=False) pyarrow.Table a: int64 b: int64 """ data = self.copy(deep=False) index_descr = [] if preserve_index: if isinstance(self.index, cudf.RangeIndex): descr = { "kind": "range", "name": self.index.name, "start": self.index._start, "stop": self.index._stop, "step": 1, } else: if isinstance(self.index, cudf.MultiIndex): gen_names = tuple( f"level_{i}" for i, _ in enumerate(self.index._data.names) ) else: gen_names = ( self.index.names if self.index.name is not None else ("index",) ) for gen_name, col_name in zip( gen_names, self.index._data.names ): data.insert( data.shape[1], gen_name, self.index._data[col_name] ) descr = gen_names[0] index_descr.append(descr) out = super(DataFrame, data).to_arrow() metadata = pa.pandas_compat.construct_metadata( self, out.schema.names, [self.index], index_descr, preserve_index, types=out.schema.types, ) return out.replace_schema_metadata(metadata) def to_records(self, index=True): """Convert to a numpy recarray Parameters ---------- index : bool Whether to include the index in the output. Returns ------- numpy recarray """ members = [("index", self.index.dtype)] if index else [] members += [(col, self[col].dtype) for col in self._data.names] dtype = np.dtype(members) ret = np.recarray(len(self), dtype=dtype) if index: ret["index"] = self.index.to_array() for col in self._data.names: ret[col] = self[col].to_array() return ret @classmethod def from_records(cls, data, index=None, columns=None, nan_as_null=False): """ Convert structured or record ndarray to DataFrame. Parameters ---------- data : numpy structured dtype or recarray of ndim=2 index : str, array-like The name of the index column in *data*. If None, the default index is used. columns : list of str List of column names to include. Returns ------- DataFrame """ if data.ndim != 1 and data.ndim != 2: raise ValueError( f"records dimension expected 1 or 2 but found {data.ndim}" ) num_cols = len(data[0]) if columns is None and data.dtype.names is None: names = [i for i in range(num_cols)] elif data.dtype.names is not None: names = data.dtype.names else: if len(columns) != num_cols: raise ValueError( f"columns length expected {num_cols} " f"but found {len(columns)}" ) names = columns df = DataFrame() if data.ndim == 2: for i, k in enumerate(names): df._data[k] = column.as_column( data[:, i], nan_as_null=nan_as_null ) elif data.ndim == 1: for k in names: df._data[k] = column.as_column( data[k], nan_as_null=nan_as_null ) if index is None: df._index = RangeIndex(start=0, stop=len(data)) elif is_scalar(index): df._index = RangeIndex(start=0, stop=len(data)) df = df.set_index(index) else: df._index = as_index(index) return df @classmethod def _from_arrays(cls, data, index=None, columns=None, nan_as_null=False): """Convert a numpy/cupy array to DataFrame. Parameters ---------- data : numpy/cupy array of ndim 1 or 2, dimensions greater than 2 are not supported yet. index : Index or array-like Index to use for resulting frame. Will default to RangeIndex if no indexing information part of input data and no index provided. columns : list of str List of column names to include. Returns ------- DataFrame """ data = cupy.asarray(data) if data.ndim != 1 and data.ndim != 2: raise ValueError( f"records dimension expected 1 or 2 but found: {data.ndim}" ) if data.ndim == 2: num_cols = len(data[0]) else: # Since we validate ndim to be either 1 or 2 above, # this case can be assumed to be ndim == 1. num_cols = 1 if columns is None: names = [i for i in range(num_cols)] else: if len(columns) != num_cols: raise ValueError( f"columns length expected {num_cols} but " f"found {len(columns)}" ) names = columns df = cls() if data.ndim == 2: for i, k in enumerate(names): df._data[k] = column.as_column( data[:, i], nan_as_null=nan_as_null ) elif data.ndim == 1: df._data[names[0]] = column.as_column( data, nan_as_null=nan_as_null ) if index is None: df._index = RangeIndex(start=0, stop=len(data)) else: df._index = as_index(index) return df @classmethod def _from_columns(cls, cols, index=None, columns=None): """ Construct a DataFrame from a list of Columns """ if columns is not None: data = dict(zip(columns, cols)) else: data = dict(enumerate(cols)) return cls(data=data, index=index,) def quantile( self, q=0.5, axis=0, numeric_only=True, interpolation="linear", columns=None, exact=True, ): """ Return values at the given quantile. Parameters ---------- q : float or array-like 0 <= q <= 1, the quantile(s) to compute axis : int axis is a NON-FUNCTIONAL parameter numeric_only : bool, default True If False, the quantile of datetime and timedelta data will be computed as well. interpolation : {`linear`, `lower`, `higher`, `midpoint`, `nearest`} This parameter specifies the interpolation method to use, when the desired quantile lies between two data points i and j. Default ``linear``. columns : list of str List of column names to include. exact : boolean Whether to use approximate or exact quantile algorithm. Returns ------- Series or DataFrame If q is an array or numeric_only is set to False, a DataFrame will be returned where index is q, the columns are the columns of self, and the values are the quantile. If q is a float, a Series will be returned where the index is the columns of self and the values are the quantiles. Notes ----- One notable difference from Pandas is when DataFrame is of non-numeric types and result is expected to be a Series in case of Pandas. cuDF will return a DataFrame as it doesn't support mixed types under Series. """ if axis not in (0, None): raise NotImplementedError("axis is not implemented yet") if numeric_only: data_df = self.select_dtypes( include=[np.number], exclude=["datetime64", "timedelta64"] ) else: data_df = self if columns is None: columns = data_df._data.names result = DataFrame() for k in data_df._data.names: if k in columns: res = data_df[k].quantile( q, interpolation=interpolation, exact=exact, quant_index=False, ) if ( not isinstance( res, (numbers.Number, pd.Timestamp, pd.Timedelta) ) and len(res) == 0 ): res = column.column_empty_like( q, dtype=data_df[k].dtype, masked=True, newsize=len(q) ) result[k] = column.as_column(res) if isinstance(q, numbers.Number) and numeric_only: result = result.fillna(np.nan) result = result.iloc[0] result.index = as_index(data_df.columns) result.name = q return result else: q = list(map(float, [q] if isinstance(q, numbers.Number) else q)) result.index = q return result def quantiles(self, q=0.5, interpolation="nearest"): """ Return values at the given quantile. Parameters ---------- q : float or array-like 0 <= q <= 1, the quantile(s) to compute interpolation : {`lower`, `higher`, `nearest`} This parameter specifies the interpolation method to use, when the desired quantile lies between two data points i and j. Default 'nearest'. Returns ------- DataFrame """ if isinstance(q, numbers.Number): q_is_number = True q = [float(q)] elif pd.api.types.is_list_like(q): q_is_number = False else: msg = "`q` must be either a single element or list" raise TypeError(msg) result = self._quantiles(q, interpolation.upper()) if q_is_number: result = result.transpose() return Series( data=result._columns[0], index=result.index, name=q[0] ) else: result.index = as_index(q) return result def isin(self, values): """ Whether each element in the DataFrame is contained in values. Parameters ---------- values : iterable, Series, DataFrame or dict The result will only be true at a location if all the labels match. If values is a Series, that’s the index. If values is a dict, the keys must be the column names, which must match. If values is a DataFrame, then both the index and column labels must match. Returns ------- DataFrame: DataFrame of booleans showing whether each element in the DataFrame is contained in values. """ if isinstance(values, dict): result_df = DataFrame() for col in self._data.names: if col in values: val = values[col] result_df[col] = self._data[col].isin(val) else: result_df[col] = column.full( size=len(self), fill_value=False, dtype="bool" ) result_df.index = self.index return result_df elif isinstance(values, Series): values = values.reindex(self.index) result = DataFrame() for col in self._data.names: if isinstance( self[col]._column, cudf.core.column.CategoricalColumn ) and isinstance( values._column, cudf.core.column.CategoricalColumn ): res = self._data[col] == values._column result[col] = res elif ( isinstance( self[col]._column, cudf.core.column.CategoricalColumn ) or np.issubdtype(self[col].dtype, np.dtype("object")) ) or ( isinstance( values._column, cudf.core.column.CategoricalColumn ) or np.issubdtype(values.dtype, np.dtype("object")) ): result[col] = utils.scalar_broadcast_to(False, len(self)) else: result[col] = self._data[col] == values._column result.index = self.index return result elif isinstance(values, DataFrame): values = values.reindex(self.index) result = DataFrame() for col in self._data.names: if col in values.columns: result[col] = self._data[col] == values[col]._column else: result[col] = utils.scalar_broadcast_to(False, len(self)) result.index = self.index return result else: if not is_list_like(values): raise TypeError( f"only list-like or dict-like objects are " f"allowed to be passed to DataFrame.isin(), " f"you passed a " f"'{type(values).__name__}'" ) result_df = DataFrame() for col in self._data.names: result_df[col] = self._data[col].isin(values) result_df.index = self.index return result_df # # Stats # def _prepare_for_rowwise_op(self, method, skipna): """Prepare a DataFrame for CuPy-based row-wise operations. """ if method not in _cupy_nan_methods_map and any( col.nullable for col in self._columns ): msg = ( f"Row-wise operations to calculate '{method}' is not " f"currently support columns with null values. " f"Consider removing them with .dropna() " f"or using .fillna()." ) raise ValueError(msg) is_pure_dt = all(is_datetime_dtype(dt) for dt in self.dtypes) if not is_pure_dt: filtered = self.select_dtypes(include=[np.number, np.bool]) else: filtered = self.copy(deep=False) common_dtype = find_common_type(filtered.dtypes) if filtered._num_columns < self._num_columns: msg = ( "Row-wise operations currently only support int, float " "and bool dtypes. Non numeric columns are ignored." ) warnings.warn(msg) if not skipna and any(col.nullable for col in filtered._columns): mask = cudf.DataFrame( { name: filtered._data[name]._get_mask_as_column() if filtered._data[name].nullable else column.full(len(filtered._data[name]), True) for name in filtered._data.names } ) mask = mask.all(axis=1) else: mask = None coerced = filtered.astype(common_dtype, copy=False) if is_pure_dt: # Further convert into cupy friendly types coerced = coerced.astype("int64", copy=False) return coerced, mask, common_dtype def count(self, axis=0, level=None, numeric_only=False, **kwargs): """ Count ``non-NA`` cells for each column or row. The values ``None``, ``NaN``, ``NaT`` are considered ``NA``. Returns ------- Series For each column/row the number of non-NA/null entries. Notes ----- Parameters currently not supported are `axis`, `level`, `numeric_only`. Examples -------- >>> import cudf >>> import numpy as np >>> df = cudf.DataFrame({"Person": ... ["John", "Myla", "Lewis", "John", "Myla"], ... "Age": [24., np.nan, 21., 33, 26], ... "Single": [False, True, True, True, False]}) >>> df.count() Person 5 Age 4 Single 5 dtype: int64 """ if axis not in (0, "index", None): raise NotImplementedError("Only axis=0 is currently supported.") return self._apply_support_method( "count", axis=axis, level=level, numeric_only=numeric_only, **kwargs, ) def min( self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs, ): """ Return the minimum of the values in the DataFrame. Parameters ---------- axis: {index (0), columns(1)} Axis for the function to be applied on. skipna: bool, default True Exclude NA/null values when computing the result. level: int or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series. numeric_only: bool, default None Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Returns ------- Series Notes ----- Parameters currently not supported are `level`, `numeric_only`. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.min() a 1 b 7 dtype: int64 """ return self._apply_support_method( "min", axis=axis, skipna=skipna, level=level, numeric_only=numeric_only, **kwargs, ) def max( self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs, ): """ Return the maximum of the values in the DataFrame. Parameters ---------- axis: {index (0), columns(1)} Axis for the function to be applied on. skipna: bool, default True Exclude NA/null values when computing the result. level: int or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series. numeric_only: bool, default None Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Returns ------- Series Notes ----- Parameters currently not supported are `level`, `numeric_only`. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.max() a 4 b 10 dtype: int64 """ return self._apply_support_method( "max", axis=axis, skipna=skipna, level=level, numeric_only=numeric_only, **kwargs, ) def sum( self, axis=None, skipna=None, dtype=None, level=None, numeric_only=None, min_count=0, **kwargs, ): """ Return sum of the values in the DataFrame. Parameters ---------- axis: {index (0), columns(1)} Axis for the function to be applied on. skipna: bool, default True Exclude NA/null values when computing the result. dtype: data type Data type to cast the result to. min_count: int, default 0 The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA. The default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty Series is 1. Returns ------- Series Notes ----- Parameters currently not supported are `level`, `numeric_only`. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.sum() a 10 b 34 dtype: int64 """ return self._apply_support_method( "sum", axis=axis, skipna=skipna, dtype=dtype, level=level, numeric_only=numeric_only, min_count=min_count, **kwargs, ) def product( self, axis=None, skipna=None, dtype=None, level=None, numeric_only=None, min_count=0, **kwargs, ): """ Return product of the values in the DataFrame. Parameters ---------- axis: {index (0), columns(1)} Axis for the function to be applied on. skipna: bool, default True Exclude NA/null values when computing the result. dtype: data type Data type to cast the result to. min_count: int, default 0 The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA. The default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty Series is 1. Returns ------- Series Notes ----- Parameters currently not supported are level`, `numeric_only`. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.product() a 24 b 5040 dtype: int64 """ return self._apply_support_method( "prod", axis=axis, skipna=skipna, dtype=dtype, level=level, numeric_only=numeric_only, min_count=min_count, **kwargs, ) def prod( self, axis=None, skipna=None, dtype=None, level=None, numeric_only=None, min_count=0, **kwargs, ): """ Return product of the values in the DataFrame. Parameters ---------- axis: {index (0), columns(1)} Axis for the function to be applied on. skipna: bool, default True Exclude NA/null values when computing the result. dtype: data type Data type to cast the result to. min_count: int, default 0 The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA. The default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty Series is 1. Returns ------- scalar Notes ----- Parameters currently not supported are `level`, `numeric_only`. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.prod() a 24 b 5040 dtype: int64 """ return self.product( axis=axis, skipna=skipna, dtype=dtype, level=level, numeric_only=numeric_only, min_count=min_count, **kwargs, ) def cummin(self, axis=None, skipna=True, *args, **kwargs): """ Return cumulative minimum of the DataFrame. Parameters ---------- skipna: bool, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. Returns ------- DataFrame Notes ----- Parameters currently not supported is `axis` Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.cummin() a b 0 1 7 1 1 7 2 1 7 3 1 7 """ if axis not in (0, "index", None): raise NotImplementedError("Only axis=0 is currently supported.") return self._apply_support_method( "cummin", axis=axis, skipna=skipna, *args, **kwargs ) def cummax(self, axis=None, skipna=True, *args, **kwargs): """ Return cumulative maximum of the DataFrame. Parameters ---------- skipna: bool, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. Returns ------- DataFrame Notes ----- Parameters currently not supported is `axis` Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.cummax() a b 0 1 7 1 2 8 2 3 9 3 4 10 """ if axis not in (0, "index", None): raise NotImplementedError("Only axis=0 is currently supported.") return self._apply_support_method( "cummax", axis=axis, skipna=skipna, *args, **kwargs ) def cumsum(self, axis=None, skipna=True, *args, **kwargs): """ Return cumulative sum of the DataFrame. Parameters ---------- skipna: bool, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. Returns ------- DataFrame Notes ----- Parameters currently not supported is `axis` Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> s.cumsum() a b 0 1 7 1 3 15 2 6 24 3 10 34 """ if axis not in (0, "index", None): raise NotImplementedError("Only axis=0 is currently supported.") return self._apply_support_method( "cumsum", axis=axis, skipna=skipna, *args, **kwargs ) def cumprod(self, axis=None, skipna=True, *args, **kwargs): """ Return cumulative product of the DataFrame. Parameters ---------- skipna: bool, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. Returns ------- DataFrame Notes ----- Parameters currently not supported is `axis` Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> s.cumprod() a b 0 1 7 1 2 56 2 6 504 3 24 5040 """ if axis not in (0, "index", None): raise NotImplementedError("Only axis=0 is currently supported.") return self._apply_support_method( "cumprod", axis=axis, skipna=skipna, *args, **kwargs ) def mean( self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs ): """ Return the mean of the values for the requested axis. Parameters ---------- axis : {0 or 'index', 1 or 'columns'} Axis for the function to be applied on. skipna : bool, default True Exclude NA/null values when computing the result. level : int or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series. numeric_only : bool, default None Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. **kwargs Additional keyword arguments to be passed to the function. Returns ------- mean : Series or DataFrame (if level specified) Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.mean() a 2.5 b 8.5 dtype: float64 """ return self._apply_support_method( "mean", axis=axis, skipna=skipna, level=level, numeric_only=numeric_only, **kwargs, ) def mode(self, axis=0, numeric_only=False, dropna=True): """ Get the mode(s) of each element along the selected axis. The mode of a set of values is the value that appears most often. It can be multiple values. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to iterate over while searching for the mode: - 0 or 'index' : get mode of each column - 1 or 'columns' : get mode of each row. numeric_only : bool, default False If True, only apply to numeric columns. dropna : bool, default True Don't consider counts of NA/NaN/NaT. Returns ------- DataFrame The modes of each column or row. See Also -------- cudf.core.series.Series.mode : Return the highest frequency value in a Series. cudf.core.series.Series.value_counts : Return the counts of values in a Series. Notes ----- ``axis`` parameter is currently not supported. Examples -------- >>> import cudf >>> df = cudf.DataFrame({ ... "species": ["bird", "mammal", "arthropod", "bird"], ... "legs": [2, 4, 8, 2], ... "wings": [2.0, None, 0.0, None] ... }) >>> df species legs wings 0 bird 2 2.0 1 mammal 4 <NA> 2 arthropod 8 0.0 3 bird 2 <NA> By default, missing values are not considered, and the mode of wings are both 0 and 2. The second row of species and legs contains ``NA``, because they have only one mode, but the DataFrame has two rows. >>> df.mode() species legs wings 0 bird 2 0.0 1 <NA> <NA> 2.0 Setting ``dropna=False``, ``NA`` values are considered and they can be the mode (like for wings). >>> df.mode(dropna=False) species legs wings 0 bird 2 <NA> Setting ``numeric_only=True``, only the mode of numeric columns is computed, and columns of other types are ignored. >>> df.mode(numeric_only=True) legs wings 0 2 0.0 1 <NA> 2.0 """ if axis not in (0, "index"): raise NotImplementedError("Only axis=0 is currently supported") if numeric_only: data_df = self.select_dtypes( include=[np.number], exclude=["datetime64", "timedelta64"] ) else: data_df = self mode_results = [ data_df[col].mode(dropna=dropna) for col in data_df._data ] if len(mode_results) == 0: df = DataFrame(index=self.index) return df df = cudf.concat(mode_results, axis=1) if isinstance(df, Series): df = df.to_frame() df.columns = data_df.columns return df def std( self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs, ): """ Return sample standard deviation of the DataFrame. Normalized by N-1 by default. This can be changed using the `ddof` argument Parameters ---------- axis: {index (0), columns(1)} Axis for the function to be applied on. skipna: bool, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. ddof: int, default 1 Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. Returns ------- Series Notes ----- Parameters currently not supported are `level` and `numeric_only` Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.std() a 1.290994 b 1.290994 dtype: float64 """ return self._apply_support_method( "std", axis=axis, skipna=skipna, level=level, ddof=ddof, numeric_only=numeric_only, **kwargs, ) def var( self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs, ): """ Return unbiased variance of the DataFrame. Normalized by N-1 by default. This can be changed using the ddof argument Parameters ---------- axis: {index (0), columns(1)} Axis for the function to be applied on. skipna: bool, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. ddof: int, default 1 Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. Returns ------- scalar Notes ----- Parameters currently not supported are `level` and `numeric_only` Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.var() a 1.666667 b 1.666667 dtype: float64 """ return self._apply_support_method( "var", axis=axis, skipna=skipna, level=level, ddof=ddof, numeric_only=numeric_only, **kwargs, ) def kurtosis( self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs ): """ Return Fisher's unbiased kurtosis of a sample. Kurtosis obtained using Fisher’s definition of kurtosis (kurtosis of normal == 0.0). Normalized by N-1. Parameters ---------- skipna: bool, default True Exclude NA/null values when computing the result. Returns ------- Series Notes ----- Parameters currently not supported are `axis`, `level` and `numeric_only` Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]}) >>> df.kurt() a -1.2 b -1.2 dtype: float64 """ if axis not in (0, "index", None): raise NotImplementedError("Only axis=0 is currently supported.") if numeric_only not in (None, True): msg = "Kurtosis only supports int, float, and bool dtypes." raise NotImplementedError(msg) self = self.select_dtypes(include=[np.number, np.bool]) return self._apply_support_method( "kurtosis", axis=axis, skipna=skipna, level=level, numeric_only=numeric_only, **kwargs, ) # Alias for kurtosis. kurt = kurtosis def skew( self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs ): """ Return unbiased Fisher-Pearson skew of a sample. Parameters ---------- skipna: bool, default True Exclude NA/null values when computing the result. Returns ------- Series Notes ----- Parameters currently not supported are `axis`, `level` and `numeric_only` Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [3, 2, 3, 4], 'b': [7, 8, 10, 10]}) >>> df.skew() a 0.00000 b -0.37037 dtype: float64 """ if axis not in (0, "index", None): raise NotImplementedError("Only axis=0 is currently supported.") if numeric_only not in (None, True): msg = "Skew only supports int, float, and bool dtypes." raise NotImplementedError(msg) self = self.select_dtypes(include=[np.number, np.bool]) return self._apply_support_method( "skew", axis=axis, skipna=skipna, level=level, numeric_only=numeric_only, **kwargs, ) def all(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): """ Return whether all elements are True in DataFrame. Parameters ---------- skipna: bool, default True Exclude NA/null values. If the entire row/column is NA and skipna is True, then the result will be True, as for an empty row/column. If skipna is False, then NA are treated as True, because these are not equal to zero. Returns ------- Series Notes ----- Parameters currently not supported are `axis`, `bool_only`, `level`. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [3, 2, 3, 4], 'b': [7, 0, 10, 10]}) >>> df.all() a True b False dtype: bool """ if bool_only: return self.select_dtypes(include="bool")._apply_support_method( "all", axis=axis, bool_only=bool_only, skipna=skipna, level=level, **kwargs, ) return self._apply_support_method( "all", axis=axis, bool_only=bool_only, skipna=skipna, level=level, **kwargs, ) def any(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): """ Return whether any elements is True in DataFrame. Parameters ---------- skipna: bool, default True Exclude NA/null values. If the entire row/column is NA and skipna is True, then the result will be False, as for an empty row/column. If skipna is False, then NA are treated as True, because these are not equal to zero. Returns ------- Series Notes ----- Parameters currently not supported are `axis`, `bool_only`, `level`. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [3, 2, 3, 4], 'b': [7, 0, 10, 10]}) >>> df.any() a True b True dtype: bool """ if bool_only: return self.select_dtypes(include="bool")._apply_support_method( "any", axis=axis, bool_only=bool_only, skipna=skipna, level=level, **kwargs, ) return self._apply_support_method( "any", axis=axis, bool_only=bool_only, skipna=skipna, level=level, **kwargs, ) def _apply_support_method(self, method, axis=0, *args, **kwargs): assert axis in (None, 0, 1) if axis in (None, 0): result = [ getattr(self[col], method)(*args, **kwargs) for col in self._data.names ] if isinstance(result[0], Series): support_result = result result = DataFrame(index=support_result[0].index) for idx, col in enumerate(self._data.names): result[col] = support_result[idx] else: result = Series(result) result = result.set_index(self._data.names) return result elif axis == 1: # for dask metadata compatibility skipna = kwargs.pop("skipna", None) if method not in _cupy_nan_methods_map and skipna not in ( None, True, 1, ): raise NotImplementedError( f"Row-wise operation to calculate '{method}'" f" currently do not support `skipna=False`." ) level = kwargs.pop("level", None) if level not in (None,): raise NotImplementedError( "Row-wise operations currently do not support `level`." ) numeric_only = kwargs.pop("numeric_only", None) if numeric_only not in (None, True): raise NotImplementedError( "Row-wise operations currently do not " "support `numeric_only=False`." ) min_count = kwargs.pop("min_count", None) if min_count not in (None, 0): raise NotImplementedError( "Row-wise operations currently do not " "support `min_count`." ) bool_only = kwargs.pop("bool_only", None) if bool_only not in (None, True): raise NotImplementedError( "Row-wise operations currently do not " "support `bool_only`." ) prepared, mask, common_dtype = self._prepare_for_rowwise_op( method, skipna ) for col in prepared._data.names: if prepared._data[col].nullable: prepared._data[col] = ( prepared._data[col] .astype( cudf.utils.dtypes.get_min_float_dtype( prepared._data[col] ) if not is_datetime_dtype(common_dtype) else np.dtype("float64") ) .fillna(np.nan) ) arr = cupy.asarray(prepared.as_gpu_matrix()) if skipna is not False and method in _cupy_nan_methods_map: method = _cupy_nan_methods_map[method] result = getattr(cupy, method)(arr, axis=1, **kwargs) if result.ndim == 1: type_coerced_methods = { "count", "min", "max", "sum", "prod", "cummin", "cummax", "cumsum", "cumprod", } result_dtype = ( common_dtype if method in type_coerced_methods or is_datetime_dtype(common_dtype) else None ) result = column.as_column(result, dtype=result_dtype) if mask is not None: result = result.set_mask( cudf._lib.transform.bools_to_mask(mask._column) ) return Series(result, index=self.index, dtype=result_dtype,) else: result_df = DataFrame(result).set_index(self.index) result_df.columns = prepared.columns return result_df def _columns_view(self, columns): """ Return a subset of the DataFrame's columns as a view. """ result_columns = OrderedDict({}) for col in columns: result_columns[col] = self._data[col] return DataFrame(result_columns, index=self.index) def select_dtypes(self, include=None, exclude=None): """Return a subset of the DataFrame’s columns based on the column dtypes. Parameters ---------- include : str or list which columns to include based on dtypes exclude : str or list which columns to exclude based on dtypes Returns ------- DataFrame The subset of the frame including the dtypes in ``include`` and excluding the dtypes in ``exclude``. Raises ------ ValueError - If both of ``include`` and ``exclude`` are empty - If ``include`` and ``exclude`` have overlapping elements Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a': [1, 2] * 3, ... 'b': [True, False] * 3, ... 'c': [1.0, 2.0] * 3}) >>> df a b c 0 1 True 1.0 1 2 False 2.0 2 1 True 1.0 3 2 False 2.0 4 1 True 1.0 5 2 False 2.0 >>> df.select_dtypes(include='bool') b 0 True 1 False 2 True 3 False 4 True 5 False >>> df.select_dtypes(include=['float64']) c 0 1.0 1 2.0 2 1.0 3 2.0 4 1.0 5 2.0 >>> df.select_dtypes(exclude=['int']) b c 0 True 1.0 1 False 2.0 2 True 1.0 3 False 2.0 4 True 1.0 5 False 2.0 """ # code modified from: # https://github.com/pandas-dev/pandas/blob/master/pandas/core/frame.py#L3196 if not isinstance(include, (list, tuple)): include = (include,) if include is not None else () if not isinstance(exclude, (list, tuple)): exclude = (exclude,) if exclude is not None else () df = DataFrame(index=self.index) # cudf_dtype_from_pydata_dtype can distinguish between # np.float and np.number selection = tuple(map(frozenset, (include, exclude))) if not any(selection): raise ValueError( "at least one of include or exclude must be nonempty" ) include, exclude = map( lambda x: frozenset(map(cudf_dtype_from_pydata_dtype, x)), selection, ) # can't both include AND exclude! if not include.isdisjoint(exclude): raise ValueError( f"include and exclude overlap on {(include & exclude)}" ) # include all subtypes include_subtypes = set() for dtype in self.dtypes: for i_dtype in include: # category handling if is_categorical_dtype(i_dtype): include_subtypes.add(i_dtype) elif issubclass(dtype.type, i_dtype): include_subtypes.add(dtype.type) # exclude all subtypes exclude_subtypes = set() for dtype in self.dtypes: for e_dtype in exclude: # category handling if is_categorical_dtype(e_dtype): exclude_subtypes.add(e_dtype) elif issubclass(dtype.type, e_dtype): exclude_subtypes.add(dtype.type) include_all = set( [cudf_dtype_from_pydata_dtype(d) for d in self.dtypes] ) if include: inclusion = include_all & include_subtypes elif exclude: inclusion = include_all else: inclusion = set() # remove all exclude types inclusion = inclusion - exclude_subtypes for k, col in self._data.items(): infered_type = cudf_dtype_from_pydata_dtype(col.dtype) if infered_type in inclusion: df.insert(len(df._data), k, col) return df @ioutils.doc_to_parquet() def to_parquet(self, path, *args, **kwargs): """{docstring}""" from cudf.io import parquet as pq return pq.to_parquet(self, path, *args, **kwargs) @ioutils.doc_to_feather() def to_feather(self, path, *args, **kwargs): """{docstring}""" from cudf.io import feather as feather feather.to_feather(self, path, *args, **kwargs) @ioutils.doc_to_json() def to_json(self, path_or_buf=None, *args, **kwargs): """{docstring}""" from cudf.io import json as json return json.to_json(self, path_or_buf=path_or_buf, *args, **kwargs) @ioutils.doc_to_hdf() def to_hdf(self, path_or_buf, key, *args, **kwargs): """{docstring}""" from cudf.io import hdf as hdf hdf.to_hdf(path_or_buf, key, self, *args, **kwargs) @ioutils.doc_to_dlpack() def to_dlpack(self): """{docstring}""" from cudf.io import dlpack as dlpack return dlpack.to_dlpack(self) @ioutils.doc_dataframe_to_csv() def to_csv( self, path_or_buf=None, sep=",", na_rep="", columns=None, header=True, index=True, line_terminator="\n", chunksize=None, ): """{docstring}""" from cudf.io import csv as csv return csv.to_csv( self, path_or_buf=path_or_buf, sep=sep, na_rep=na_rep, columns=columns, header=header, index=index, line_terminator=line_terminator, chunksize=chunksize, ) @ioutils.doc_to_orc() def to_orc(self, fname, compression=None, *args, **kwargs): """{docstring}""" from cudf.io import orc as orc orc.to_orc(self, fname, compression, *args, **kwargs) def stack(self, level=-1, dropna=True): """Stack the prescribed level(s) from columns to index Return a reshaped Series Parameters ---------- dropna : bool, default True Whether to drop rows in the resulting Series with missing values. Returns ------- The stacked cudf.Series Examples -------- >>> import cudf >>> df = cudf.DataFrame({'a':[0,1,3], 'b':[1,2,4]}) >>> df.stack() 0 a 0 b 1 1 a 1 b 2 2 a 3 b 4 dtype: int64 """ assert level in (None, -1) repeated_index = self.index.repeat(self.shape[1]) name_index = Frame({0: self._column_names}).tile(self.shape[0]) new_index = list(repeated_index._columns) + [name_index._columns[0]] new_index = cudf.core.multiindex.MultiIndex.from_frame( DataFrame(dict(zip(range(0, len(new_index)), new_index))) ) # Collect datatypes and cast columns as that type common_type = np.result_type(*self.dtypes) homogenized = DataFrame( { c: ( self._data[c].astype(common_type) if not np.issubdtype(self._data[c].dtype, common_type) else self._data[c] ) for c in self._data } ) data_col = libcudf.reshape.interleave_columns(homogenized) result = Series(data=data_col, index=new_index) if dropna: return result.dropna() else: return result def cov(self, **kwargs): """Compute the covariance matrix of a DataFrame. Parameters ---------- **kwargs Keyword arguments to be passed to cupy.cov Returns ------- cov : DataFrame """ cov = cupy.cov(self.values, rowvar=False) df = DataFrame(cupy.asfortranarray(cov)).set_index(self.columns) df.columns = self.columns return df def corr(self): """Compute the correlation matrix of a DataFrame. """ corr = cupy.corrcoef(self.values, rowvar=False) df = DataFrame(cupy.asfortranarray(corr)).set_index(self.columns) df.columns = self.columns return df def to_dict(self, orient="dict", into=dict): raise TypeError( "cuDF does not support conversion to host memory " "via `to_dict()` method. Consider using " "`.to_pandas().to_dict()` to construct a Python dictionary." ) def keys(self): """ Get the columns. This is index for Series, columns for DataFrame. Returns ------- Index Columns of DataFrame. Examples -------- >>> import cudf >>> df = cudf.DataFrame({'one' : [1, 2, 3], 'five' : ['a', 'b', 'c']}) >>> df one five 0 1 a 1 2 b 2 3 c >>> df.keys() Index(['one', 'five'], dtype='object') >>> df = cudf.DataFrame(columns=[0, 1, 2, 3]) >>> df Empty DataFrame Columns: [0, 1, 2, 3] Index: [] >>> df.keys() Int64Index([0, 1, 2, 3], dtype='int64') """ return self.columns def itertuples(self, index=True, name="Pandas"): raise TypeError( "cuDF does not support iteration of DataFrame " "via itertuples. Consider using " "`.to_pandas().itertuples()` " "if you wish to iterate over namedtuples." ) def iterrows(self): raise TypeError( "cuDF does not support iteration of DataFrame " "via iterrows. Consider using " "`.to_pandas().iterrows()` " "if you wish to iterate over each row." ) def append( self, other, ignore_index=False, verify_integrity=False, sort=False ): """ Append rows of `other` to the end of caller, returning a new object. Columns in `other` that are not in the caller are added as new columns. Parameters ---------- other : DataFrame or Series/dict-like object, or list of these The data to append. ignore_index : bool, default False If True, do not use the index labels. sort : bool, default False Sort columns ordering if the columns of `self` and `other` are not aligned. verify_integrity : bool, default False This Parameter is currently not supported. Returns ------- DataFrame See Also -------- cudf.core.reshape.concat : General function to concatenate DataFrame or objects. Notes ----- If a list of dict/series is passed and the keys are all contained in the DataFrame's index, the order of the columns in the resulting DataFrame will be unchanged. Iteratively appending rows to a cudf DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once. `verify_integrity` parameter is not supported yet. Examples -------- >>> import cudf >>> df = cudf.DataFrame([[1, 2], [3, 4]], columns=list('AB')) >>> df A B 0 1 2 1 3 4 >>> df2 = cudf.DataFrame([[5, 6], [7, 8]], columns=list('AB')) >>> df2 A B 0 5 6 1 7 8 >>> df.append(df2) A B 0 1 2 1 3 4 0 5 6 1 7 8 With `ignore_index` set to True: >>> df.append(df2, ignore_index=True) A B 0 1 2 1 3 4 2 5 6 3 7 8 The following, while not recommended methods for generating DataFrames, show two ways to generate a DataFrame from multiple data sources. Less efficient: >>> df = cudf.DataFrame(columns=['A']) >>> for i in range(5): ... df = df.append({'A': i}, ignore_index=True) >>> df A 0 0 1 1 2 2 3 3 4 4 More efficient than above: >>> cudf.concat([cudf.DataFrame([i], columns=['A']) for i in range(5)], ... ignore_index=True) A 0 0 1 1 2 2 3 3 4 4 """ if verify_integrity not in (None, False): raise NotImplementedError( "verify_integrity parameter is not supported yet." ) if isinstance(other, dict): if not ignore_index: raise TypeError("Can only append a dict if ignore_index=True") other = DataFrame(other) result = cudf.concat( [self, other], ignore_index=ignore_index, sort=sort ) return result elif isinstance(other, Series): if other.name is None and not ignore_index: raise TypeError( "Can only append a Series if ignore_index=True " "or if the Series has a name" ) current_cols = self.columns combined_columns = other.index.to_pandas() if len(current_cols): if cudf.utils.dtypes.is_mixed_with_object_dtype( current_cols, combined_columns ): raise TypeError( "cudf does not support mixed types, please type-cast " "the column index of dataframe and index of series " "to same dtypes." ) combined_columns = current_cols.union( combined_columns, sort=False ) if sort: combined_columns = combined_columns.sort_values() other = other.reindex(combined_columns, copy=False).to_frame().T if not current_cols.equals(combined_columns): self = self.reindex(columns=combined_columns) elif isinstance(other, list): if not other: pass elif not isinstance(other[0], cudf.DataFrame): other = cudf.DataFrame(other) if (self.columns.get_indexer(other.columns) >= 0).all(): other = other.reindex(columns=self.columns) if is_list_like(other): to_concat = [self, *other] else: to_concat = [self, other] return cudf.concat(to_concat, ignore_index=ignore_index, sort=sort) @copy_docstring(reshape.pivot) def pivot(self, index, columns, values=None): return cudf.core.reshape.pivot( self, index=index, columns=columns, values=values ) @copy_docstring(reshape.unstack) def unstack(self, level=-1, fill_value=None): return cudf.core.reshape.unstack( self, level=level, fill_value=fill_value ) def equals(self, other): if not isinstance(other, DataFrame): return False for self_name, other_name in zip(self._data.names, other._data.names): if self_name != other_name: return False return super().equals(other) _accessors = set() def from_pandas(obj, nan_as_null=None): """ Convert certain Pandas objects into the cudf equivalent. Supports DataFrame, Series, Index, or MultiIndex. Returns ------- DataFrame/Series/Index/MultiIndex Return type depends on the passed input. Raises ------ TypeError for invalid input type. Examples -------- >>> import cudf >>> import pandas as pd >>> data = [[0, 1], [1, 2], [3, 4]] >>> pdf = pd.DataFrame(data, columns=['a', 'b'], dtype=int) >>> pdf a b 0 0 1 1 1 2 2 3 4 >>> gdf = cudf.from_pandas(pdf) >>> gdf a b 0 0 1 1 1 2 2 3 4 >>> type(gdf) <class 'cudf.core.dataframe.DataFrame'> >>> type(pdf) <class 'pandas.core.frame.DataFrame'> Converting a Pandas Series to cuDF Series: >>> psr = pd.Series(['a', 'b', 'c', 'd'], name='apple') >>> psr 0 a 1 b 2 c 3 d Name: apple, dtype: object >>> gsr = cudf.from_pandas(psr) >>> gsr 0 a 1 b 2 c 3 d Name: apple, dtype: object >>> type(gsr) <class 'cudf.core.series.Series'> >>> type(psr) <class 'pandas.core.series.Series'> Converting a Pandas Index to cuDF Index: >>> pidx = pd.Index([1, 2, 10, 20]) >>> pidx Int64Index([1, 2, 10, 20], dtype='int64') >>> gidx = cudf.from_pandas(pidx) >>> gidx Int64Index([1, 2, 10, 20], dtype='int64') >>> type(gidx) <class 'cudf.core.index.Int64Index'> >>> type(pidx) <class 'pandas.core.indexes.numeric.Int64Index'> Converting a Pandas MultiIndex to cuDF MultiIndex: >>> pmidx = pd.MultiIndex( ... levels=[[1, 3, 4, 5], [1, 2, 5]], ... codes=[[0, 0, 1, 2, 3], [0, 2, 1, 1, 0]], ... names=["x", "y"], ... ) >>> pmidx MultiIndex([(1, 1), (1, 5), (3, 2), (4, 2), (5, 1)], names=['x', 'y']) >>> gmidx = cudf.from_pandas(pmidx) >>> gmidx MultiIndex([(1, 1), (1, 5), (3, 2), (4, 2), (5, 1)], names=['x', 'y']) >>> type(gmidx) <class 'cudf.core.multiindex.MultiIndex'> >>> type(pmidx) <class 'pandas.core.indexes.multi.MultiIndex'> """ if isinstance(obj, pd.DataFrame): return DataFrame.from_pandas(obj, nan_as_null=nan_as_null) elif isinstance(obj, pd.Series): return Series.from_pandas(obj, nan_as_null=nan_as_null) elif isinstance(obj, pd.MultiIndex): return cudf.MultiIndex.from_pandas(obj, nan_as_null=nan_as_null) elif isinstance(obj, pd.RangeIndex): return cudf.core.index.RangeIndex( start=obj.start, stop=obj.stop, step=obj.step, name=obj.name ) elif isinstance(obj, pd.Index): return cudf.Index.from_pandas(obj, nan_as_null=nan_as_null) elif isinstance(obj, pd.CategoricalDtype): return cudf.CategoricalDtype.from_pandas(obj) else: raise TypeError( "from_pandas only accepts Pandas Dataframes, Series, " "Index, RangeIndex and MultiIndex objects. " "Got %s" % type(obj) ) def merge(left, right, *args, **kwargs): return left.merge(right, *args, **kwargs) # a bit of fanciness to inject docstring with left parameter merge_doc = DataFrame.merge.__doc__ idx = merge_doc.find("right") merge.__doc__ = "".join( [merge_doc[:idx], "\n\tleft : DataFrame\n\t", merge_doc[idx:]] ) def _align_indices(lhs, rhs): """ Internal util to align the indices of two DataFrames. Returns a tuple of the aligned dataframes, or the original arguments if the indices are the same, or if rhs isn't a DataFrame. """ lhs_out, rhs_out = lhs, rhs if isinstance(rhs, DataFrame) and not lhs.index.equals(rhs.index): df = lhs.merge( rhs, sort=True, how="outer", left_index=True, right_index=True, suffixes=("_x", "_y"), ) df = df.sort_index() lhs_out = DataFrame(index=df.index) rhs_out = DataFrame(index=df.index) common = set(lhs.columns) & set(rhs.columns) common_x = set(["{}_x".format(x) for x in common]) common_y = set(["{}_y".format(x) for x in common]) for col in df.columns: if col in common_x: lhs_out[col[:-2]] = df[col] elif col in common_y: rhs_out[col[:-2]] = df[col] elif col in lhs: lhs_out[col] = df[col] elif col in rhs: rhs_out[col] = df[col] return lhs_out, rhs_out def _setitem_with_dataframe(input_df, replace_df, input_cols=None, mask=None): """ This function sets item dataframes relevant columns with replacement df :param input_df: Dataframe to be modified inplace :param replace_df: Replacement DataFrame to replace values with :param input_cols: columns to replace in the input dataframe :param mask: boolean mask in case of masked replacing """ if input_cols is None: input_cols = input_df.columns if len(input_cols) != len(replace_df.columns): raise ValueError( "Number of Input Columns must be same replacement Dataframe" ) for col_1, col_2 in zip(input_cols, replace_df.columns): if col_1 in input_df.columns: if mask is not None: input_df._data[col_1][mask] = column.as_column( replace_df[col_2] ) else: input_df._data[col_1] = column.as_column(replace_df[col_2]) else: if mask is not None: raise ValueError("Can not insert new column with a bool mask") else: # handle append case input_df.insert(len(input_df._data), col_1, replace_df[col_2]) def extract_col(df, col): """ Extract column from dataframe `df` with their name `col`. If `col` is index and there are no columns with name `index`, then this will return index column. """ try: return df._data[col] except KeyError: if ( col == "index" and col not in df.index._data and not isinstance(df.index, cudf.MultiIndex) ): return df.index._data.columns[0] return df.index._data[col] def _get_union_of_indices(indexes): if len(indexes) == 1: return indexes[0] else: merged_index = cudf.core.Index._concat(indexes) merged_index = merged_index.drop_duplicates() _, inds = merged_index._values.sort_by_values() return merged_index.take(inds) def _get_union_of_series_names(series_list): names_list = [] unnamed_count = 0 for series in series_list: if series.name is None: names_list.append(f"Unnamed {unnamed_count}") unnamed_count += 1 else: names_list.append(series.name) if unnamed_count == len(series_list): names_list = [*range(len(series_list))] return names_list def _drop_columns(df, columns, errors): for c in columns: try: df._drop_column(c) except KeyError as e: if errors == "ignore": pass else: raise e def _get_host_unique(array): if isinstance( array, (cudf.Series, cudf.Index, cudf.core.column.ColumnBase) ): return array.unique.to_pandas() elif isinstance(array, (str, numbers.Number)): return [array] else: return set(array)
import asyncio import json import os import string from statistics import mean from typing import Any from packaging import version as pyver import pytz from alerts.models import SEVERITY_CHOICES from core.models import CoreSettings from django.conf import settings from django.contrib.postgres.fields import ArrayField from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from logs.models import BaseAuditModel from loguru import logger from .utils import bytes2human logger.configure(**settings.LOG_CONFIG) CHECK_TYPE_CHOICES = [ ("diskspace", "Disk Space Check"), ("ping", "Ping Check"), ("cpuload", "CPU Load Check"), ("memory", "Memory Check"), ("winsvc", "Service Check"), ("script", "Script Check"), ("eventlog", "Event Log Check"), ] CHECK_STATUS_CHOICES = [ ("passing", "Passing"), ("failing", "Failing"), ("pending", "Pending"), ] EVT_LOG_NAME_CHOICES = [ ("Application", "Application"), ("System", "System"), ("Security", "Security"), ] EVT_LOG_TYPE_CHOICES = [ ("INFO", "Information"), ("WARNING", "Warning"), ("ERROR", "Error"), ("AUDIT_SUCCESS", "Success Audit"), ("AUDIT_FAILURE", "Failure Audit"), ] EVT_LOG_FAIL_WHEN_CHOICES = [ ("contains", "Log contains"), ("not_contains", "Log does not contain"), ] class Check(BaseAuditModel): # common fields agent = models.ForeignKey( "agents.Agent", related_name="agentchecks", null=True, blank=True, on_delete=models.CASCADE, ) policy = models.ForeignKey( "automation.Policy", related_name="policychecks", null=True, blank=True, on_delete=models.CASCADE, ) managed_by_policy = models.BooleanField(default=False) overriden_by_policy = models.BooleanField(default=False) parent_check = models.PositiveIntegerField(null=True, blank=True) name = models.CharField(max_length=255, null=True, blank=True) check_type = models.CharField( max_length=50, choices=CHECK_TYPE_CHOICES, default="diskspace" ) status = models.CharField( max_length=100, choices=CHECK_STATUS_CHOICES, default="pending" ) more_info = models.TextField(null=True, blank=True) last_run = models.DateTimeField(null=True, blank=True) email_alert = models.BooleanField(default=False) text_alert = models.BooleanField(default=False) dashboard_alert = models.BooleanField(default=False) fails_b4_alert = models.PositiveIntegerField(default=1) fail_count = models.PositiveIntegerField(default=0) outage_history = models.JSONField(null=True, blank=True) # store extra_details = models.JSONField(null=True, blank=True) run_interval = models.PositiveIntegerField(blank=True, default=0) # check specific fields # for eventlog, script, ip, and service alert severity alert_severity = models.CharField( max_length=15, choices=SEVERITY_CHOICES, default="warning", null=True, blank=True, ) # threshold percent for diskspace, cpuload or memory check error_threshold = models.PositiveIntegerField( validators=[MinValueValidator(0), MaxValueValidator(99)], null=True, blank=True, default=0, ) warning_threshold = models.PositiveIntegerField( null=True, blank=True, validators=[MinValueValidator(0), MaxValueValidator(99)], default=0, ) # diskcheck i.e C:, D: etc disk = models.CharField(max_length=2, null=True, blank=True) # ping checks ip = models.CharField(max_length=255, null=True, blank=True) # script checks script = models.ForeignKey( "scripts.Script", related_name="script", on_delete=models.CASCADE, null=True, blank=True, ) script_args = ArrayField( models.CharField(max_length=255, null=True, blank=True), null=True, blank=True, default=list, ) info_return_codes = ArrayField( models.PositiveIntegerField(), null=True, blank=True, default=list, ) warning_return_codes = ArrayField( models.PositiveIntegerField(), null=True, blank=True, default=list, ) timeout = models.PositiveIntegerField(null=True, blank=True) stdout = models.TextField(null=True, blank=True) stderr = models.TextField(null=True, blank=True) retcode = models.IntegerField(null=True, blank=True) execution_time = models.CharField(max_length=100, null=True, blank=True) # cpu and mem check history history = ArrayField( models.IntegerField(blank=True), null=True, blank=True, default=list ) # win service checks svc_name = models.CharField(max_length=255, null=True, blank=True) svc_display_name = models.CharField(max_length=255, null=True, blank=True) pass_if_start_pending = models.BooleanField(null=True, blank=True) pass_if_svc_not_exist = models.BooleanField(default=False) restart_if_stopped = models.BooleanField(null=True, blank=True) svc_policy_mode = models.CharField( max_length=20, null=True, blank=True ) # 'default' or 'manual', for editing policy check # event log checks log_name = models.CharField( max_length=255, choices=EVT_LOG_NAME_CHOICES, null=True, blank=True ) event_id = models.IntegerField(null=True, blank=True) event_id_is_wildcard = models.BooleanField(default=False) event_type = models.CharField( max_length=255, choices=EVT_LOG_TYPE_CHOICES, null=True, blank=True ) event_source = models.CharField(max_length=255, null=True, blank=True) event_message = models.TextField(null=True, blank=True) fail_when = models.CharField( max_length=255, choices=EVT_LOG_FAIL_WHEN_CHOICES, null=True, blank=True ) search_last_days = models.PositiveIntegerField(null=True, blank=True) number_of_events_b4_alert = models.PositiveIntegerField( null=True, blank=True, default=1 ) def __str__(self): if self.agent: return f"{self.agent.hostname} - {self.readable_desc}" else: return f"{self.policy.name} - {self.readable_desc}" @property def readable_desc(self): if self.check_type == "diskspace": text = "" if self.warning_threshold: text += f" Warning Threshold: {self.warning_threshold}%" if self.error_threshold: text += f" Error Threshold: {self.error_threshold}%" return f"{self.get_check_type_display()}: Drive {self.disk} - {text}" # type: ignore elif self.check_type == "ping": return f"{self.get_check_type_display()}: {self.name}" # type: ignore elif self.check_type == "cpuload" or self.check_type == "memory": text = "" if self.warning_threshold: text += f" Warning Threshold: {self.warning_threshold}%" if self.error_threshold: text += f" Error Threshold: {self.error_threshold}%" return f"{self.get_check_type_display()} - {text}" # type: ignore elif self.check_type == "winsvc": return f"{self.get_check_type_display()}: {self.svc_display_name}" # type: ignore elif self.check_type == "eventlog": return f"{self.get_check_type_display()}: {self.name}" # type: ignore elif self.check_type == "script": return f"{self.get_check_type_display()}: {self.script.name}" # type: ignore else: return "n/a" @property def history_info(self): if self.check_type == "cpuload" or self.check_type == "memory": return ", ".join(str(f"{x}%") for x in self.history[-6:]) @property def last_run_as_timezone(self): if self.last_run is not None and self.agent is not None: return self.last_run.astimezone( pytz.timezone(self.agent.timezone) ).strftime("%b-%d-%Y - %H:%M") return self.last_run @property def non_editable_fields(self) -> list[str]: return [ "check_type", "status", "more_info", "last_run", "fail_count", "outage_history", "extra_details", "stdout", "stderr", "retcode", "execution_time", "history", "readable_desc", "history_info", "parent_check", "managed_by_policy", "overriden_by_policy", "created_by", "created_time", "modified_by", "modified_time", ] @property def policy_fields_to_copy(self) -> list[str]: return [ "warning_threshold", "error_threshold", "alert_severity", "name", "run_interval", "disk", "fails_b4_alert", "ip", "script", "script_args", "info_return_codes", "warning_return_codes", "timeout", "svc_name", "svc_display_name", "svc_policy_mode", "pass_if_start_pending", "pass_if_svc_not_exist", "restart_if_stopped", "log_name", "event_id", "event_id_is_wildcard", "event_type", "event_source", "event_message", "fail_when", "search_last_days", "number_of_events_b4_alert", "email_alert", "text_alert", "dashboard_alert", ] def should_create_alert(self, alert_template=None): return ( self.dashboard_alert or self.email_alert or self.text_alert or ( alert_template and ( alert_template.check_always_alert or alert_template.check_always_email or alert_template.check_always_text ) ) ) def add_check_history(self, value: int, more_info: Any = None) -> None: CheckHistory.objects.create(check_history=self, y=value, results=more_info) def handle_checkv2(self, data): from alerts.models import Alert # cpuload or mem checks if self.check_type == "cpuload" or self.check_type == "memory": self.history.append(data["percent"]) if len(self.history) > 15: self.history = self.history[-15:] self.save(update_fields=["history"]) avg = int(mean(self.history)) if self.error_threshold and avg > self.error_threshold: self.status = "failing" self.alert_severity = "error" elif self.warning_threshold and avg > self.warning_threshold: self.status = "failing" self.alert_severity = "warning" else: self.status = "passing" # add check history self.add_check_history(data["percent"]) # diskspace checks elif self.check_type == "diskspace": if data["exists"]: percent_used = round(data["percent_used"]) total = bytes2human(data["total"]) free = bytes2human(data["free"]) if self.error_threshold and (100 - percent_used) < self.error_threshold: self.status = "failing" self.alert_severity = "error" elif ( self.warning_threshold and (100 - percent_used) < self.warning_threshold ): self.status = "failing" self.alert_severity = "warning" else: self.status = "passing" self.more_info = f"Total: {total}B, Free: {free}B" # add check history self.add_check_history(100 - percent_used) else: self.status = "failing" self.alert_severity = "error" self.more_info = f"Disk {self.disk} does not exist" self.save(update_fields=["more_info"]) # script checks elif self.check_type == "script": self.stdout = data["stdout"] self.stderr = data["stderr"] self.retcode = data["retcode"] try: # python agent self.execution_time = "{:.4f}".format(data["stop"] - data["start"]) except: # golang agent self.execution_time = "{:.4f}".format(data["runtime"]) if data["retcode"] in self.info_return_codes: self.alert_severity = "info" self.status = "failing" elif data["retcode"] in self.warning_return_codes: self.alert_severity = "warning" self.status = "failing" elif data["retcode"] != 0: self.status = "failing" self.alert_severity = "error" else: self.status = "passing" self.save( update_fields=[ "stdout", "stderr", "retcode", "execution_time", ] ) # add check history self.add_check_history( 1 if self.status == "failing" else 0, { "retcode": data["retcode"], "stdout": data["stdout"][:60], "stderr": data["stderr"][:60], "execution_time": self.execution_time, }, ) # ping checks elif self.check_type == "ping": output = data["output"] if pyver.parse(self.agent.version) <= pyver.parse("1.5.2"): # DEPRECATED success = ["Reply", "bytes", "time", "TTL"] if data["has_stdout"]: if all(x in output for x in success): self.status = "passing" else: self.status = "failing" elif data["has_stderr"]: self.status = "failing" else: self.status = data["status"] self.more_info = output self.save(update_fields=["more_info"]) self.add_check_history( 1 if self.status == "failing" else 0, self.more_info[:60] ) # windows service checks elif self.check_type == "winsvc": svc_stat = data["status"] self.more_info = f"Status {svc_stat.upper()}" if data["exists"]: if svc_stat == "running": self.status = "passing" elif svc_stat == "start_pending" and self.pass_if_start_pending: self.status = "passing" else: if self.agent and self.restart_if_stopped: nats_data = { "func": "winsvcaction", "payload": {"name": self.svc_name, "action": "start"}, } r = asyncio.run(self.agent.nats_cmd(nats_data, timeout=32)) if r == "timeout" or r == "natsdown": self.status = "failing" elif not r["success"] and r["errormsg"]: self.status = "failing" elif r["success"]: self.status = "passing" self.more_info = f"Status RUNNING" else: self.status = "failing" else: self.status = "failing" else: if self.pass_if_svc_not_exist: self.status = "passing" else: self.status = "failing" self.more_info = f"Service {self.svc_name} does not exist" self.save(update_fields=["more_info"]) self.add_check_history( 1 if self.status == "failing" else 0, self.more_info[:60] ) elif self.check_type == "eventlog": log = [] is_wildcard = self.event_id_is_wildcard eventType = self.event_type eventID = self.event_id source = self.event_source message = self.event_message r = data["log"] for i in r: if i["eventType"] == eventType: if not is_wildcard and not int(i["eventID"]) == eventID: continue if not source and not message: if is_wildcard: log.append(i) elif int(i["eventID"]) == eventID: log.append(i) continue if source and message: if is_wildcard: if source in i["source"] and message in i["message"]: log.append(i) elif int(i["eventID"]) == eventID: if source in i["source"] and message in i["message"]: log.append(i) continue if source and source in i["source"]: if is_wildcard: log.append(i) elif int(i["eventID"]) == eventID: log.append(i) if message and message in i["message"]: if is_wildcard: log.append(i) elif int(i["eventID"]) == eventID: log.append(i) if self.fail_when == "contains": if log and len(log) >= self.number_of_events_b4_alert: self.status = "failing" else: self.status = "passing" elif self.fail_when == "not_contains": if log and len(log) >= self.number_of_events_b4_alert: self.status = "passing" else: self.status = "failing" self.extra_details = {"log": log} self.save(update_fields=["extra_details"]) self.add_check_history( 1 if self.status == "failing" else 0, "Events Found:" + str(len(self.extra_details["log"])), ) # handle status if self.status == "failing": self.fail_count += 1 self.save(update_fields=["status", "fail_count", "alert_severity"]) if self.fail_count >= self.fails_b4_alert: Alert.handle_alert_failure(self) elif self.status == "passing": self.fail_count = 0 self.save(update_fields=["status", "fail_count", "alert_severity"]) if Alert.objects.filter(assigned_check=self, resolved=False).exists(): Alert.handle_alert_resolve(self) return self.status @staticmethod def serialize(check): # serializes the check and returns json from .serializers import CheckSerializer return CheckSerializer(check).data # for policy diskchecks @staticmethod def all_disks(): return [f"{i}:" for i in string.ascii_uppercase] # for policy service checks @staticmethod def load_default_services(): with open( os.path.join(settings.BASE_DIR, "services/default_services.json") ) as f: default_services = json.load(f) return default_services def create_policy_check(self, agent=None, policy=None): if (not agent and not policy) or (agent and policy): return check = Check.objects.create( agent=agent, policy=policy, managed_by_policy=bool(agent), parent_check=(self.pk if agent else None), check_type=self.check_type, script=self.script, ) for field in self.policy_fields_to_copy: setattr(check, field, getattr(self, field)) check.save() def is_duplicate(self, check): if self.check_type == "diskspace": return self.disk == check.disk elif self.check_type == "script": return self.script == check.script elif self.check_type == "ping": return self.ip == check.ip elif self.check_type == "cpuload": return True elif self.check_type == "memory": return True elif self.check_type == "winsvc": return self.svc_name == check.svc_name elif self.check_type == "eventlog": return [self.log_name, self.event_id] == [check.log_name, check.event_id] def send_email(self): CORE = CoreSettings.objects.first() body: str = "" if self.agent: subject = f"{self.agent.client.name}, {self.agent.site.name}, {self.agent.hostname} - {self} Failed" else: subject = f"{self} Failed" if self.check_type == "diskspace": text = "" if self.warning_threshold: text += f" Warning Threshold: {self.warning_threshold}%" if self.error_threshold: text += f" Error Threshold: {self.error_threshold}%" try: percent_used = [ d["percent"] for d in self.agent.disks if d["device"] == self.disk ][0] percent_free = 100 - percent_used body = subject + f" - Free: {percent_free}%, {text}" except: body = subject + f" - Disk {self.disk} does not exist" elif self.check_type == "script": body = ( subject + f" - Return code: {self.retcode}\nStdout:{self.stdout}\nStderr: {self.stderr}" ) elif self.check_type == "ping": body = self.more_info elif self.check_type == "cpuload" or self.check_type == "memory": text = "" if self.warning_threshold: text += f" Warning Threshold: {self.warning_threshold}%" if self.error_threshold: text += f" Error Threshold: {self.error_threshold}%" avg = int(mean(self.history)) if self.check_type == "cpuload": body = subject + f" - Average CPU utilization: {avg}%, {text}" elif self.check_type == "memory": body = subject + f" - Average memory usage: {avg}%, {text}" elif self.check_type == "winsvc": body = subject + f" - Status: {self.more_info}" elif self.check_type == "eventlog": if self.event_source and self.event_message: start = f"Event ID {self.event_id}, source {self.event_source}, containing string {self.event_message} " elif self.event_source: start = f"Event ID {self.event_id}, source {self.event_source} " elif self.event_message: start = ( f"Event ID {self.event_id}, containing string {self.event_message} " ) else: start = f"Event ID {self.event_id} " body = start + f"was found in the {self.log_name} log\n\n" for i in self.extra_details["log"]: try: if i["message"]: body += f"{i["message"]}\n" except: continue CORE.send_mail(subject, body, alert_template=self.agent.alert_template) def send_sms(self): CORE = CoreSettings.objects.first() body: str = "" if self.agent: subject = f"{self.agent.client.name}, {self.agent.site.name}, {self} Failed" else: subject = f"{self} Failed" if self.check_type == "diskspace": text = "" if self.warning_threshold: text += f" Warning Threshold: {self.warning_threshold}%" if self.error_threshold: text += f" Error Threshold: {self.error_threshold}%" try: percent_used = [ d["percent"] for d in self.agent.disks if d["device"] == self.disk ][0] percent_free = 100 - percent_used body = subject + f" - Free: {percent_free}%, {text}" except: body = subject + f" - Disk {self.disk} does not exist" elif self.check_type == "script": body = subject + f" - Return code: {self.retcode}" elif self.check_type == "ping": body = subject elif self.check_type == "cpuload" or self.check_type == "memory": text = "" if self.warning_threshold: text += f" Warning Threshold: {self.warning_threshold}%" if self.error_threshold: text += f" Error Threshold: {self.error_threshold}%" avg = int(mean(self.history)) if self.check_type == "cpuload": body = subject + f" - Average CPU utilization: {avg}%, {text}" elif self.check_type == "memory": body = subject + f" - Average memory usage: {avg}%, {text}" elif self.check_type == "winsvc": body = subject + f" - Status: {self.more_info}" elif self.check_type == "eventlog": body = subject CORE.send_sms(body, alert_template=self.agent.alert_template) def send_resolved_email(self): CORE = CoreSettings.objects.first() subject = f"{self.agent.client.name}, {self.agent.site.name}, {self} Resolved" body = f"{self} is now back to normal" CORE.send_mail(subject, body, alert_template=self.agent.alert_template) def send_resolved_sms(self): CORE = CoreSettings.objects.first() subject = f"{self.agent.client.name}, {self.agent.site.name}, {self} Resolved" CORE.send_sms(subject, alert_template=self.agent.alert_template) class CheckHistory(models.Model): check_history = models.ForeignKey( Check, related_name="check_history", on_delete=models.CASCADE, ) x = models.DateTimeField(auto_now_add=True) y = models.PositiveIntegerField(null=True, blank=True, default=None) results = models.JSONField(null=True, blank=True) def __str__(self): return self.check_history.readable_desc
import asyncio import json import os import string from statistics import mean from typing import Any from packaging import version as pyver import pytz from alerts.models import SEVERITY_CHOICES from core.models import CoreSettings from django.conf import settings from django.contrib.postgres.fields import ArrayField from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from logs.models import BaseAuditModel from loguru import logger from .utils import bytes2human logger.configure(**settings.LOG_CONFIG) CHECK_TYPE_CHOICES = [ ("diskspace", "Disk Space Check"), ("ping", "Ping Check"), ("cpuload", "CPU Load Check"), ("memory", "Memory Check"), ("winsvc", "Service Check"), ("script", "Script Check"), ("eventlog", "Event Log Check"), ] CHECK_STATUS_CHOICES = [ ("passing", "Passing"), ("failing", "Failing"), ("pending", "Pending"), ] EVT_LOG_NAME_CHOICES = [ ("Application", "Application"), ("System", "System"), ("Security", "Security"), ] EVT_LOG_TYPE_CHOICES = [ ("INFO", "Information"), ("WARNING", "Warning"), ("ERROR", "Error"), ("AUDIT_SUCCESS", "Success Audit"), ("AUDIT_FAILURE", "Failure Audit"), ] EVT_LOG_FAIL_WHEN_CHOICES = [ ("contains", "Log contains"), ("not_contains", "Log does not contain"), ] class Check(BaseAuditModel): # common fields agent = models.ForeignKey( "agents.Agent", related_name="agentchecks", null=True, blank=True, on_delete=models.CASCADE, ) policy = models.ForeignKey( "automation.Policy", related_name="policychecks", null=True, blank=True, on_delete=models.CASCADE, ) managed_by_policy = models.BooleanField(default=False) overriden_by_policy = models.BooleanField(default=False) parent_check = models.PositiveIntegerField(null=True, blank=True) name = models.CharField(max_length=255, null=True, blank=True) check_type = models.CharField( max_length=50, choices=CHECK_TYPE_CHOICES, default="diskspace" ) status = models.CharField( max_length=100, choices=CHECK_STATUS_CHOICES, default="pending" ) more_info = models.TextField(null=True, blank=True) last_run = models.DateTimeField(null=True, blank=True) email_alert = models.BooleanField(default=False) text_alert = models.BooleanField(default=False) dashboard_alert = models.BooleanField(default=False) fails_b4_alert = models.PositiveIntegerField(default=1) fail_count = models.PositiveIntegerField(default=0) outage_history = models.JSONField(null=True, blank=True) # store extra_details = models.JSONField(null=True, blank=True) run_interval = models.PositiveIntegerField(blank=True, default=0) # check specific fields # for eventlog, script, ip, and service alert severity alert_severity = models.CharField( max_length=15, choices=SEVERITY_CHOICES, default="warning", null=True, blank=True, ) # threshold percent for diskspace, cpuload or memory check error_threshold = models.PositiveIntegerField( validators=[MinValueValidator(0), MaxValueValidator(99)], null=True, blank=True, default=0, ) warning_threshold = models.PositiveIntegerField( null=True, blank=True, validators=[MinValueValidator(0), MaxValueValidator(99)], default=0, ) # diskcheck i.e C:, D: etc disk = models.CharField(max_length=2, null=True, blank=True) # ping checks ip = models.CharField(max_length=255, null=True, blank=True) # script checks script = models.ForeignKey( "scripts.Script", related_name="script", on_delete=models.CASCADE, null=True, blank=True, ) script_args = ArrayField( models.CharField(max_length=255, null=True, blank=True), null=True, blank=True, default=list, ) info_return_codes = ArrayField( models.PositiveIntegerField(), null=True, blank=True, default=list, ) warning_return_codes = ArrayField( models.PositiveIntegerField(), null=True, blank=True, default=list, ) timeout = models.PositiveIntegerField(null=True, blank=True) stdout = models.TextField(null=True, blank=True) stderr = models.TextField(null=True, blank=True) retcode = models.IntegerField(null=True, blank=True) execution_time = models.CharField(max_length=100, null=True, blank=True) # cpu and mem check history history = ArrayField( models.IntegerField(blank=True), null=True, blank=True, default=list ) # win service checks svc_name = models.CharField(max_length=255, null=True, blank=True) svc_display_name = models.CharField(max_length=255, null=True, blank=True) pass_if_start_pending = models.BooleanField(null=True, blank=True) pass_if_svc_not_exist = models.BooleanField(default=False) restart_if_stopped = models.BooleanField(null=True, blank=True) svc_policy_mode = models.CharField( max_length=20, null=True, blank=True ) # 'default' or 'manual', for editing policy check # event log checks log_name = models.CharField( max_length=255, choices=EVT_LOG_NAME_CHOICES, null=True, blank=True ) event_id = models.IntegerField(null=True, blank=True) event_id_is_wildcard = models.BooleanField(default=False) event_type = models.CharField( max_length=255, choices=EVT_LOG_TYPE_CHOICES, null=True, blank=True ) event_source = models.CharField(max_length=255, null=True, blank=True) event_message = models.TextField(null=True, blank=True) fail_when = models.CharField( max_length=255, choices=EVT_LOG_FAIL_WHEN_CHOICES, null=True, blank=True ) search_last_days = models.PositiveIntegerField(null=True, blank=True) number_of_events_b4_alert = models.PositiveIntegerField( null=True, blank=True, default=1 ) def __str__(self): if self.agent: return f"{self.agent.hostname} - {self.readable_desc}" else: return f"{self.policy.name} - {self.readable_desc}" @property def readable_desc(self): if self.check_type == "diskspace": text = "" if self.warning_threshold: text += f" Warning Threshold: {self.warning_threshold}%" if self.error_threshold: text += f" Error Threshold: {self.error_threshold}%" return f"{self.get_check_type_display()}: Drive {self.disk} - {text}" # type: ignore elif self.check_type == "ping": return f"{self.get_check_type_display()}: {self.name}" # type: ignore elif self.check_type == "cpuload" or self.check_type == "memory": text = "" if self.warning_threshold: text += f" Warning Threshold: {self.warning_threshold}%" if self.error_threshold: text += f" Error Threshold: {self.error_threshold}%" return f"{self.get_check_type_display()} - {text}" # type: ignore elif self.check_type == "winsvc": return f"{self.get_check_type_display()}: {self.svc_display_name}" # type: ignore elif self.check_type == "eventlog": return f"{self.get_check_type_display()}: {self.name}" # type: ignore elif self.check_type == "script": return f"{self.get_check_type_display()}: {self.script.name}" # type: ignore else: return "n/a" @property def history_info(self): if self.check_type == "cpuload" or self.check_type == "memory": return ", ".join(str(f"{x}%") for x in self.history[-6:]) @property def last_run_as_timezone(self): if self.last_run is not None and self.agent is not None: return self.last_run.astimezone( pytz.timezone(self.agent.timezone) ).strftime("%b-%d-%Y - %H:%M") return self.last_run @property def non_editable_fields(self) -> list[str]: return [ "check_type", "status", "more_info", "last_run", "fail_count", "outage_history", "extra_details", "stdout", "stderr", "retcode", "execution_time", "history", "readable_desc", "history_info", "parent_check", "managed_by_policy", "overriden_by_policy", "created_by", "created_time", "modified_by", "modified_time", ] @property def policy_fields_to_copy(self) -> list[str]: return [ "warning_threshold", "error_threshold", "alert_severity", "name", "run_interval", "disk", "fails_b4_alert", "ip", "script", "script_args", "info_return_codes", "warning_return_codes", "timeout", "svc_name", "svc_display_name", "svc_policy_mode", "pass_if_start_pending", "pass_if_svc_not_exist", "restart_if_stopped", "log_name", "event_id", "event_id_is_wildcard", "event_type", "event_source", "event_message", "fail_when", "search_last_days", "number_of_events_b4_alert", "email_alert", "text_alert", "dashboard_alert", ] def should_create_alert(self, alert_template=None): return ( self.dashboard_alert or self.email_alert or self.text_alert or ( alert_template and ( alert_template.check_always_alert or alert_template.check_always_email or alert_template.check_always_text ) ) ) def add_check_history(self, value: int, more_info: Any = None) -> None: CheckHistory.objects.create(check_history=self, y=value, results=more_info) def handle_checkv2(self, data): from alerts.models import Alert # cpuload or mem checks if self.check_type == "cpuload" or self.check_type == "memory": self.history.append(data["percent"]) if len(self.history) > 15: self.history = self.history[-15:] self.save(update_fields=["history"]) avg = int(mean(self.history)) if self.error_threshold and avg > self.error_threshold: self.status = "failing" self.alert_severity = "error" elif self.warning_threshold and avg > self.warning_threshold: self.status = "failing" self.alert_severity = "warning" else: self.status = "passing" # add check history self.add_check_history(data["percent"]) # diskspace checks elif self.check_type == "diskspace": if data["exists"]: percent_used = round(data["percent_used"]) total = bytes2human(data["total"]) free = bytes2human(data["free"]) if self.error_threshold and (100 - percent_used) < self.error_threshold: self.status = "failing" self.alert_severity = "error" elif ( self.warning_threshold and (100 - percent_used) < self.warning_threshold ): self.status = "failing" self.alert_severity = "warning" else: self.status = "passing" self.more_info = f"Total: {total}B, Free: {free}B" # add check history self.add_check_history(100 - percent_used) else: self.status = "failing" self.alert_severity = "error" self.more_info = f"Disk {self.disk} does not exist" self.save(update_fields=["more_info"]) # script checks elif self.check_type == "script": self.stdout = data["stdout"] self.stderr = data["stderr"] self.retcode = data["retcode"] try: # python agent self.execution_time = "{:.4f}".format(data["stop"] - data["start"]) except: # golang agent self.execution_time = "{:.4f}".format(data["runtime"]) if data["retcode"] in self.info_return_codes: self.alert_severity = "info" self.status = "failing" elif data["retcode"] in self.warning_return_codes: self.alert_severity = "warning" self.status = "failing" elif data["retcode"] != 0: self.status = "failing" self.alert_severity = "error" else: self.status = "passing" self.save( update_fields=[ "stdout", "stderr", "retcode", "execution_time", ] ) # add check history self.add_check_history( 1 if self.status == "failing" else 0, { "retcode": data["retcode"], "stdout": data["stdout"][:60], "stderr": data["stderr"][:60], "execution_time": self.execution_time, }, ) # ping checks elif self.check_type == "ping": output = data["output"] if pyver.parse(self.agent.version) <= pyver.parse("1.5.2"): # DEPRECATED success = ["Reply", "bytes", "time", "TTL"] if data["has_stdout"]: if all(x in output for x in success): self.status = "passing" else: self.status = "failing" elif data["has_stderr"]: self.status = "failing" else: self.status = data["status"] self.more_info = output self.save(update_fields=["more_info"]) self.add_check_history( 1 if self.status == "failing" else 0, self.more_info[:60] ) # windows service checks elif self.check_type == "winsvc": svc_stat = data["status"] self.more_info = f"Status {svc_stat.upper()}" if data["exists"]: if svc_stat == "running": self.status = "passing" elif svc_stat == "start_pending" and self.pass_if_start_pending: self.status = "passing" else: if self.agent and self.restart_if_stopped: nats_data = { "func": "winsvcaction", "payload": {"name": self.svc_name, "action": "start"}, } r = asyncio.run(self.agent.nats_cmd(nats_data, timeout=32)) if r == "timeout" or r == "natsdown": self.status = "failing" elif not r["success"] and r["errormsg"]: self.status = "failing" elif r["success"]: self.status = "passing" self.more_info = f"Status RUNNING" else: self.status = "failing" else: self.status = "failing" else: if self.pass_if_svc_not_exist: self.status = "passing" else: self.status = "failing" self.more_info = f"Service {self.svc_name} does not exist" self.save(update_fields=["more_info"]) self.add_check_history( 1 if self.status == "failing" else 0, self.more_info[:60] ) elif self.check_type == "eventlog": log = [] is_wildcard = self.event_id_is_wildcard eventType = self.event_type eventID = self.event_id source = self.event_source message = self.event_message r = data["log"] for i in r: if i["eventType"] == eventType: if not is_wildcard and not int(i["eventID"]) == eventID: continue if not source and not message: if is_wildcard: log.append(i) elif int(i["eventID"]) == eventID: log.append(i) continue if source and message: if is_wildcard: if source in i["source"] and message in i["message"]: log.append(i) elif int(i["eventID"]) == eventID: if source in i["source"] and message in i["message"]: log.append(i) continue if source and source in i["source"]: if is_wildcard: log.append(i) elif int(i["eventID"]) == eventID: log.append(i) if message and message in i["message"]: if is_wildcard: log.append(i) elif int(i["eventID"]) == eventID: log.append(i) if self.fail_when == "contains": if log and len(log) >= self.number_of_events_b4_alert: self.status = "failing" else: self.status = "passing" elif self.fail_when == "not_contains": if log and len(log) >= self.number_of_events_b4_alert: self.status = "passing" else: self.status = "failing" self.extra_details = {"log": log} self.save(update_fields=["extra_details"]) self.add_check_history( 1 if self.status == "failing" else 0, "Events Found:" + str(len(self.extra_details["log"])), ) # handle status if self.status == "failing": self.fail_count += 1 self.save(update_fields=["status", "fail_count", "alert_severity"]) if self.fail_count >= self.fails_b4_alert: Alert.handle_alert_failure(self) elif self.status == "passing": self.fail_count = 0 self.save(update_fields=["status", "fail_count", "alert_severity"]) if Alert.objects.filter(assigned_check=self, resolved=False).exists(): Alert.handle_alert_resolve(self) return self.status @staticmethod def serialize(check): # serializes the check and returns json from .serializers import CheckSerializer return CheckSerializer(check).data # for policy diskchecks @staticmethod def all_disks(): return [f"{i}:" for i in string.ascii_uppercase] # for policy service checks @staticmethod def load_default_services(): with open( os.path.join(settings.BASE_DIR, "services/default_services.json") ) as f: default_services = json.load(f) return default_services def create_policy_check(self, agent=None, policy=None): if (not agent and not policy) or (agent and policy): return check = Check.objects.create( agent=agent, policy=policy, managed_by_policy=bool(agent), parent_check=(self.pk if agent else None), check_type=self.check_type, script=self.script, ) for field in self.policy_fields_to_copy: setattr(check, field, getattr(self, field)) check.save() def is_duplicate(self, check): if self.check_type == "diskspace": return self.disk == check.disk elif self.check_type == "script": return self.script == check.script elif self.check_type == "ping": return self.ip == check.ip elif self.check_type == "cpuload": return True elif self.check_type == "memory": return True elif self.check_type == "winsvc": return self.svc_name == check.svc_name elif self.check_type == "eventlog": return [self.log_name, self.event_id] == [check.log_name, check.event_id] def send_email(self): CORE = CoreSettings.objects.first() body: str = "" if self.agent: subject = f"{self.agent.client.name}, {self.agent.site.name}, {self.agent.hostname} - {self} Failed" else: subject = f"{self} Failed" if self.check_type == "diskspace": text = "" if self.warning_threshold: text += f" Warning Threshold: {self.warning_threshold}%" if self.error_threshold: text += f" Error Threshold: {self.error_threshold}%" try: percent_used = [ d["percent"] for d in self.agent.disks if d["device"] == self.disk ][0] percent_free = 100 - percent_used body = subject + f" - Free: {percent_free}%, {text}" except: body = subject + f" - Disk {self.disk} does not exist" elif self.check_type == "script": body = ( subject + f" - Return code: {self.retcode}\nStdout:{self.stdout}\nStderr: {self.stderr}" ) elif self.check_type == "ping": body = self.more_info elif self.check_type == "cpuload" or self.check_type == "memory": text = "" if self.warning_threshold: text += f" Warning Threshold: {self.warning_threshold}%" if self.error_threshold: text += f" Error Threshold: {self.error_threshold}%" avg = int(mean(self.history)) if self.check_type == "cpuload": body = subject + f" - Average CPU utilization: {avg}%, {text}" elif self.check_type == "memory": body = subject + f" - Average memory usage: {avg}%, {text}" elif self.check_type == "winsvc": body = subject + f" - Status: {self.more_info}" elif self.check_type == "eventlog": if self.event_source and self.event_message: start = f"Event ID {self.event_id}, source {self.event_source}, containing string {self.event_message} " elif self.event_source: start = f"Event ID {self.event_id}, source {self.event_source} " elif self.event_message: start = ( f"Event ID {self.event_id}, containing string {self.event_message} " ) else: start = f"Event ID {self.event_id} " body = start + f"was found in the {self.log_name} log\n\n" for i in self.extra_details["log"]: try: if i["message"]: body += f"{i['message']}\n" except: continue CORE.send_mail(subject, body, alert_template=self.agent.alert_template) def send_sms(self): CORE = CoreSettings.objects.first() body: str = "" if self.agent: subject = f"{self.agent.client.name}, {self.agent.site.name}, {self} Failed" else: subject = f"{self} Failed" if self.check_type == "diskspace": text = "" if self.warning_threshold: text += f" Warning Threshold: {self.warning_threshold}%" if self.error_threshold: text += f" Error Threshold: {self.error_threshold}%" try: percent_used = [ d["percent"] for d in self.agent.disks if d["device"] == self.disk ][0] percent_free = 100 - percent_used body = subject + f" - Free: {percent_free}%, {text}" except: body = subject + f" - Disk {self.disk} does not exist" elif self.check_type == "script": body = subject + f" - Return code: {self.retcode}" elif self.check_type == "ping": body = subject elif self.check_type == "cpuload" or self.check_type == "memory": text = "" if self.warning_threshold: text += f" Warning Threshold: {self.warning_threshold}%" if self.error_threshold: text += f" Error Threshold: {self.error_threshold}%" avg = int(mean(self.history)) if self.check_type == "cpuload": body = subject + f" - Average CPU utilization: {avg}%, {text}" elif self.check_type == "memory": body = subject + f" - Average memory usage: {avg}%, {text}" elif self.check_type == "winsvc": body = subject + f" - Status: {self.more_info}" elif self.check_type == "eventlog": body = subject CORE.send_sms(body, alert_template=self.agent.alert_template) def send_resolved_email(self): CORE = CoreSettings.objects.first() subject = f"{self.agent.client.name}, {self.agent.site.name}, {self} Resolved" body = f"{self} is now back to normal" CORE.send_mail(subject, body, alert_template=self.agent.alert_template) def send_resolved_sms(self): CORE = CoreSettings.objects.first() subject = f"{self.agent.client.name}, {self.agent.site.name}, {self} Resolved" CORE.send_sms(subject, alert_template=self.agent.alert_template) class CheckHistory(models.Model): check_history = models.ForeignKey( Check, related_name="check_history", on_delete=models.CASCADE, ) x = models.DateTimeField(auto_now_add=True) y = models.PositiveIntegerField(null=True, blank=True, default=None) results = models.JSONField(null=True, blank=True) def __str__(self): return self.check_history.readable_desc
"""'Git type Path Source.""" import logging import shutil import subprocess import tempfile from pathlib import Path from typing import Any, Dict, Optional from .source import Source LOGGER = logging.getLogger(__name__) class Git(Source): """Git Path Source. The Git path source can be tasked with cloning a remote repository and pointing to a specific module folder (or the root). """ def __init__( self, *, arguments: Optional[Dict[str, str]] = None, location: str = "", uri: str = "", **kwargs: Any, ) -> None: """Git Path Source. Args: arguments: A reference can be passed along via the arguments so that a specific version of the repository is cloned. **commit**, **tag**, **branch** are all valid keys with respective output location: The relative location to the root of the repository where the module resides. Leaving this as an empty string, ``/``, or ``./`` will have runway look in the root folder. uri: The uniform resource identifier that targets the remote git repository """ self.args = arguments or {} self.uri = uri self.location = location super().__init__(**kwargs) def fetch(self) -> Path: """Retrieve the git repository from it's remote location.""" from git.repo import Repo # pylint: disable=import-outside-toplevel ref = self.__determine_git_ref() dir_name = "_".join([self.sanitize_git_path(self.uri), ref]) cached_dir_path = self.cache_dir / dir_name if cached_dir_path.exists(): return cached_dir_path with tempfile.TemporaryDirectory() as tmpdirname: tmp_repo_path = Path(tmpdirname) / dir_name with Repo.clone_from(self.uri, str(tmp_repo_path)) as repo: repo.head.set_reference(ref) repo.head.reset(index=True, working_tree=True) shutil.move(str(tmp_repo_path), self.cache_dir) return cached_dir_path def __git_ls_remote(self, ref: str) -> str: """List remote repositories based on uri and ref received. Keyword Args: ref (str): The git reference value """ cmd = ["git", "ls-remote", self.uri, ref] LOGGER.debug("getting commit ID from repo: %s", " ".join(cmd)) ls_remote_output = subprocess.check_output(cmd) if b"\t" in ls_remote_output: commit_id = ls_remote_output.split(b"\t", maxsplit=1)[0].decode() LOGGER.debug("matching commit id found: %s", commit_id) return commit_id raise ValueError(f'Ref "{ref}" not found for repo {self.uri}.') def __determine_git_ls_remote_ref(self) -> str: """Determine remote ref, defaulting to HEAD unless a branch is found.""" ref = "HEAD" if self.args.get("branch"): ref = f"refs/heads/{self.args["branch"]}" return ref def __determine_git_ref(self) -> str: """Determine the git reference code.""" ref_config_keys = sum( bool(self.args.get(i)) for i in ["commit", "tag", "branch"] ) if ref_config_keys > 1: raise ValueError( "Fetching remote git sources failed: conflicting revisions " "(e.g. 'commit', 'tag', 'branch') specified for a package source" ) if self.args.get("commit"): return self.args["commit"] if self.args.get("tag"): return self.args["tag"] return self.__git_ls_remote(self.__determine_git_ls_remote_ref()) @classmethod def sanitize_git_path(cls, path: str) -> str: """Sanitize the git path for folder/file assignment. Keyword Args: path: The path string to be sanitized """ dir_name = path split = path.split("//") domain = split[len(split) - 1] if domain.endswith(".git"): dir_name = domain[:-4] return cls.sanitize_directory_path(dir_name)
"""'Git type Path Source.""" import logging import shutil import subprocess import tempfile from pathlib import Path from typing import Any, Dict, Optional from .source import Source LOGGER = logging.getLogger(__name__) class Git(Source): """Git Path Source. The Git path source can be tasked with cloning a remote repository and pointing to a specific module folder (or the root). """ def __init__( self, *, arguments: Optional[Dict[str, str]] = None, location: str = "", uri: str = "", **kwargs: Any, ) -> None: """Git Path Source. Args: arguments: A reference can be passed along via the arguments so that a specific version of the repository is cloned. **commit**, **tag**, **branch** are all valid keys with respective output location: The relative location to the root of the repository where the module resides. Leaving this as an empty string, ``/``, or ``./`` will have runway look in the root folder. uri: The uniform resource identifier that targets the remote git repository """ self.args = arguments or {} self.uri = uri self.location = location super().__init__(**kwargs) def fetch(self) -> Path: """Retrieve the git repository from it's remote location.""" from git.repo import Repo # pylint: disable=import-outside-toplevel ref = self.__determine_git_ref() dir_name = "_".join([self.sanitize_git_path(self.uri), ref]) cached_dir_path = self.cache_dir / dir_name if cached_dir_path.exists(): return cached_dir_path with tempfile.TemporaryDirectory() as tmpdirname: tmp_repo_path = Path(tmpdirname) / dir_name with Repo.clone_from(self.uri, str(tmp_repo_path)) as repo: repo.head.set_reference(ref) repo.head.reset(index=True, working_tree=True) shutil.move(str(tmp_repo_path), self.cache_dir) return cached_dir_path def __git_ls_remote(self, ref: str) -> str: """List remote repositories based on uri and ref received. Keyword Args: ref (str): The git reference value """ cmd = ["git", "ls-remote", self.uri, ref] LOGGER.debug("getting commit ID from repo: %s", " ".join(cmd)) ls_remote_output = subprocess.check_output(cmd) if b"\t" in ls_remote_output: commit_id = ls_remote_output.split(b"\t", maxsplit=1)[0].decode() LOGGER.debug("matching commit id found: %s", commit_id) return commit_id raise ValueError(f'Ref "{ref}" not found for repo {self.uri}.') def __determine_git_ls_remote_ref(self) -> str: """Determine remote ref, defaulting to HEAD unless a branch is found.""" ref = "HEAD" if self.args.get("branch"): ref = f"refs/heads/{self.args['branch']}" return ref def __determine_git_ref(self) -> str: """Determine the git reference code.""" ref_config_keys = sum( bool(self.args.get(i)) for i in ["commit", "tag", "branch"] ) if ref_config_keys > 1: raise ValueError( "Fetching remote git sources failed: conflicting revisions " "(e.g. 'commit', 'tag', 'branch') specified for a package source" ) if self.args.get("commit"): return self.args["commit"] if self.args.get("tag"): return self.args["tag"] return self.__git_ls_remote(self.__determine_git_ls_remote_ref()) @classmethod def sanitize_git_path(cls, path: str) -> str: """Sanitize the git path for folder/file assignment. Keyword Args: path: The path string to be sanitized """ dir_name = path split = path.split("//") domain = split[len(split) - 1] if domain.endswith(".git"): dir_name = domain[:-4] return cls.sanitize_directory_path(dir_name)
from django.utils import timezone from calendar import HTMLCalendar import logging logger = logging.getLogger(__name__) class Calendar(HTMLCalendar): def __init__(self, year=None, month=None, dark=False): self.year = year self.month = month self.events = None self.dark = dark super(Calendar, self).__init__() self.setfirstweekday(6) # formats a day as a td # filter events by day def formatday(self, day): events_per_day = self.events.filter(class_date__day=day) data = '' for event in events_per_day: logging.debug(event.class_type) btn_color = 'btn-primary' if event.class_type == 'combined': btn_color = 'btn-info' elif event.class_type == 'returnee': btn_color = 'btn-secondary' cd = timezone.localtime(event.class_date) data += f'<li><button class="btn {btn_color} bc-btn m-1" type="button" bc_id="{event.id}">' data += f'{event.class_type.capitalize()} {cd.strftime('%I:%M %p')}</button></li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {data} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek): week = '' for d, weekday in theweek: week += self.formatday(d) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): if self.dark: bg = 'table-dark' else: bg = '' cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar table table-bordered {bg}">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week)}\n' return cal def set_event(self, queryset): self.events = queryset
from django.utils import timezone from calendar import HTMLCalendar import logging logger = logging.getLogger(__name__) class Calendar(HTMLCalendar): def __init__(self, year=None, month=None, dark=False): self.year = year self.month = month self.events = None self.dark = dark super(Calendar, self).__init__() self.setfirstweekday(6) # formats a day as a td # filter events by day def formatday(self, day): events_per_day = self.events.filter(class_date__day=day) data = '' for event in events_per_day: logging.debug(event.class_type) btn_color = 'btn-primary' if event.class_type == 'combined': btn_color = 'btn-info' elif event.class_type == 'returnee': btn_color = 'btn-secondary' cd = timezone.localtime(event.class_date) data += f'<li><button class="btn {btn_color} bc-btn m-1" type="button" bc_id="{event.id}">' data += f'{event.class_type.capitalize()} {cd.strftime("%I:%M %p")}</button></li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {data} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek): week = '' for d, weekday in theweek: week += self.formatday(d) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): if self.dark: bg = 'table-dark' else: bg = '' cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar table table-bordered {bg}">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week)}\n' return cal def set_event(self, queryset): self.events = queryset
# SPDX-License-Identifier: BSD-3-Clause """ Utility to create a SoftFab results file from PyLint's JSON output. For SoftFab, 'error' means the test results are incomplete, while 'warning' means the results are complete but the content has problems. So if PyLint ran successfully but finds errors in the code it examined, that means it did its job correctly and the SoftFab result will be 'warning'. """ from collections import Counter import json def results_from_exit_code(exit_code): """ Return a results dictionary based on PyLint's exit code. https://pylint.readthedocs.io/en/latest/user_guide/run.html#exit-codes """ # Incomplete results. if exit_code & 32: return dict(result="error", summary="PyLint did not complete run") if exit_code & 1: return dict(result="error", summary="PyLint encountered fatal error") if exit_code & ~63: return dict(result="error", summary=f"Unknown PyLint exit code: {exit_code:d}") # Content problems, from more to less urgent. # I'm putting convention messages before refactor messages because # the former can typically be fixed quicker. if exit_code & 2: return dict(result="warning", summary="PyLint found errors") if exit_code & 4: return dict(result="warning", summary="PyLint found warnings") if exit_code & 16: return dict(result="warning", summary="PyLint found broken conventions") if exit_code & 8: return dict(result="warning", summary="PyLint found refactor candidates") return dict(result="ok", summary="PyLint found no issues") def results_from_json(json_path): """Return a results dictionary based on a PyLint JSON output file.""" # Read and parse JSON file. try: with open(str(json_path), encoding="utf-8") as inp: data = json.load(inp) except OSError as ex: return dict(result="error", summary=f"Error reading JSON: {ex}") except ValueError as ex: return dict(result="error", summary=f"Error parsing JSON: {ex}") # Count number of issues of each type. counts = Counter() try: if isinstance(data, list): # PyLint's native JSON format. messages = data elif isinstance(data, dict): # Extended JSON format from pylint_json2html. messages = data["messages"] else: raise TypeError(f"Bad top-level type: {type(data).__name__}") for message in messages: counts[message["type"]] += 1 except Exception as ex: # pylint: disable=broad-except return dict(result="error", summary=f"Error processing JSON: {ex}") # In case of a fatal problem, the results may be incomplete, so stop # here to avoid reporting incorrect information. if counts["fatal"]: return dict(result="error", summary="PyLint encountered fatal error") # Prepare summary and gather mid-level data. results = {} issues = [] for msg_type in ("error", "warning", "convention", "refactor"): count = counts[msg_type] results[f"data.{msg_type}"] = str(count) if count: issues.append(f"{count} {msg_type}{"" if count == 1 else "s"}") # Gather more mid-level data when using extended JSON format. if isinstance(data, dict): try: stats = data["stats"] for key in ( "module", "class", "method", "function", "statement", "undocumented_module", "undocumented_class", "undocumented_method", "undocumented_function", ): results[f"data.{key}"] = str(stats[key]) except Exception as ex: # pylint: disable=broad-except return dict(result="error", summary=f"Error processing extended JSON: {ex}") # Summarize the findings. if issues: results["result"] = "warning" results["summary"] = f"PyLint found {", ".join(issues)}" else: results["result"] = "ok" results["summary"] = "PyLint found no issues" return results def gather_results(json_path, exit_code=0): """ Return a results dictionary based on PyLint's exit code and a PyLint JSON output file. """ results = results_from_exit_code(exit_code) if results["result"] != "error": results = results_from_json(json_path) return results
# SPDX-License-Identifier: BSD-3-Clause """ Utility to create a SoftFab results file from PyLint's JSON output. For SoftFab, 'error' means the test results are incomplete, while 'warning' means the results are complete but the content has problems. So if PyLint ran successfully but finds errors in the code it examined, that means it did its job correctly and the SoftFab result will be 'warning'. """ from collections import Counter import json def results_from_exit_code(exit_code): """ Return a results dictionary based on PyLint's exit code. https://pylint.readthedocs.io/en/latest/user_guide/run.html#exit-codes """ # Incomplete results. if exit_code & 32: return dict(result="error", summary="PyLint did not complete run") if exit_code & 1: return dict(result="error", summary="PyLint encountered fatal error") if exit_code & ~63: return dict(result="error", summary=f"Unknown PyLint exit code: {exit_code:d}") # Content problems, from more to less urgent. # I'm putting convention messages before refactor messages because # the former can typically be fixed quicker. if exit_code & 2: return dict(result="warning", summary="PyLint found errors") if exit_code & 4: return dict(result="warning", summary="PyLint found warnings") if exit_code & 16: return dict(result="warning", summary="PyLint found broken conventions") if exit_code & 8: return dict(result="warning", summary="PyLint found refactor candidates") return dict(result="ok", summary="PyLint found no issues") def results_from_json(json_path): """Return a results dictionary based on a PyLint JSON output file.""" # Read and parse JSON file. try: with open(str(json_path), encoding="utf-8") as inp: data = json.load(inp) except OSError as ex: return dict(result="error", summary=f"Error reading JSON: {ex}") except ValueError as ex: return dict(result="error", summary=f"Error parsing JSON: {ex}") # Count number of issues of each type. counts = Counter() try: if isinstance(data, list): # PyLint's native JSON format. messages = data elif isinstance(data, dict): # Extended JSON format from pylint_json2html. messages = data["messages"] else: raise TypeError(f"Bad top-level type: {type(data).__name__}") for message in messages: counts[message["type"]] += 1 except Exception as ex: # pylint: disable=broad-except return dict(result="error", summary=f"Error processing JSON: {ex}") # In case of a fatal problem, the results may be incomplete, so stop # here to avoid reporting incorrect information. if counts["fatal"]: return dict(result="error", summary="PyLint encountered fatal error") # Prepare summary and gather mid-level data. results = {} issues = [] for msg_type in ("error", "warning", "convention", "refactor"): count = counts[msg_type] results[f"data.{msg_type}"] = str(count) if count: issues.append(f"{count} {msg_type}{'' if count == 1 else 's'}") # Gather more mid-level data when using extended JSON format. if isinstance(data, dict): try: stats = data["stats"] for key in ( "module", "class", "method", "function", "statement", "undocumented_module", "undocumented_class", "undocumented_method", "undocumented_function", ): results[f"data.{key}"] = str(stats[key]) except Exception as ex: # pylint: disable=broad-except return dict(result="error", summary=f"Error processing extended JSON: {ex}") # Summarize the findings. if issues: results["result"] = "warning" results["summary"] = f"PyLint found {', '.join(issues)}" else: results["result"] = "ok" results["summary"] = "PyLint found no issues" return results def gather_results(json_path, exit_code=0): """ Return a results dictionary based on PyLint's exit code and a PyLint JSON output file. """ results = results_from_exit_code(exit_code) if results["result"] != "error": results = results_from_json(json_path) return results
""" This is a sample on how to define custom components. You can make a repo out of this file, having one custom component per file """ import os import shutil import pytest import pp from pp.add_padding import add_padding_to_grid from pp.add_termination import add_gratings_and_loop_back from pp.autoplacer.yaml_placer import place_from_yaml from pp.components.spiral_inner_io import spiral_inner_io_euler from pp.config import CONFIG from pp.generate_does import generate_does from pp.mask.merge_metadata import merge_metadata from pp.routing.connect import connect_strip_way_points def _route_filter(*args, **kwargs): return connect_strip_way_points( *args, taper_factory=None, start_straight=5.0, end_straight=5.0, **kwargs ) def add_te(component, **kwargs): c = pp.routing.add_fiber_array( component, grating_coupler=pp.c.grating_coupler_elliptical_te, route_filter=_route_filter, **kwargs, ) c.test = "passive_optical_te" c = add_padding_to_grid(c) return c def add_tm(component, **kwargs): c = pp.routing.add_fiber_array( component, grating_coupler=pp.c.grating_coupler_elliptical_tm, route_filter=_route_filter, bend_radius=20, **kwargs, ) c = add_padding_to_grid(c) return c @pp.cell def coupler_te(gap, length, wg_width=0.5, nominal_wg_width=0.5): """ sample of component cutback """ c = pp.c.coupler(wg_width=wg_width, gap=gap, length=length) cc = add_te(c) return cc @pp.cell def spiral_te(wg_width=0.5, length=2): """ sample of component cutback Args: wg_width: um lenght: mm """ c = spiral_inner_io_euler(wg_width=wg_width, length=length) cc = add_gratings_and_loop_back( component=c, grating_coupler=pp.c.grating_coupler_elliptical_te, bend_factory=pp.c.bend_circular, ) return cc @pp.cell def spiral_tm(wg_width=0.5, length=2): """ sample of component cutback """ c = spiral_inner_io_euler(wg_width=wg_width, length=length, dx=10, dy=10, N=5) cc = add_gratings_and_loop_back( component=c, grating_coupler=pp.c.grating_coupler_elliptical_tm, bend_factory=pp.c.bend_circular, ) return cc component_factory = dict( spiral_te=spiral_te, spiral_tm=spiral_tm, coupler_te=coupler_te ) @pytest.fixture def cleandir(): build_folder = CONFIG["samples_path"] / "mask_custom" / "build" if build_folder.exists(): shutil.rmtree(build_folder) @pytest.fixture def chdir(): workspace_folder = CONFIG["samples_path"] / "mask_custom" os.chdir(workspace_folder) @pytest.mark.usefixtures("cleandir") def test_mask(precision=2e-9): workspace_folder = CONFIG["samples_path"] / "mask_custom" build_path = workspace_folder / "build" doe_root_path = build_path / "cache_doe" doe_metadata_path = build_path / "doe" mask_path = build_path / "mask" does_yml = workspace_folder / "does.yml" mask_path.mkdir(parents=True, exist_ok=True) gdspath = mask_path / "sample_mask.gds" markdown_path = gdspath.with_suffix(".md") json_path = gdspath.with_suffix(".json") test_metadata_path = gdspath.with_suffix(".tp.json") generate_does( str(does_yml), component_factory=component_factory, precision=precision, doe_root_path=doe_root_path, doe_metadata_path=doe_metadata_path, ) top_level = place_from_yaml(does_yml, precision=precision, root_does=doe_root_path) top_level.write(str(gdspath)) merge_metadata(gdspath=gdspath) assert gdspath.exists() assert markdown_path.exists() assert json_path.exists() assert test_metadata_path.exists() report = open(markdown_path).read() assert report.count("#") == 2, f" only {report.count("#")} DOEs in {markdown_path}" return gdspath if __name__ == "__main__": # from pprint import pprint # pprint(component_factory) c = test_mask() pp.klive.show(c) # c = coupler_te(gap=0.3, length=20) # pp.show(c)
""" This is a sample on how to define custom components. You can make a repo out of this file, having one custom component per file """ import os import shutil import pytest import pp from pp.add_padding import add_padding_to_grid from pp.add_termination import add_gratings_and_loop_back from pp.autoplacer.yaml_placer import place_from_yaml from pp.components.spiral_inner_io import spiral_inner_io_euler from pp.config import CONFIG from pp.generate_does import generate_does from pp.mask.merge_metadata import merge_metadata from pp.routing.connect import connect_strip_way_points def _route_filter(*args, **kwargs): return connect_strip_way_points( *args, taper_factory=None, start_straight=5.0, end_straight=5.0, **kwargs ) def add_te(component, **kwargs): c = pp.routing.add_fiber_array( component, grating_coupler=pp.c.grating_coupler_elliptical_te, route_filter=_route_filter, **kwargs, ) c.test = "passive_optical_te" c = add_padding_to_grid(c) return c def add_tm(component, **kwargs): c = pp.routing.add_fiber_array( component, grating_coupler=pp.c.grating_coupler_elliptical_tm, route_filter=_route_filter, bend_radius=20, **kwargs, ) c = add_padding_to_grid(c) return c @pp.cell def coupler_te(gap, length, wg_width=0.5, nominal_wg_width=0.5): """ sample of component cutback """ c = pp.c.coupler(wg_width=wg_width, gap=gap, length=length) cc = add_te(c) return cc @pp.cell def spiral_te(wg_width=0.5, length=2): """ sample of component cutback Args: wg_width: um lenght: mm """ c = spiral_inner_io_euler(wg_width=wg_width, length=length) cc = add_gratings_and_loop_back( component=c, grating_coupler=pp.c.grating_coupler_elliptical_te, bend_factory=pp.c.bend_circular, ) return cc @pp.cell def spiral_tm(wg_width=0.5, length=2): """ sample of component cutback """ c = spiral_inner_io_euler(wg_width=wg_width, length=length, dx=10, dy=10, N=5) cc = add_gratings_and_loop_back( component=c, grating_coupler=pp.c.grating_coupler_elliptical_tm, bend_factory=pp.c.bend_circular, ) return cc component_factory = dict( spiral_te=spiral_te, spiral_tm=spiral_tm, coupler_te=coupler_te ) @pytest.fixture def cleandir(): build_folder = CONFIG["samples_path"] / "mask_custom" / "build" if build_folder.exists(): shutil.rmtree(build_folder) @pytest.fixture def chdir(): workspace_folder = CONFIG["samples_path"] / "mask_custom" os.chdir(workspace_folder) @pytest.mark.usefixtures("cleandir") def test_mask(precision=2e-9): workspace_folder = CONFIG["samples_path"] / "mask_custom" build_path = workspace_folder / "build" doe_root_path = build_path / "cache_doe" doe_metadata_path = build_path / "doe" mask_path = build_path / "mask" does_yml = workspace_folder / "does.yml" mask_path.mkdir(parents=True, exist_ok=True) gdspath = mask_path / "sample_mask.gds" markdown_path = gdspath.with_suffix(".md") json_path = gdspath.with_suffix(".json") test_metadata_path = gdspath.with_suffix(".tp.json") generate_does( str(does_yml), component_factory=component_factory, precision=precision, doe_root_path=doe_root_path, doe_metadata_path=doe_metadata_path, ) top_level = place_from_yaml(does_yml, precision=precision, root_does=doe_root_path) top_level.write(str(gdspath)) merge_metadata(gdspath=gdspath) assert gdspath.exists() assert markdown_path.exists() assert json_path.exists() assert test_metadata_path.exists() report = open(markdown_path).read() assert report.count("#") == 2, f" only {report.count('#')} DOEs in {markdown_path}" return gdspath if __name__ == "__main__": # from pprint import pprint # pprint(component_factory) c = test_mask() pp.klive.show(c) # c = coupler_te(gap=0.3, length=20) # pp.show(c)
import csv import io import json import logging import uuid from abc import ABCMeta, abstractmethod from collections import defaultdict, namedtuple from contextlib import closing from itertools import chain from typing import Set import psycopg2 from botocore.exceptions import ClientError from csp.decorators import csp_update from django.conf import settings from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from django.core import serializers from django.core.exceptions import PermissionDenied from django.core.paginator import Paginator from django.core.serializers.json import DjangoJSONEncoder from django.db import connections, ProgrammingError from django.db.models import ( Count, F, CharField, Value, Func, Q, Prefetch, ) from django.db.models.functions import TruncDay from django.forms.models import model_to_dict from django.http import ( Http404, HttpResponse, HttpResponseForbidden, HttpResponseNotFound, HttpResponseRedirect, HttpResponseServerError, JsonResponse, ) from django.shortcuts import get_object_or_404, render, redirect from django.urls import reverse from django.views.decorators.http import ( require_GET, require_http_methods, ) from django.views.generic import DetailView, FormView, TemplateView, UpdateView, View from psycopg2 import sql from waffle.mixins import WaffleFlagMixin from dataworkspace import datasets_db from dataworkspace.apps.api_v1.core.views import invalidate_superset_user_cached_credentials from dataworkspace.apps.applications.models import ApplicationInstance from dataworkspace.apps.core.boto3_client import get_s3_client from dataworkspace.apps.core.charts.models import ChartBuilderChart from dataworkspace.apps.core.charts.tasks import run_chart_builder_query from dataworkspace.apps.core.errors import DatasetPermissionDenied, DatasetPreviewDisabledError from dataworkspace.apps.core.utils import ( StreamingHttpResponseWithoutDjangoDbConnection, database_dsn, streaming_query_response, table_data, view_exists, get_random_data_sample, ) from dataworkspace.apps.core.models import ( Database, ) from dataworkspace.apps.datasets.constants import ( DataSetType, DataLinkType, ) from dataworkspace.apps.datasets.constants import TagType from dataworkspace.apps.datasets.forms import ( ChartSourceSelectForm, DatasetEditForm, DatasetSearchForm, EligibilityCriteriaForm, RelatedMastersSortForm, RelatedDataCutsSortForm, RelatedVisualisationsSortForm, UserSearchForm, VisualisationCatalogueItemEditForm, ) from dataworkspace.apps.datasets.models import ( CustomDatasetQuery, DataCutDataset, DataSet, DataSetUserPermission, PendingAuthorizedUsers, MasterDataset, ReferenceDataset, ReferenceDatasetField, SourceLink, SourceView, VisualisationCatalogueItem, SourceTable, ToolQueryAuditLogTable, Tag, VisualisationUserPermission, SourceTableFieldDefinition, ) from dataworkspace.apps.datasets.permissions.utils import ( process_dataset_authorized_users_change, process_visualisation_catalogue_item_authorized_users_change, ) from dataworkspace.apps.datasets.search import search_for_datasets from dataworkspace.apps.datasets.utils import ( build_filtered_dataset_query, dataset_type_to_manage_unpublished_permission_codename, find_dataset, get_code_snippets_for_table, get_code_snippets_for_query, get_code_snippets_for_reference_table, get_detailed_changelog, ) from dataworkspace.apps.eventlog.models import EventLog from dataworkspace.apps.eventlog.utils import log_event, log_permission_change from dataworkspace.apps.explorer.utils import invalidate_data_explorer_user_cached_credentials logger = logging.getLogger("app") def _matches_filters( data, unpublished: bool, opendata: bool, withvisuals: bool, use: Set, data_type: Set, source_ids: Set, topic_ids: Set, user_accessible: bool = False, user_inaccessible: bool = False, selected_user_datasets: Set = None, ): subscribed_or_bookmarked = set() if data["is_bookmarked"]: subscribed_or_bookmarked.add("bookmarked") if data["is_subscribed"]: subscribed_or_bookmarked.add("subscribed") return ( ( not selected_user_datasets or selected_user_datasets == [None] or set(selected_user_datasets).intersection(subscribed_or_bookmarked) ) and ( not selected_user_datasets or selected_user_datasets == [None] or set(selected_user_datasets).intersection(subscribed_or_bookmarked) ) and (unpublished or data["published"]) and (not opendata or data["is_open_data"]) and (not withvisuals or data["has_visuals"]) and (not data_type or data_type == [None] or data["data_type"] in data_type) and (not source_ids or source_ids.intersection(set(data["source_tag_ids"]))) and (not topic_ids or topic_ids.intersection(set(data["topic_tag_ids"]))) and (not user_accessible or data["has_access"]) and (not user_inaccessible or not data["has_access"]) ) def has_unpublished_dataset_access(user): access = user.is_superuser for dataset_type in DataSetType: access = access or user.has_perm( dataset_type_to_manage_unpublished_permission_codename(dataset_type.value) ) return access def _get_tags_as_dict(): """ Gets all tags and returns them as a dictionary keyed by the tag.id as a string @return: """ tags = Tag.objects.all() tags_dict = {} for tag in tags: tags_dict[str(tag.id)] = model_to_dict(tag) return tags_dict @require_GET def find_datasets(request): ############### # Validate form form = DatasetSearchForm(request.GET) if not form.is_valid(): logger.warning(form.errors) return HttpResponseRedirect(reverse("datasets:find_datasets")) data_types = form.fields[ "data_type" ].choices # Cache these now, as we annotate them with result numbers later which we don't want here. ############################################### # Find all results, and matching filter numbers filters = form.get_filters() all_visible_datasets, matched_datasets = search_for_datasets( request.user, filters, _matches_filters ) form.annotate_and_update_filters( all_visible_datasets, matcher=_matches_filters, ) #################################### # Select the current page of results paginator = Paginator( matched_datasets, settings.SEARCH_RESULTS_DATASETS_PER_PAGE, ) datasets = paginator.get_page(request.GET.get("page")) ######################################################## # Augment results with tags, avoiding queries-per-result tags_dict = _get_tags_as_dict() for dataset in datasets: dataset["sources"] = [ tags_dict.get(str(source_id)) for source_id in dataset["source_tag_ids"] ] dataset["topics"] = [tags_dict.get(str(topic_id)) for topic_id in dataset["topic_tag_ids"]] ###################################################################### # Augment results with last updated dates, avoiding queries-per-result # Data structures to quickly look up datasets as needed further down datasets_by_type = defaultdict(list) datasets_by_type_id = {} for dataset in datasets: datasets_by_type[dataset["data_type"]].append(dataset) datasets_by_type_id[(dataset["data_type"], dataset["id"])] = dataset # Reference datasets reference_datasets = ReferenceDataset.objects.filter( uuid__in=tuple(dataset["id"] for dataset in datasets_by_type[DataSetType.REFERENCE.value]) ) for reference_dataset in reference_datasets: dataset = datasets_by_type_id[(DataSetType.REFERENCE.value, reference_dataset.uuid)] try: # If the reference dataset csv table doesn't exist we # get an unhandled relation does not exist error # this is currently only a problem with integration tests dataset["last_updated"] = reference_dataset.data_last_updated except ProgrammingError as e: logger.error(e) dataset["last_updated"] = None # Master datasets and datacuts together to minimise metadata table queries master_datasets = MasterDataset.objects.filter( id__in=tuple(dataset["id"] for dataset in datasets_by_type[DataSetType.MASTER.value]) ).prefetch_related("sourcetable_set") datacut_datasets = DataCutDataset.objects.filter( id__in=tuple(dataset["id"] for dataset in datasets_by_type[DataSetType.DATACUT.value]) ).prefetch_related( Prefetch( "customdatasetquery_set", queryset=CustomDatasetQuery.objects.prefetch_related("tables"), ) ) databases = {database.id: database for database in Database.objects.all()} tables_and_last_updated_dates = datasets_db.get_all_tables_last_updated_date( [ (databases[table.database_id].memorable_name, table.schema, table.table) for master_dataset in master_datasets for table in master_dataset.sourcetable_set.all() ] + [ (databases[query.database_id].memorable_name, table.schema, table.table) for datacut_dataset in datacut_datasets for query in datacut_dataset.customdatasetquery_set.all() for table in query.tables.all() ] ) def _without_none(it): return (val for val in it if val is not None) for master_dataset in master_datasets: dataset = datasets_by_type_id[(DataSetType.MASTER.value, master_dataset.id)] dataset["last_updated"] = max( _without_none( ( tables_and_last_updated_dates[databases[table.database_id].memorable_name].get( (table.schema, table.table) ) for table in master_dataset.sourcetable_set.all() ) ), default=None, ) for datacut_dataset in datacut_datasets: dataset = datasets_by_type_id[(DataSetType.DATACUT.value, datacut_dataset.id)] last_updated_dates_for_queries = ( ( tables_and_last_updated_dates[databases[query.database_id].memorable_name].get( (table.schema, table.table) ) for table in query.tables.all() ) for query in datacut_dataset.customdatasetquery_set.all() ) dataset["last_updated"] = max( _without_none( ( min(_without_none(last_updated_dates_for_query), default=None) for last_updated_dates_for_query in last_updated_dates_for_queries ) ), default=None, ) # Visualisations visualisation_datasets = VisualisationCatalogueItem.objects.filter( id__in=tuple( dataset["id"] for dataset in datasets_by_type[DataSetType.VISUALISATION.value] ) ).prefetch_related("visualisationlink_set") for visualisation_dataset in visualisation_datasets: dataset = datasets_by_type_id[(DataSetType.VISUALISATION.value, visualisation_dataset.id)] dataset["last_updated"] = max( _without_none( ( link.data_source_last_updated for link in visualisation_dataset.visualisationlink_set.all() ) ), default=None, ) return render( request, "datasets/index.html", { "form": form, "query": filters.query, "datasets": datasets, "data_type": dict(data_types), "show_admin_filters": has_unpublished_dataset_access(request.user), "DATASET_FINDER_FLAG": settings.DATASET_FINDER_ADMIN_ONLY_FLAG, "search_type": "searchBar" if filters.query else "noSearch", "has_filters": filters.has_filters(), }, ) class DatasetDetailView(DetailView): def _is_reference_dataset(self): return isinstance(self.object, ReferenceDataset) def _is_visualisation(self): return isinstance(self.object, VisualisationCatalogueItem) def get_object(self, queryset=None): return find_dataset(self.kwargs["dataset_uuid"], self.request.user) @csp_update(frame_src=settings.QUICKSIGHT_DASHBOARD_HOST) def get(self, request, *args, **kwargs): return super().get(request, *args, **kwargs) def _get_source_text(self, model): source_text = ",".join( sorted({t.name for t in self.object.tags.filter(type=TagType.SOURCE)}) ) return source_text def _get_user_tools_access(self) -> bool: user_has_tools_access = self.request.user.user_permissions.filter( codename="start_all_applications", content_type=ContentType.objects.get_for_model(ApplicationInstance), ).exists() return user_has_tools_access def _get_context_data_for_master_dataset(self, ctx, **kwargs): source_tables = sorted(self.object.sourcetable_set.all(), key=lambda x: x.name) MasterDatasetInfo = namedtuple( "MasterDatasetInfo", ("source_table", "code_snippets", "columns") ) master_datasets_info = [ MasterDatasetInfo( source_table=source_table, code_snippets=get_code_snippets_for_table(source_table), columns=datasets_db.get_columns( source_table.database.memorable_name, schema=source_table.schema, table=source_table.table, include_types=True, ), ) for source_table in sorted(source_tables, key=lambda x: x.name) ] summarised_update_frequency = ",".join( sorted({t.get_frequency_display() for t in source_tables}) ) subscription = self.object.subscriptions.filter(user=self.request.user) ctx.update( { "summarised_update_frequency": summarised_update_frequency, "source_text": self._get_source_text(self.object), "has_access": self.object.user_has_access(self.request.user), "has_tools_access": self._get_user_tools_access(), "is_bookmarked": self.object.user_has_bookmarked(self.request.user), "master_datasets_info": master_datasets_info, "source_table_type": DataLinkType.SOURCE_TABLE, "related_data": self.object.related_datasets(), "related_visualisations": self.object.related_visualisations.filter( published=True ), "subscription": { "current_user_is_subscribed": subscription.exists() and subscription.first().is_active(), "details": subscription.first(), }, } ) return ctx def _get_context_data_for_datacut_dataset(self, ctx, **kwargs): custom_queries = self.object.customdatasetquery_set.all().prefetch_related("tables") datacut_links = sorted( chain( self.object.sourcetable_set.all(), self.object.sourcelink_set.all(), custom_queries, ), key=lambda x: x.name, ) summarised_update_frequency = ",".join( sorted({t.get_frequency_display() for t in datacut_links}) ) DatacutLinkInfo = namedtuple( "DatacutLinkInfo", ("datacut_link", "can_show_link", "code_snippets", "columns"), ) datacut_links_info = [ DatacutLinkInfo( datacut_link=datacut_link, can_show_link=datacut_link.can_show_link_for_user(self.request.user), code_snippets=( get_code_snippets_for_query(datacut_link.query) if hasattr(datacut_link, "query") else None ), columns=( datasets_db.get_columns( database_name=datacut_link.database.memorable_name, query=datacut_link.query, include_types=True, ) if hasattr(datacut_link, "query") else None ), ) for datacut_link in datacut_links ] subscription = self.object.subscriptions.filter(user=self.request.user) ctx.update( { "has_access": self.object.user_has_access(self.request.user), "is_bookmarked": self.object.user_has_bookmarked(self.request.user), "datacut_links_info": datacut_links_info, "data_hosted_externally": any( not source_link.url.startswith("s3://") for source_link in self.object.sourcelink_set.all() ), "custom_dataset_query_type": DataLinkType.CUSTOM_QUERY, "related_data": self.object.related_datasets(), "related_visualisations": self.object.related_visualisations.filter( published=True ), "summarised_update_frequency": summarised_update_frequency, "source_text": self._get_source_text(self.object), "subscription": { "current_user_is_subscribed": subscription.exists() and subscription.first().is_active(), "details": subscription.first(), }, } ) return ctx def _get_context_data_for_reference_dataset(self, ctx, **kwargs): records = self.object.get_records() total_record_count = records.count() preview_limit = self.get_preview_limit(total_record_count) records = records[:preview_limit] code_snippets = get_code_snippets_for_reference_table(self.object.table_name) columns = None if self.object.external_database: columns = datasets_db.get_columns( self.object.external_database.memorable_name, schema="public", table=self.object.table_name, include_types=True, ) subscription = self.object.subscriptions.filter(user=self.request.user) ctx.update( { "preview_limit": preview_limit, "record_count": total_record_count, "records": records, "is_bookmarked": self.object.user_has_bookmarked(self.request.user), "DATA_GRID_REFERENCE_DATASET_FLAG": settings.DATA_GRID_REFERENCE_DATASET_FLAG, "code_snippets": code_snippets, "columns": columns, "subscription": { "current_user_is_subscribed": subscription.exists() and subscription.first().is_active(), "details": subscription.first(), }, } ) return ctx def _get_context_data_for_visualisation(self, ctx, **kwargs): ctx.update( { "has_access": self.object.user_has_access(self.request.user), "is_bookmarked": self.object.user_has_bookmarked(self.request.user), "visualisation_links": self.object.get_visualisation_links(self.request), "summarised_update_frequency": "N/A", "source_text": self._get_source_text(self.object), } ) return ctx def get_context_data(self, **kwargs): ctx = super().get_context_data() ctx["model"] = self.object ctx["DATA_CUT_ENHANCED_PREVIEW_FLAG"] = settings.DATA_CUT_ENHANCED_PREVIEW_FLAG ctx["DATASET_CHANGELOG_PAGE_FLAG"] = settings.DATASET_CHANGELOG_PAGE_FLAG ctx["DATA_UPLOADER_UI_FLAG"] = settings.DATA_UPLOADER_UI_FLAG if self._is_reference_dataset(): return self._get_context_data_for_reference_dataset(ctx, **kwargs) elif self._is_visualisation(): return self._get_context_data_for_visualisation(ctx, **kwargs) elif self.object.type == DataSetType.MASTER: return self._get_context_data_for_master_dataset(ctx, **kwargs) elif self.object.type == DataSetType.DATACUT: return self._get_context_data_for_datacut_dataset(ctx, **kwargs) raise ValueError(f"Unknown dataset/type for {self.__class__.__name__}: {self.object}") def get_template_names(self): if self._is_reference_dataset(): return ["datasets/referencedataset_detail.html"] elif self.object.type == DataSetType.MASTER: return ["datasets/master_dataset.html"] elif self.object.type == DataSetType.DATACUT: return ["datasets/data_cut_dataset.html"] elif self._is_visualisation(): return ["datasets/visualisation_catalogue_item.html"] raise RuntimeError(f"Unknown template for {self}") def get_preview_limit(self, record_count): return min([record_count, settings.REFERENCE_DATASET_PREVIEW_NUM_OF_ROWS]) @require_http_methods(["GET", "POST"]) def eligibility_criteria_view(request, dataset_uuid): dataset = find_dataset(dataset_uuid, request.user) if request.method == "POST": form = EligibilityCriteriaForm(request.POST) if form.is_valid(): access_request_id = form.cleaned_data.get("access_request") if form.cleaned_data["meet_criteria"]: url = reverse("request_access:dataset", args=[dataset_uuid]) if access_request_id: url = reverse( "request_access:dataset-request-update", args=[access_request_id], ) else: url = reverse("datasets:eligibility_criteria_not_met", args=[dataset_uuid]) return HttpResponseRedirect(url) return render( request, "eligibility_criteria.html", {"dataset": dataset, "access_request": request.GET.get("access_request")}, ) @require_GET def toggle_bookmark(request, dataset_uuid): dataset = find_dataset(dataset_uuid, request.user) dataset.toggle_bookmark(request.user) return HttpResponseRedirect(dataset.get_absolute_url()) class ReferenceDatasetDownloadView(DetailView): model = ReferenceDataset def get_object(self, queryset=None): return find_dataset(self.kwargs["dataset_uuid"], self.request.user, ReferenceDataset) def get(self, request, *args, **kwargs): dl_format = self.kwargs.get("format") if dl_format not in ["json", "csv"]: raise Http404 ref_dataset = self.get_object() records = [] for record in ref_dataset.get_records(): record_data = {} for field in ref_dataset.fields.all(): if field.data_type == ReferenceDatasetField.DATA_TYPE_FOREIGN_KEY: relationship = getattr(record, field.relationship_name) record_data[field.name] = ( getattr( relationship, field.linked_reference_dataset_field.column_name, ) if relationship else None ) else: record_data[field.name] = getattr(record, field.column_name) records.append(record_data) response = HttpResponse() response["Content-Disposition"] = "attachment; filename={}-{}.{}".format( ref_dataset.slug, ref_dataset.published_version, dl_format ) log_event( request.user, EventLog.TYPE_REFERENCE_DATASET_DOWNLOAD, ref_dataset, extra={ "path": request.get_full_path(), "reference_dataset_version": ref_dataset.published_version, "download_format": dl_format, }, ) ref_dataset.number_of_downloads = F("number_of_downloads") + 1 ref_dataset.save(update_fields=["number_of_downloads"]) if dl_format == "json": response["Content-Type"] = "application/json" response.write(json.dumps(list(records), cls=DjangoJSONEncoder)) else: response["Content-Type"] = "text/csv" with closing(io.StringIO()) as outfile: writer = csv.DictWriter( outfile, fieldnames=ref_dataset.export_field_names, quoting=csv.QUOTE_NONNUMERIC, ) writer.writeheader() writer.writerows(records) response.write(outfile.getvalue()) # pylint: disable=no-member return response class SourceLinkDownloadView(DetailView): model = SourceLink def get(self, request, *args, **kwargs): dataset = find_dataset(self.kwargs.get("dataset_uuid"), request.user) if not dataset.user_has_access(self.request.user): return HttpResponseForbidden() source_link = get_object_or_404( SourceLink, id=self.kwargs.get("source_link_id"), dataset=dataset ) log_event( request.user, EventLog.TYPE_DATASET_SOURCE_LINK_DOWNLOAD, source_link.dataset, extra={ "path": request.get_full_path(), **serializers.serialize("python", [source_link])[0], }, ) dataset.number_of_downloads = F("number_of_downloads") + 1 dataset.save(update_fields=["number_of_downloads"]) if source_link.link_type == source_link.TYPE_EXTERNAL: return HttpResponseRedirect(source_link.url) client = get_s3_client() try: file_object = client.get_object( Bucket=settings.AWS_UPLOADS_BUCKET, Key=source_link.url ) except ClientError as ex: try: return HttpResponse(status=ex.response["ResponseMetadata"]["HTTPStatusCode"]) except KeyError: return HttpResponseServerError() response = StreamingHttpResponseWithoutDjangoDbConnection( file_object["Body"].iter_chunks(chunk_size=65536), content_type=file_object["ContentType"], ) response["Content-Disposition"] = f'attachment; filename="{source_link.get_filename()}"' response["Content-Length"] = file_object["ContentLength"] return response class SourceDownloadMixin: pk_url_kwarg = "source_id" event_log_type = None @staticmethod def db_object_exists(db_object): raise NotImplementedError() def get_table_data(self, db_object): raise NotImplementedError() def get(self, request, *_, **__): dataset = find_dataset(self.kwargs.get("dataset_uuid"), request.user) db_object = get_object_or_404(self.model, id=self.kwargs.get("source_id"), dataset=dataset) if not db_object.dataset.user_has_access(self.request.user): return HttpResponseForbidden() if not self.db_object_exists(db_object): return HttpResponseNotFound() log_event( request.user, self.event_log_type, db_object.dataset, extra={ "path": request.get_full_path(), **serializers.serialize("python", [db_object])[0], }, ) dataset.number_of_downloads = F("number_of_downloads") + 1 dataset.save(update_fields=["number_of_downloads"]) return self.get_table_data(db_object) class SourceViewDownloadView(SourceDownloadMixin, DetailView): model = SourceView event_log_type = EventLog.TYPE_DATASET_SOURCE_VIEW_DOWNLOAD @staticmethod def db_object_exists(db_object): return view_exists(db_object.database.memorable_name, db_object.schema, db_object.view) def get_table_data(self, db_object): return table_data( self.request.user.email, db_object.database.memorable_name, db_object.schema, db_object.view, db_object.get_filename(), ) class CustomDatasetQueryDownloadView(DetailView): model = CustomDatasetQuery def get(self, request, *args, **kwargs): dataset = find_dataset(self.kwargs.get("dataset_uuid"), request.user) if not dataset.user_has_access(self.request.user): return HttpResponseForbidden() query = get_object_or_404(self.model, id=self.kwargs.get("query_id"), dataset=dataset) if not query.reviewed and not request.user.is_superuser: return HttpResponseForbidden() log_event( request.user, EventLog.TYPE_DATASET_CUSTOM_QUERY_DOWNLOAD, query.dataset, extra={ "path": request.get_full_path(), **serializers.serialize("python", [query])[0], }, ) dataset.number_of_downloads = F("number_of_downloads") + 1 dataset.save(update_fields=["number_of_downloads"]) filtered_query = sql.SQL(query.query) columns = request.GET.getlist("columns") if columns: trimmed_query = query.query.rstrip().rstrip(";") filtered_query = sql.SQL("SELECT {fields} from ({query}) as data;").format( fields=sql.SQL(",").join([sql.Identifier(column) for column in columns]), query=sql.SQL(trimmed_query), ) return streaming_query_response( request.user.email, query.database.memorable_name, filtered_query, query.get_filename(), cursor_name=f"custom_query--{query.id}", ) class DatasetPreviewView(DetailView, metaclass=ABCMeta): @property @abstractmethod def model(self): pass @abstractmethod def get_preview_data(self, dataset): pass def get(self, request, *args, **kwargs): user = self.request.user dataset = find_dataset(self.kwargs.get("dataset_uuid"), user) if not dataset.user_has_access(user): return HttpResponseForbidden() source_object, columns, query = self.get_preview_data(dataset) records = [] sample_size = settings.DATASET_PREVIEW_NUM_OF_ROWS if columns: rows = get_random_data_sample( source_object.database.memorable_name, sql.SQL(query), sample_size, ) for row in rows: record_data = {} for i, column in enumerate(columns): record_data[column] = row[i] records.append(record_data) can_download = source_object.can_show_link_for_user(user) return render( request, "datasets/dataset_preview.html", { "dataset": dataset, "source_object": source_object, "fields": columns, "records": records, "preview_limit": sample_size, "record_count": len(records), "fixed_table_height_limit": 10, "truncate_limit": 100, "can_download": can_download, "type": source_object.type, }, ) class SourceTablePreviewView(DatasetPreviewView): model = SourceTable def get_preview_data(self, dataset): source_table_object = get_object_or_404( self.model, id=self.kwargs.get("table_uuid"), dataset=dataset ) database_name = source_table_object.database.memorable_name table_name = source_table_object.table schema_name = source_table_object.schema columns = datasets_db.get_columns(database_name, schema=schema_name, table=table_name) preview_query = f""" select * from "{schema_name}"."{table_name}" """ return source_table_object, columns, preview_query class CustomDatasetQueryPreviewView(DatasetPreviewView): model = CustomDatasetQuery def get_preview_data(self, dataset): query_object = get_object_or_404( self.model, id=self.kwargs.get("query_id"), dataset=dataset ) if not query_object.reviewed and not self.request.user.is_superuser: raise PermissionDenied() database_name = query_object.database.memorable_name columns = datasets_db.get_columns(database_name, query=query_object.query) preview_query = query_object.query return query_object, columns, preview_query class SourceTableColumnDetails(View): def get(self, request, dataset_uuid, table_uuid): dataset = find_dataset(dataset_uuid, request.user, MasterDataset) source_table = get_object_or_404(SourceTable, id=table_uuid, dataset=dataset) columns = datasets_db.get_columns( source_table.database.memorable_name, schema=source_table.schema, table=source_table.table, include_types=True, ) return render( request, "datasets/source_table_column_details.html", context={ "dataset": dataset, "source_table": source_table, "columns": columns, }, ) class ReferenceDatasetColumnDetails(View): def get(self, request, dataset_uuid): dataset = find_dataset(dataset_uuid, request.user, ReferenceDataset) columns = datasets_db.get_columns( dataset.external_database.memorable_name, schema="public", table=dataset.table_name, include_types=True, ) return render( request, "datasets/referencedataset_column_details.html", context={"dataset": dataset, "columns": columns}, ) class ReferenceDatasetGridView(View): def get(self, request, dataset_uuid): dataset = find_dataset(dataset_uuid, request.user, ReferenceDataset) return render( request, "datasets/reference_dataset_grid.html", context={"model": dataset}, ) class RelatedDataView(View): def get(self, request, dataset_uuid): dataset = find_dataset(dataset_uuid, request.user) if dataset.type == DataSetType.DATACUT: form = RelatedMastersSortForm(request.GET) elif dataset.type == DataSetType.MASTER: form = RelatedDataCutsSortForm(request.GET) else: return HttpResponse(status=404) if form.is_valid(): related_datasets = dataset.related_datasets( order=form.cleaned_data.get("sort") or form.fields["sort"].initial ) return render( request, "datasets/related_data.html", context={ "dataset": dataset, "related_data": related_datasets, "form": form, }, ) return HttpResponse(status=500) class RelatedVisualisationsView(View): def get(self, request, dataset_uuid): dataset = find_dataset(dataset_uuid, request.user) form = RelatedVisualisationsSortForm(request.GET) if form.is_valid(): related_visualisations = dataset.related_visualisations.order_by( form.cleaned_data.get("sort") or form.fields["sort"].initial ) return render( request, "datasets/related_visualisations.html", context={ "dataset": dataset, "related_visualisations": related_visualisations, "form": form, }, ) return HttpResponse(status=500) class DataCutPreviewView(WaffleFlagMixin, DetailView): waffle_flag = settings.DATA_CUT_ENHANCED_PREVIEW_FLAG template_name = "datasets/data_cut_preview.html" def dispatch(self, request, *args, **kwargs): if not self.get_object().dataset.user_has_access(self.request.user): return HttpResponseForbidden() return super().dispatch(request, *args, **kwargs) def get_object(self, queryset=None): return get_object_or_404(self.kwargs["model_class"], pk=self.kwargs["object_id"]) def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) model = self.get_object() ctx.update( { "can_download": model.can_show_link_for_user(self.request.user), "form_action": model.get_absolute_url(), "can_filter_columns": model.show_column_filter(), "truncate_limit": 100, "fixed_table_height_limit": 10, } ) if model.user_can_preview(self.request.user): columns, records = model.get_preview_data() ctx.update( { "columns": columns, "records": records, "preview_limit": min( [len(records), settings.REFERENCE_DATASET_PREVIEW_NUM_OF_ROWS] ), } ) return ctx class DatasetUsageHistoryView(View): def get(self, request, dataset_uuid, **kwargs): dataset = find_dataset(dataset_uuid, request.user, kwargs["model_class"]) if dataset.type == DataSetType.MASTER: tables = list(dataset.sourcetable_set.values_list("table", flat=True)) return render( request, "datasets/dataset_usage_history.html", context={ "dataset": dataset, "event_description": "Queried", "rows": ToolQueryAuditLogTable.objects.filter(table__in=tables) .annotate(day=TruncDay("audit_log__timestamp")) .annotate(email=F("audit_log__user__email")) .annotate(object=F("table")) .order_by("-day") .values("day", "email", "object") .annotate(count=Count("id"))[:100], }, ) return render( request, "datasets/dataset_usage_history.html", context={ "dataset": dataset, "event_description": "Viewed" if dataset.type == DataSetType.VISUALISATION else "Downloaded", "rows": dataset.events.filter( event_type__in=[ EventLog.TYPE_DATASET_SOURCE_LINK_DOWNLOAD, EventLog.TYPE_DATASET_CUSTOM_QUERY_DOWNLOAD, EventLog.TYPE_VIEW_VISUALISATION_TEMPLATE, EventLog.TYPE_VIEW_SUPERSET_VISUALISATION, EventLog.TYPE_VIEW_QUICKSIGHT_VISUALISATION, ] ) .annotate(day=TruncDay("timestamp")) .annotate(email=F("user__email")) .annotate( object=Func( F("extra"), Value("fields"), Value("name"), function="jsonb_extract_path_text", output_field=CharField(), ), ) .order_by("-day") .values("day", "email", "object") .annotate(count=Count("id"))[:100], }, ) class DataCutSourceDetailView(DetailView): template_name = "datasets/data_cut_source_detail.html" def dispatch(self, request, *args, **kwargs): source = self.get_object() if not source.data_grid_enabled: raise DatasetPreviewDisabledError(source.dataset) if not source.dataset.user_has_access(self.request.user): raise DatasetPermissionDenied(source.dataset) return super().dispatch(request, *args, **kwargs) def get_object(self, queryset=None): dataset = find_dataset(self.kwargs["dataset_uuid"], self.request.user) return get_object_or_404( self.kwargs["model_class"], dataset=dataset, pk=self.kwargs["object_id"], ) class DataGridDataView(DetailView): def _user_can_access(self): source = self.get_object() return source.dataset.user_has_access(self.request.user) and source.data_grid_enabled def get_object(self, queryset=None): dataset = find_dataset(self.kwargs.get("dataset_uuid"), self.request.user) return get_object_or_404( self.kwargs["model_class"], dataset=dataset, pk=self.kwargs["object_id"], ) def dispatch(self, request, *args, **kwargs): if not self._user_can_access(): return HttpResponseForbidden() return super().dispatch(request, *args, **kwargs) @staticmethod def _get_rows(source, query, query_params): with psycopg2.connect( database_dsn(settings.DATABASES_DATA[source.database.memorable_name]) ) as connection: with connection.cursor( name="data-grid-data", cursor_factory=psycopg2.extras.RealDictCursor, ) as cursor: cursor.execute(query, query_params) return cursor.fetchall() def post(self, request, *args, **kwargs): source = self.get_object() if request.GET.get("download"): if not source.data_grid_download_enabled: return JsonResponse({}, status=403) filters = {} for filter_data in [json.loads(x) for x in request.POST.getlist("filters")]: filters.update(filter_data) column_config = [ x for x in source.get_column_config() if x["field"] in request.POST.getlist("columns", []) ] if not column_config: return JsonResponse({}, status=400) post_data = { "filters": filters, "limit": source.data_grid_download_limit, "sortDir": request.POST.get("sortDir", "ASC"), "sortField": request.POST.get("sortField", column_config[0]["field"]), } else: post_data = json.loads(request.body.decode("utf-8")) post_data["limit"] = min(post_data.get("limit", 100), 100) column_config = source.get_column_config() original_query = source.get_data_grid_query() query, params = build_filtered_dataset_query( original_query, column_config, post_data, ) if request.GET.get("download"): extra = { "correlation_id": str(uuid.uuid4()), **serializers.serialize("python", [source])[0], } log_event( request.user, EventLog.TYPE_DATASET_CUSTOM_QUERY_DOWNLOAD, source.dataset, extra=extra, ) def write_metrics_to_eventlog(log_data): logger.debug("write_metrics_to_eventlog %s", log_data) log_data.update(extra) log_event( request.user, EventLog.TYPE_DATASET_CUSTOM_QUERY_DOWNLOAD_COMPLETE, source.dataset, extra=log_data, ) return streaming_query_response( request.user.email, source.database.memorable_name, query, request.POST.get("export_file_name", f"custom-{source.dataset.slug}-export.csv"), params, original_query, write_metrics_to_eventlog, cursor_name=f'data-grid--{self.kwargs['model_class'].__name__}--{source.id}', ) records = self._get_rows(source, query, params) return JsonResponse({"records": records}) class DatasetVisualisationPreview(View): def _get_vega_definition(self, visualisation): vega_definition = json.loads(visualisation.vega_definition_json) if visualisation.query: with psycopg2.connect( database_dsn(settings.DATABASES_DATA[visualisation.database.memorable_name]) ) as connection: with connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cursor: cursor.execute(visualisation.query) data = cursor.fetchall() try: # vega-lite, 'data' is a dictionary vega_definition["data"]["values"] = data except TypeError: # vega, 'data' is a list, and we support setting the query # results as the first item vega_definition["data"][0]["values"] = data return vega_definition def get(self, request, dataset_uuid, object_id, **kwargs): model_class = kwargs["model_class"] dataset = find_dataset(dataset_uuid, request.user, model_class) if not dataset.user_has_access(request.user): return HttpResponseForbidden() visualisation = dataset.visualisations.get(id=object_id) vega_definition = self._get_vega_definition(visualisation) return JsonResponse(vega_definition) class DatasetVisualisationView(View): def get(self, request, dataset_uuid, object_id, **kwargs): model_class = kwargs["model_class"] dataset = find_dataset(dataset_uuid, self.request.user, model_class) if not dataset.user_has_access(request.user): return HttpResponseForbidden() visualisation = dataset.visualisations.live().get(id=object_id) return render( request, "datasets/visualisation.html", context={"dataset_uuid": dataset_uuid, "visualisation": visualisation}, ) class CustomQueryColumnDetails(View): def get(self, request, dataset_uuid, query_id): dataset = find_dataset(dataset_uuid, self.request.user, DataCutDataset) try: query = CustomDatasetQuery.objects.get(id=query_id, dataset__id=dataset_uuid) except CustomDatasetQuery.DoesNotExist: return HttpResponse(status=404) return render( request, "datasets/data_cut_column_details.html", context={ "dataset": dataset, "query": query, "columns": datasets_db.get_columns( query.database.memorable_name, query=query.query, include_types=True ), }, ) class SourceChangelogView(WaffleFlagMixin, DetailView): waffle_flag = settings.DATASET_CHANGELOG_PAGE_FLAG template_name = "datasets/source_changelog.html" context_object_name = "source" def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx["changelog"] = get_detailed_changelog(self.get_object()) return ctx def get_object(self, queryset=None): dataset = find_dataset(self.kwargs["dataset_uuid"], self.request.user) if self.kwargs["model_class"] == ReferenceDataset: return dataset return get_object_or_404( self.kwargs["model_class"], dataset=dataset, pk=self.kwargs["source_id"], ) class DatasetChartView(WaffleFlagMixin, View): waffle_flag = settings.CHART_BUILDER_PUBLISH_CHARTS_FLAG def get_object(self): dataset = find_dataset( self.kwargs["dataset_uuid"], self.request.user, self.kwargs["model_class"] ) return dataset.charts.get(id=self.kwargs["object_id"]) @csp_update(SCRIPT_SRC=["'unsafe-eval'", "blob:"], IMG_SRC=["blob:"]) def get(self, request, **kwargs): chart = self.get_object() if not chart.dataset.user_has_access(request.user): return HttpResponseForbidden() return render( request, "datasets/charts/chart.html", context={ "chart": chart, }, ) class DatasetChartDataView(DatasetChartView): waffle_flag = settings.CHART_BUILDER_PUBLISH_CHARTS_FLAG def get(self, request, **kwargs): dataset_chart = self.get_object() if not dataset_chart.dataset.user_has_access(request.user): return HttpResponseForbidden() chart = dataset_chart.chart return JsonResponse( { "total_rows": chart.query_log.rows, "duration": chart.query_log.duration, "data": chart.get_table_data(chart.get_required_columns()), } ) class EditBaseView(View): obj = None summary: str = None def dispatch(self, request, *args, **kwargs): try: dataset = DataSet.objects.live().get(pk=self.kwargs.get("pk")) except DataSet.DoesNotExist: dataset = None try: visualisation_catalogue_item = VisualisationCatalogueItem.objects.live().get( pk=self.kwargs.get("pk") ) except VisualisationCatalogueItem.DoesNotExist: raise Http404 # pylint: disable=W0707 if "summary_id" in self.kwargs: self.summary = get_object_or_404( PendingAuthorizedUsers.objects.all(), pk=self.kwargs.get("summary_id") ) self.obj = dataset or visualisation_catalogue_item if ( request.user not in [ self.obj.information_asset_owner, self.obj.information_asset_manager, ] and not request.user.is_superuser ): return HttpResponseForbidden() return super().dispatch(request, *args, **kwargs) class DatasetEditView(EditBaseView, UpdateView): model = DataSet form_class = DatasetEditForm template_name = "datasets/edit_dataset.html" def get_success_url(self): return self.object.get_absolute_url() def get_initial(self): return { "enquiries_contact": self.object.enquiries_contact.email if self.object.enquiries_contact else "", "authorized_email_domains": ",".join(self.object.authorized_email_domains), } def form_valid(self, form): if "authorized_email_domains" in form.changed_data: log_permission_change( self.request.user, self.object, EventLog.TYPE_CHANGED_AUTHORIZED_EMAIL_DOMAIN, {"authorized_email_domains": self.object.authorized_email_domains}, f"authorized_email_domains set to {self.object.authorized_email_domains}", ) # As the dataset's access type has changed, clear cached credentials for all # users to ensure they either: # - lose access if it went from REQUIRES_AUTHENTICATION/OPEN to REQUIRES_AUTHORIZATION # - get access if it went from REQUIRES_AUTHORIZATION to REQUIRES_AUTHENTICATION/OPEN invalidate_data_explorer_user_cached_credentials() invalidate_superset_user_cached_credentials() messages.success(self.request, "Dataset updated") return super().form_valid(form) class VisualisationCatalogueItemEditView(EditBaseView, UpdateView): model = VisualisationCatalogueItem form_class = VisualisationCatalogueItemEditForm template_name = "datasets/edit_visualisation_catalogue_item.html" def get_success_url(self): return self.object.get_absolute_url() def get_initial(self): return { "enquiries_contact": self.object.enquiries_contact.email if self.object.enquiries_contact else "", "secondary_enquiries_contact": self.object.secondary_enquiries_contact.email if self.object.secondary_enquiries_contact else "", "authorized_email_domains": ",".join(self.object.authorized_email_domains), } def form_valid(self, form): if "authorized_email_domains" in form.changed_data: log_permission_change( self.request.user, self.object, EventLog.TYPE_CHANGED_AUTHORIZED_EMAIL_DOMAIN, {"authorized_email_domains": self.object.authorized_email_domains}, f"authorized_email_domains set to {self.object.authorized_email_domains}", ) # As the dataset's access type has changed, clear cached credentials for all # users to ensure they either: # - lose access if it went from REQUIRES_AUTHENTICATION/OPEN to REQUIRES_AUTHORIZATION # - get access if it went from REQUIRES_AUTHORIZATION to REQUIRES_AUTHENTICATION/OPEN invalidate_data_explorer_user_cached_credentials() invalidate_superset_user_cached_credentials() messages.success(self.request, "Dataset updated") return super().form_valid(form) class UserSearchFormView(EditBaseView, FormView): form_class = UserSearchForm form: None def form_valid(self, form): self.form = form return super().form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) search_query = self.request.GET.get("search_query") if search_query: email_filter = Q(email__icontains=search_query) name_filter = Q(first_name__icontains=search_query) | Q( last_name__icontains=search_query ) users = get_user_model().objects.filter(Q(email_filter | name_filter)) context["search_results"] = users context["search_query"] = search_query context["obj"] = self.obj context["obj_edit_url"] = ( reverse("datasets:edit_dataset", args=[self.obj.pk]) if isinstance(self.obj, DataSet) else reverse("datasets:edit_visualisation_catalogue_item", args=[self.obj.pk]) ) return context class DatasetEnquiriesContactSearchView(UserSearchFormView): template_name = "datasets/search_enquiries_contact.html" def get_success_url(self): url = ( reverse( "datasets:search_enquiries_contact", args=[ self.obj.pk, ], ) + "?search_query=" + self.form.cleaned_data["search"] ) if self.request.GET.get("secondary_enquiries_contact"): url = ( url + "&secondary_enquiries_contact=" + self.request.GET.get("secondary_enquiries_contact") ) return url class DatasetSecondaryEnquiriesContactSearchView(UserSearchFormView): template_name = "datasets/search_secondary_enquiries_contact.html" def get_success_url(self): url = ( reverse( "datasets:search_secondary_enquiries_contact", args=[ self.obj.pk, ], ) + "?search_query=" + self.form.cleaned_data["search"] ) if self.request.GET.get("enquiries_contact"): url = url + "&enquiries_contact=" + self.request.GET.get("enquiries_contact") return url class DatasetEditPermissionsView(EditBaseView, View): def dispatch(self, request, *args, **kwargs): super().dispatch(request, *args, **kwargs) if isinstance(self.obj, DataSet): permissions = DataSetUserPermission.objects.filter(dataset=self.obj) else: permissions = VisualisationUserPermission.objects.filter(visualisation=self.obj) users = json.dumps([p.user.id for p in permissions]) summary = PendingAuthorizedUsers.objects.create(created_by=request.user, users=users) return HttpResponseRedirect( reverse("datasets:edit_permissions_summary", args=[self.obj.id, summary.id]) ) class DatasetEditPermissionsSummaryView(EditBaseView, TemplateView): template_name = "datasets/edit_permissions_summary.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["obj"] = self.obj context["obj_edit_url"] = ( reverse("datasets:edit_dataset", args=[self.obj.pk]) if isinstance(self.obj, DataSet) else reverse("datasets:edit_visualisation_catalogue_item", args=[self.obj.pk]) ) context["summary"] = self.summary context["authorised_users"] = get_user_model().objects.filter( id__in=json.loads(self.summary.users if self.summary.users else "[]") ) return context def post(self, request, *args, **kwargs): authorized_users = set( get_user_model().objects.filter( id__in=json.loads(self.summary.users if self.summary.users else "[]") ) ) if isinstance(self.obj, DataSet): process_dataset_authorized_users_change( authorized_users, request.user, self.obj, False, False, True ) messages.success(request, "Dataset permissions updated") return HttpResponseRedirect(reverse("datasets:edit_dataset", args=[self.obj.id])) else: process_visualisation_catalogue_item_authorized_users_change( authorized_users, request.user, self.obj, False, False ) messages.success(request, "Visualisation permissions updated") return HttpResponseRedirect( reverse("datasets:edit_visualisation_catalogue_item", args=[self.obj.id]) ) class DatasetAuthorisedUsersSearchView(UserSearchFormView): template_name = "datasets/search_authorised_users.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["summary_id"] = self.kwargs.get("summary_id") return context def get_success_url(self): return ( reverse( "datasets:search_authorized_users", args=[self.obj.pk, self.kwargs.get("summary_id")], ) + "?search_query=" + self.form.cleaned_data["search"] ) class DatasetAddAuthorisedUserView(EditBaseView, View): def get(self, request, *args, **kwargs): summary = PendingAuthorizedUsers.objects.get(id=self.kwargs.get("summary_id")) user = get_user_model().objects.get(id=self.kwargs.get("user_id")) users = json.loads(summary.users if summary.users else "[]") if user.id not in users: users.append(user.id) summary.users = json.dumps(users) summary.save() return HttpResponseRedirect( reverse( "datasets:edit_permissions_summary", args=[ self.obj.id, self.kwargs.get("summary_id"), ], ) ) class DatasetRemoveAuthorisedUserView(EditBaseView, View): def get(self, request, *args, **kwargs): summary = PendingAuthorizedUsers.objects.get(id=self.kwargs.get("summary_id")) user = get_user_model().objects.get(id=self.kwargs.get("user_id")) users = json.loads(summary.users if summary.users else "[]") if user.id in users: summary.users = json.dumps([user_id for user_id in users if user_id != user.id]) summary.save() return HttpResponseRedirect( reverse( "datasets:edit_permissions_summary", args=[ self.obj.id, self.kwargs.get("summary_id"), ], ) ) class SelectChartSourceView(WaffleFlagMixin, FormView): waffle_flag = settings.CHART_BUILDER_BUILD_CHARTS_FLAG form_class = ChartSourceSelectForm template_name = "datasets/charts/select_chart_source.html" def get_object(self, queryset=None): dataset = find_dataset(self.kwargs["pk"], self.request.user, DataSet) if not dataset.user_has_access(self.request.user): raise DatasetPermissionDenied(dataset) return dataset def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx["dataset"] = self.get_object() return ctx def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["dataset"] = self.get_object() return kwargs def form_valid(self, form): dataset = self.get_object() source_id = form.cleaned_data["source"] source = dataset.get_related_source(source_id) if source is None: raise Http404 chart = ChartBuilderChart.objects.create_from_source(source, self.request.user) run_chart_builder_query.delay(chart.id) if source.data_grid_enabled: return HttpResponseRedirect( reverse("datasets:filter_chart_data", args=(dataset.id, source.id)) ) return HttpResponseRedirect(f"{chart.get_edit_url()}?prev={self.request.path}") class FilterChartDataView(WaffleFlagMixin, DetailView): waffle_flag = settings.CHART_BUILDER_BUILD_CHARTS_FLAG form_class = ChartSourceSelectForm template_name = "datasets/charts/filter_chart_data.html" context_object_name = "source" def get_object(self, queryset=None): dataset = find_dataset(self.kwargs["pk"], self.request.user, DataSet) if not dataset.user_has_access(self.request.user): raise DatasetPermissionDenied(dataset) source = dataset.get_related_source(self.kwargs["source_id"]) if source is None: raise Http404 return source class CreateGridChartView(WaffleFlagMixin, View): waffle_flag = settings.CHART_BUILDER_BUILD_CHARTS_FLAG def post(self, request, dataset_uuid, source_id, *args, **kwargs): dataset = find_dataset(dataset_uuid, self.request.user) source = dataset.get_related_source(source_id) if source is None: raise Http404 filters = {} for filter_data in [json.loads(x) for x in request.POST.getlist("filters")]: filters.update(filter_data) column_config = [ x for x in source.get_column_config() if x["field"] in request.POST.getlist("columns", []) ] post_data = { "filters": filters, "sortDir": request.POST.get("sortDir", "ASC"), "sortField": request.POST.get("sortField", column_config[0]["field"]), } original_query = source.get_data_grid_query() query, params = build_filtered_dataset_query( original_query, column_config, post_data, ) db_name = list(settings.DATABASES_DATA.items())[0][0] with connections[db_name].cursor() as cursor: full_query = cursor.mogrify(query, params).decode() chart = ChartBuilderChart.objects.create_from_sql(str(full_query), request.user, db_name) run_chart_builder_query.delay(chart.id) return HttpResponseRedirect( f"{chart.get_edit_url()}?prev={request.META.get("HTTP_REFERER")}" ) class DatasetChartsView(WaffleFlagMixin, View): waffle_flag = settings.CHART_BUILDER_PUBLISH_CHARTS_FLAG @csp_update(SCRIPT_SRC=["'unsafe-eval'", "blob:"]) def get(self, request, **kwargs): dataset = find_dataset(self.kwargs["dataset_uuid"], self.request.user, DataSet) if not dataset.user_has_access(self.request.user): return HttpResponseForbidden() return render( self.request, "datasets/charts/charts.html", context={"charts": dataset.related_charts(), "dataset": dataset}, ) def find_data_dictionary_view(request, schema_name, table_name): query = SourceTable.objects.filter(schema=schema_name, table=table_name) if not query.exists(): raise Http404 return redirect("datasets:data_dictionary", source_uuid=query.first().id) class DataDictionaryBaseView(View): def get_dictionary(self, source_table): columns = datasets_db.get_columns( source_table.database.memorable_name, schema=source_table.schema, table=source_table.table, include_types=True, ) fields = source_table.field_definitions.all() dictionary = [] for name, data_type in columns: definition = "" if fields.filter(field=name).exists(): definition = fields.filter(field=name).first() dictionary.append( ( name, data_type, definition, ) ) return columns, fields, dictionary class DataDictionaryView(DataDictionaryBaseView): def get(self, request, source_uuid): source_table = get_object_or_404(SourceTable, pk=source_uuid) dataset = None if request.GET.get("dataset_uuid"): dataset = find_dataset(request.GET.get("dataset_uuid"), self.request.user, DataSet) columns, fields, dictionary = self.get_dictionary(source_table) return render( request, "datasets/data_dictionary.html", context={ "source_table": source_table, "dataset": dataset, "columns": columns, "fields": fields, "dictionary": dictionary, }, ) class DataDictionaryEditView(DataDictionaryBaseView): def dispatch(self, request, *args, **kwargs): dataset = DataSet.objects.live().get(pk=self.kwargs.get("dataset_uuid")) if ( request.user not in [ dataset.information_asset_owner, dataset.information_asset_manager, ] and not request.user.is_superuser ): return HttpResponseForbidden() return super().dispatch(request, *args, **kwargs) def get(self, request, dataset_uuid, source_uuid): source_table = get_object_or_404(SourceTable, pk=source_uuid) dataset = find_dataset(dataset_uuid, self.request.user, DataSet) columns, fields, dictionary = self.get_dictionary(source_table) return render( request, "datasets/edit_data_dictionary.html", context={ "source_table": source_table, "dataset": dataset, "columns": columns, "fields": fields, "dictionary": dictionary, }, ) def post(self, request, dataset_uuid, source_uuid): source_table = get_object_or_404(SourceTable, pk=source_uuid) dataset = find_dataset(dataset_uuid, self.request.user, DataSet) for name, value in request.POST.items(): if name == "csrfmiddlewaretoken": continue field, _ = SourceTableFieldDefinition.objects.get_or_create( source_table=source_table, field=name ) field.description = value[:1024] field.save() messages.success(self.request, "Changes saved successfully") redirect_url = ( reverse("datasets:data_dictionary", args=[source_table.id]) + "?dataset_uuid=" + str(dataset.id) ) return redirect(redirect_url)
import csv import io import json import logging import uuid from abc import ABCMeta, abstractmethod from collections import defaultdict, namedtuple from contextlib import closing from itertools import chain from typing import Set import psycopg2 from botocore.exceptions import ClientError from csp.decorators import csp_update from django.conf import settings from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from django.core import serializers from django.core.exceptions import PermissionDenied from django.core.paginator import Paginator from django.core.serializers.json import DjangoJSONEncoder from django.db import connections, ProgrammingError from django.db.models import ( Count, F, CharField, Value, Func, Q, Prefetch, ) from django.db.models.functions import TruncDay from django.forms.models import model_to_dict from django.http import ( Http404, HttpResponse, HttpResponseForbidden, HttpResponseNotFound, HttpResponseRedirect, HttpResponseServerError, JsonResponse, ) from django.shortcuts import get_object_or_404, render, redirect from django.urls import reverse from django.views.decorators.http import ( require_GET, require_http_methods, ) from django.views.generic import DetailView, FormView, TemplateView, UpdateView, View from psycopg2 import sql from waffle.mixins import WaffleFlagMixin from dataworkspace import datasets_db from dataworkspace.apps.api_v1.core.views import invalidate_superset_user_cached_credentials from dataworkspace.apps.applications.models import ApplicationInstance from dataworkspace.apps.core.boto3_client import get_s3_client from dataworkspace.apps.core.charts.models import ChartBuilderChart from dataworkspace.apps.core.charts.tasks import run_chart_builder_query from dataworkspace.apps.core.errors import DatasetPermissionDenied, DatasetPreviewDisabledError from dataworkspace.apps.core.utils import ( StreamingHttpResponseWithoutDjangoDbConnection, database_dsn, streaming_query_response, table_data, view_exists, get_random_data_sample, ) from dataworkspace.apps.core.models import ( Database, ) from dataworkspace.apps.datasets.constants import ( DataSetType, DataLinkType, ) from dataworkspace.apps.datasets.constants import TagType from dataworkspace.apps.datasets.forms import ( ChartSourceSelectForm, DatasetEditForm, DatasetSearchForm, EligibilityCriteriaForm, RelatedMastersSortForm, RelatedDataCutsSortForm, RelatedVisualisationsSortForm, UserSearchForm, VisualisationCatalogueItemEditForm, ) from dataworkspace.apps.datasets.models import ( CustomDatasetQuery, DataCutDataset, DataSet, DataSetUserPermission, PendingAuthorizedUsers, MasterDataset, ReferenceDataset, ReferenceDatasetField, SourceLink, SourceView, VisualisationCatalogueItem, SourceTable, ToolQueryAuditLogTable, Tag, VisualisationUserPermission, SourceTableFieldDefinition, ) from dataworkspace.apps.datasets.permissions.utils import ( process_dataset_authorized_users_change, process_visualisation_catalogue_item_authorized_users_change, ) from dataworkspace.apps.datasets.search import search_for_datasets from dataworkspace.apps.datasets.utils import ( build_filtered_dataset_query, dataset_type_to_manage_unpublished_permission_codename, find_dataset, get_code_snippets_for_table, get_code_snippets_for_query, get_code_snippets_for_reference_table, get_detailed_changelog, ) from dataworkspace.apps.eventlog.models import EventLog from dataworkspace.apps.eventlog.utils import log_event, log_permission_change from dataworkspace.apps.explorer.utils import invalidate_data_explorer_user_cached_credentials logger = logging.getLogger("app") def _matches_filters( data, unpublished: bool, opendata: bool, withvisuals: bool, use: Set, data_type: Set, source_ids: Set, topic_ids: Set, user_accessible: bool = False, user_inaccessible: bool = False, selected_user_datasets: Set = None, ): subscribed_or_bookmarked = set() if data["is_bookmarked"]: subscribed_or_bookmarked.add("bookmarked") if data["is_subscribed"]: subscribed_or_bookmarked.add("subscribed") return ( ( not selected_user_datasets or selected_user_datasets == [None] or set(selected_user_datasets).intersection(subscribed_or_bookmarked) ) and ( not selected_user_datasets or selected_user_datasets == [None] or set(selected_user_datasets).intersection(subscribed_or_bookmarked) ) and (unpublished or data["published"]) and (not opendata or data["is_open_data"]) and (not withvisuals or data["has_visuals"]) and (not data_type or data_type == [None] or data["data_type"] in data_type) and (not source_ids or source_ids.intersection(set(data["source_tag_ids"]))) and (not topic_ids or topic_ids.intersection(set(data["topic_tag_ids"]))) and (not user_accessible or data["has_access"]) and (not user_inaccessible or not data["has_access"]) ) def has_unpublished_dataset_access(user): access = user.is_superuser for dataset_type in DataSetType: access = access or user.has_perm( dataset_type_to_manage_unpublished_permission_codename(dataset_type.value) ) return access def _get_tags_as_dict(): """ Gets all tags and returns them as a dictionary keyed by the tag.id as a string @return: """ tags = Tag.objects.all() tags_dict = {} for tag in tags: tags_dict[str(tag.id)] = model_to_dict(tag) return tags_dict @require_GET def find_datasets(request): ############### # Validate form form = DatasetSearchForm(request.GET) if not form.is_valid(): logger.warning(form.errors) return HttpResponseRedirect(reverse("datasets:find_datasets")) data_types = form.fields[ "data_type" ].choices # Cache these now, as we annotate them with result numbers later which we don't want here. ############################################### # Find all results, and matching filter numbers filters = form.get_filters() all_visible_datasets, matched_datasets = search_for_datasets( request.user, filters, _matches_filters ) form.annotate_and_update_filters( all_visible_datasets, matcher=_matches_filters, ) #################################### # Select the current page of results paginator = Paginator( matched_datasets, settings.SEARCH_RESULTS_DATASETS_PER_PAGE, ) datasets = paginator.get_page(request.GET.get("page")) ######################################################## # Augment results with tags, avoiding queries-per-result tags_dict = _get_tags_as_dict() for dataset in datasets: dataset["sources"] = [ tags_dict.get(str(source_id)) for source_id in dataset["source_tag_ids"] ] dataset["topics"] = [tags_dict.get(str(topic_id)) for topic_id in dataset["topic_tag_ids"]] ###################################################################### # Augment results with last updated dates, avoiding queries-per-result # Data structures to quickly look up datasets as needed further down datasets_by_type = defaultdict(list) datasets_by_type_id = {} for dataset in datasets: datasets_by_type[dataset["data_type"]].append(dataset) datasets_by_type_id[(dataset["data_type"], dataset["id"])] = dataset # Reference datasets reference_datasets = ReferenceDataset.objects.filter( uuid__in=tuple(dataset["id"] for dataset in datasets_by_type[DataSetType.REFERENCE.value]) ) for reference_dataset in reference_datasets: dataset = datasets_by_type_id[(DataSetType.REFERENCE.value, reference_dataset.uuid)] try: # If the reference dataset csv table doesn't exist we # get an unhandled relation does not exist error # this is currently only a problem with integration tests dataset["last_updated"] = reference_dataset.data_last_updated except ProgrammingError as e: logger.error(e) dataset["last_updated"] = None # Master datasets and datacuts together to minimise metadata table queries master_datasets = MasterDataset.objects.filter( id__in=tuple(dataset["id"] for dataset in datasets_by_type[DataSetType.MASTER.value]) ).prefetch_related("sourcetable_set") datacut_datasets = DataCutDataset.objects.filter( id__in=tuple(dataset["id"] for dataset in datasets_by_type[DataSetType.DATACUT.value]) ).prefetch_related( Prefetch( "customdatasetquery_set", queryset=CustomDatasetQuery.objects.prefetch_related("tables"), ) ) databases = {database.id: database for database in Database.objects.all()} tables_and_last_updated_dates = datasets_db.get_all_tables_last_updated_date( [ (databases[table.database_id].memorable_name, table.schema, table.table) for master_dataset in master_datasets for table in master_dataset.sourcetable_set.all() ] + [ (databases[query.database_id].memorable_name, table.schema, table.table) for datacut_dataset in datacut_datasets for query in datacut_dataset.customdatasetquery_set.all() for table in query.tables.all() ] ) def _without_none(it): return (val for val in it if val is not None) for master_dataset in master_datasets: dataset = datasets_by_type_id[(DataSetType.MASTER.value, master_dataset.id)] dataset["last_updated"] = max( _without_none( ( tables_and_last_updated_dates[databases[table.database_id].memorable_name].get( (table.schema, table.table) ) for table in master_dataset.sourcetable_set.all() ) ), default=None, ) for datacut_dataset in datacut_datasets: dataset = datasets_by_type_id[(DataSetType.DATACUT.value, datacut_dataset.id)] last_updated_dates_for_queries = ( ( tables_and_last_updated_dates[databases[query.database_id].memorable_name].get( (table.schema, table.table) ) for table in query.tables.all() ) for query in datacut_dataset.customdatasetquery_set.all() ) dataset["last_updated"] = max( _without_none( ( min(_without_none(last_updated_dates_for_query), default=None) for last_updated_dates_for_query in last_updated_dates_for_queries ) ), default=None, ) # Visualisations visualisation_datasets = VisualisationCatalogueItem.objects.filter( id__in=tuple( dataset["id"] for dataset in datasets_by_type[DataSetType.VISUALISATION.value] ) ).prefetch_related("visualisationlink_set") for visualisation_dataset in visualisation_datasets: dataset = datasets_by_type_id[(DataSetType.VISUALISATION.value, visualisation_dataset.id)] dataset["last_updated"] = max( _without_none( ( link.data_source_last_updated for link in visualisation_dataset.visualisationlink_set.all() ) ), default=None, ) return render( request, "datasets/index.html", { "form": form, "query": filters.query, "datasets": datasets, "data_type": dict(data_types), "show_admin_filters": has_unpublished_dataset_access(request.user), "DATASET_FINDER_FLAG": settings.DATASET_FINDER_ADMIN_ONLY_FLAG, "search_type": "searchBar" if filters.query else "noSearch", "has_filters": filters.has_filters(), }, ) class DatasetDetailView(DetailView): def _is_reference_dataset(self): return isinstance(self.object, ReferenceDataset) def _is_visualisation(self): return isinstance(self.object, VisualisationCatalogueItem) def get_object(self, queryset=None): return find_dataset(self.kwargs["dataset_uuid"], self.request.user) @csp_update(frame_src=settings.QUICKSIGHT_DASHBOARD_HOST) def get(self, request, *args, **kwargs): return super().get(request, *args, **kwargs) def _get_source_text(self, model): source_text = ",".join( sorted({t.name for t in self.object.tags.filter(type=TagType.SOURCE)}) ) return source_text def _get_user_tools_access(self) -> bool: user_has_tools_access = self.request.user.user_permissions.filter( codename="start_all_applications", content_type=ContentType.objects.get_for_model(ApplicationInstance), ).exists() return user_has_tools_access def _get_context_data_for_master_dataset(self, ctx, **kwargs): source_tables = sorted(self.object.sourcetable_set.all(), key=lambda x: x.name) MasterDatasetInfo = namedtuple( "MasterDatasetInfo", ("source_table", "code_snippets", "columns") ) master_datasets_info = [ MasterDatasetInfo( source_table=source_table, code_snippets=get_code_snippets_for_table(source_table), columns=datasets_db.get_columns( source_table.database.memorable_name, schema=source_table.schema, table=source_table.table, include_types=True, ), ) for source_table in sorted(source_tables, key=lambda x: x.name) ] summarised_update_frequency = ",".join( sorted({t.get_frequency_display() for t in source_tables}) ) subscription = self.object.subscriptions.filter(user=self.request.user) ctx.update( { "summarised_update_frequency": summarised_update_frequency, "source_text": self._get_source_text(self.object), "has_access": self.object.user_has_access(self.request.user), "has_tools_access": self._get_user_tools_access(), "is_bookmarked": self.object.user_has_bookmarked(self.request.user), "master_datasets_info": master_datasets_info, "source_table_type": DataLinkType.SOURCE_TABLE, "related_data": self.object.related_datasets(), "related_visualisations": self.object.related_visualisations.filter( published=True ), "subscription": { "current_user_is_subscribed": subscription.exists() and subscription.first().is_active(), "details": subscription.first(), }, } ) return ctx def _get_context_data_for_datacut_dataset(self, ctx, **kwargs): custom_queries = self.object.customdatasetquery_set.all().prefetch_related("tables") datacut_links = sorted( chain( self.object.sourcetable_set.all(), self.object.sourcelink_set.all(), custom_queries, ), key=lambda x: x.name, ) summarised_update_frequency = ",".join( sorted({t.get_frequency_display() for t in datacut_links}) ) DatacutLinkInfo = namedtuple( "DatacutLinkInfo", ("datacut_link", "can_show_link", "code_snippets", "columns"), ) datacut_links_info = [ DatacutLinkInfo( datacut_link=datacut_link, can_show_link=datacut_link.can_show_link_for_user(self.request.user), code_snippets=( get_code_snippets_for_query(datacut_link.query) if hasattr(datacut_link, "query") else None ), columns=( datasets_db.get_columns( database_name=datacut_link.database.memorable_name, query=datacut_link.query, include_types=True, ) if hasattr(datacut_link, "query") else None ), ) for datacut_link in datacut_links ] subscription = self.object.subscriptions.filter(user=self.request.user) ctx.update( { "has_access": self.object.user_has_access(self.request.user), "is_bookmarked": self.object.user_has_bookmarked(self.request.user), "datacut_links_info": datacut_links_info, "data_hosted_externally": any( not source_link.url.startswith("s3://") for source_link in self.object.sourcelink_set.all() ), "custom_dataset_query_type": DataLinkType.CUSTOM_QUERY, "related_data": self.object.related_datasets(), "related_visualisations": self.object.related_visualisations.filter( published=True ), "summarised_update_frequency": summarised_update_frequency, "source_text": self._get_source_text(self.object), "subscription": { "current_user_is_subscribed": subscription.exists() and subscription.first().is_active(), "details": subscription.first(), }, } ) return ctx def _get_context_data_for_reference_dataset(self, ctx, **kwargs): records = self.object.get_records() total_record_count = records.count() preview_limit = self.get_preview_limit(total_record_count) records = records[:preview_limit] code_snippets = get_code_snippets_for_reference_table(self.object.table_name) columns = None if self.object.external_database: columns = datasets_db.get_columns( self.object.external_database.memorable_name, schema="public", table=self.object.table_name, include_types=True, ) subscription = self.object.subscriptions.filter(user=self.request.user) ctx.update( { "preview_limit": preview_limit, "record_count": total_record_count, "records": records, "is_bookmarked": self.object.user_has_bookmarked(self.request.user), "DATA_GRID_REFERENCE_DATASET_FLAG": settings.DATA_GRID_REFERENCE_DATASET_FLAG, "code_snippets": code_snippets, "columns": columns, "subscription": { "current_user_is_subscribed": subscription.exists() and subscription.first().is_active(), "details": subscription.first(), }, } ) return ctx def _get_context_data_for_visualisation(self, ctx, **kwargs): ctx.update( { "has_access": self.object.user_has_access(self.request.user), "is_bookmarked": self.object.user_has_bookmarked(self.request.user), "visualisation_links": self.object.get_visualisation_links(self.request), "summarised_update_frequency": "N/A", "source_text": self._get_source_text(self.object), } ) return ctx def get_context_data(self, **kwargs): ctx = super().get_context_data() ctx["model"] = self.object ctx["DATA_CUT_ENHANCED_PREVIEW_FLAG"] = settings.DATA_CUT_ENHANCED_PREVIEW_FLAG ctx["DATASET_CHANGELOG_PAGE_FLAG"] = settings.DATASET_CHANGELOG_PAGE_FLAG ctx["DATA_UPLOADER_UI_FLAG"] = settings.DATA_UPLOADER_UI_FLAG if self._is_reference_dataset(): return self._get_context_data_for_reference_dataset(ctx, **kwargs) elif self._is_visualisation(): return self._get_context_data_for_visualisation(ctx, **kwargs) elif self.object.type == DataSetType.MASTER: return self._get_context_data_for_master_dataset(ctx, **kwargs) elif self.object.type == DataSetType.DATACUT: return self._get_context_data_for_datacut_dataset(ctx, **kwargs) raise ValueError(f"Unknown dataset/type for {self.__class__.__name__}: {self.object}") def get_template_names(self): if self._is_reference_dataset(): return ["datasets/referencedataset_detail.html"] elif self.object.type == DataSetType.MASTER: return ["datasets/master_dataset.html"] elif self.object.type == DataSetType.DATACUT: return ["datasets/data_cut_dataset.html"] elif self._is_visualisation(): return ["datasets/visualisation_catalogue_item.html"] raise RuntimeError(f"Unknown template for {self}") def get_preview_limit(self, record_count): return min([record_count, settings.REFERENCE_DATASET_PREVIEW_NUM_OF_ROWS]) @require_http_methods(["GET", "POST"]) def eligibility_criteria_view(request, dataset_uuid): dataset = find_dataset(dataset_uuid, request.user) if request.method == "POST": form = EligibilityCriteriaForm(request.POST) if form.is_valid(): access_request_id = form.cleaned_data.get("access_request") if form.cleaned_data["meet_criteria"]: url = reverse("request_access:dataset", args=[dataset_uuid]) if access_request_id: url = reverse( "request_access:dataset-request-update", args=[access_request_id], ) else: url = reverse("datasets:eligibility_criteria_not_met", args=[dataset_uuid]) return HttpResponseRedirect(url) return render( request, "eligibility_criteria.html", {"dataset": dataset, "access_request": request.GET.get("access_request")}, ) @require_GET def toggle_bookmark(request, dataset_uuid): dataset = find_dataset(dataset_uuid, request.user) dataset.toggle_bookmark(request.user) return HttpResponseRedirect(dataset.get_absolute_url()) class ReferenceDatasetDownloadView(DetailView): model = ReferenceDataset def get_object(self, queryset=None): return find_dataset(self.kwargs["dataset_uuid"], self.request.user, ReferenceDataset) def get(self, request, *args, **kwargs): dl_format = self.kwargs.get("format") if dl_format not in ["json", "csv"]: raise Http404 ref_dataset = self.get_object() records = [] for record in ref_dataset.get_records(): record_data = {} for field in ref_dataset.fields.all(): if field.data_type == ReferenceDatasetField.DATA_TYPE_FOREIGN_KEY: relationship = getattr(record, field.relationship_name) record_data[field.name] = ( getattr( relationship, field.linked_reference_dataset_field.column_name, ) if relationship else None ) else: record_data[field.name] = getattr(record, field.column_name) records.append(record_data) response = HttpResponse() response["Content-Disposition"] = "attachment; filename={}-{}.{}".format( ref_dataset.slug, ref_dataset.published_version, dl_format ) log_event( request.user, EventLog.TYPE_REFERENCE_DATASET_DOWNLOAD, ref_dataset, extra={ "path": request.get_full_path(), "reference_dataset_version": ref_dataset.published_version, "download_format": dl_format, }, ) ref_dataset.number_of_downloads = F("number_of_downloads") + 1 ref_dataset.save(update_fields=["number_of_downloads"]) if dl_format == "json": response["Content-Type"] = "application/json" response.write(json.dumps(list(records), cls=DjangoJSONEncoder)) else: response["Content-Type"] = "text/csv" with closing(io.StringIO()) as outfile: writer = csv.DictWriter( outfile, fieldnames=ref_dataset.export_field_names, quoting=csv.QUOTE_NONNUMERIC, ) writer.writeheader() writer.writerows(records) response.write(outfile.getvalue()) # pylint: disable=no-member return response class SourceLinkDownloadView(DetailView): model = SourceLink def get(self, request, *args, **kwargs): dataset = find_dataset(self.kwargs.get("dataset_uuid"), request.user) if not dataset.user_has_access(self.request.user): return HttpResponseForbidden() source_link = get_object_or_404( SourceLink, id=self.kwargs.get("source_link_id"), dataset=dataset ) log_event( request.user, EventLog.TYPE_DATASET_SOURCE_LINK_DOWNLOAD, source_link.dataset, extra={ "path": request.get_full_path(), **serializers.serialize("python", [source_link])[0], }, ) dataset.number_of_downloads = F("number_of_downloads") + 1 dataset.save(update_fields=["number_of_downloads"]) if source_link.link_type == source_link.TYPE_EXTERNAL: return HttpResponseRedirect(source_link.url) client = get_s3_client() try: file_object = client.get_object( Bucket=settings.AWS_UPLOADS_BUCKET, Key=source_link.url ) except ClientError as ex: try: return HttpResponse(status=ex.response["ResponseMetadata"]["HTTPStatusCode"]) except KeyError: return HttpResponseServerError() response = StreamingHttpResponseWithoutDjangoDbConnection( file_object["Body"].iter_chunks(chunk_size=65536), content_type=file_object["ContentType"], ) response["Content-Disposition"] = f'attachment; filename="{source_link.get_filename()}"' response["Content-Length"] = file_object["ContentLength"] return response class SourceDownloadMixin: pk_url_kwarg = "source_id" event_log_type = None @staticmethod def db_object_exists(db_object): raise NotImplementedError() def get_table_data(self, db_object): raise NotImplementedError() def get(self, request, *_, **__): dataset = find_dataset(self.kwargs.get("dataset_uuid"), request.user) db_object = get_object_or_404(self.model, id=self.kwargs.get("source_id"), dataset=dataset) if not db_object.dataset.user_has_access(self.request.user): return HttpResponseForbidden() if not self.db_object_exists(db_object): return HttpResponseNotFound() log_event( request.user, self.event_log_type, db_object.dataset, extra={ "path": request.get_full_path(), **serializers.serialize("python", [db_object])[0], }, ) dataset.number_of_downloads = F("number_of_downloads") + 1 dataset.save(update_fields=["number_of_downloads"]) return self.get_table_data(db_object) class SourceViewDownloadView(SourceDownloadMixin, DetailView): model = SourceView event_log_type = EventLog.TYPE_DATASET_SOURCE_VIEW_DOWNLOAD @staticmethod def db_object_exists(db_object): return view_exists(db_object.database.memorable_name, db_object.schema, db_object.view) def get_table_data(self, db_object): return table_data( self.request.user.email, db_object.database.memorable_name, db_object.schema, db_object.view, db_object.get_filename(), ) class CustomDatasetQueryDownloadView(DetailView): model = CustomDatasetQuery def get(self, request, *args, **kwargs): dataset = find_dataset(self.kwargs.get("dataset_uuid"), request.user) if not dataset.user_has_access(self.request.user): return HttpResponseForbidden() query = get_object_or_404(self.model, id=self.kwargs.get("query_id"), dataset=dataset) if not query.reviewed and not request.user.is_superuser: return HttpResponseForbidden() log_event( request.user, EventLog.TYPE_DATASET_CUSTOM_QUERY_DOWNLOAD, query.dataset, extra={ "path": request.get_full_path(), **serializers.serialize("python", [query])[0], }, ) dataset.number_of_downloads = F("number_of_downloads") + 1 dataset.save(update_fields=["number_of_downloads"]) filtered_query = sql.SQL(query.query) columns = request.GET.getlist("columns") if columns: trimmed_query = query.query.rstrip().rstrip(";") filtered_query = sql.SQL("SELECT {fields} from ({query}) as data;").format( fields=sql.SQL(",").join([sql.Identifier(column) for column in columns]), query=sql.SQL(trimmed_query), ) return streaming_query_response( request.user.email, query.database.memorable_name, filtered_query, query.get_filename(), cursor_name=f"custom_query--{query.id}", ) class DatasetPreviewView(DetailView, metaclass=ABCMeta): @property @abstractmethod def model(self): pass @abstractmethod def get_preview_data(self, dataset): pass def get(self, request, *args, **kwargs): user = self.request.user dataset = find_dataset(self.kwargs.get("dataset_uuid"), user) if not dataset.user_has_access(user): return HttpResponseForbidden() source_object, columns, query = self.get_preview_data(dataset) records = [] sample_size = settings.DATASET_PREVIEW_NUM_OF_ROWS if columns: rows = get_random_data_sample( source_object.database.memorable_name, sql.SQL(query), sample_size, ) for row in rows: record_data = {} for i, column in enumerate(columns): record_data[column] = row[i] records.append(record_data) can_download = source_object.can_show_link_for_user(user) return render( request, "datasets/dataset_preview.html", { "dataset": dataset, "source_object": source_object, "fields": columns, "records": records, "preview_limit": sample_size, "record_count": len(records), "fixed_table_height_limit": 10, "truncate_limit": 100, "can_download": can_download, "type": source_object.type, }, ) class SourceTablePreviewView(DatasetPreviewView): model = SourceTable def get_preview_data(self, dataset): source_table_object = get_object_or_404( self.model, id=self.kwargs.get("table_uuid"), dataset=dataset ) database_name = source_table_object.database.memorable_name table_name = source_table_object.table schema_name = source_table_object.schema columns = datasets_db.get_columns(database_name, schema=schema_name, table=table_name) preview_query = f""" select * from "{schema_name}"."{table_name}" """ return source_table_object, columns, preview_query class CustomDatasetQueryPreviewView(DatasetPreviewView): model = CustomDatasetQuery def get_preview_data(self, dataset): query_object = get_object_or_404( self.model, id=self.kwargs.get("query_id"), dataset=dataset ) if not query_object.reviewed and not self.request.user.is_superuser: raise PermissionDenied() database_name = query_object.database.memorable_name columns = datasets_db.get_columns(database_name, query=query_object.query) preview_query = query_object.query return query_object, columns, preview_query class SourceTableColumnDetails(View): def get(self, request, dataset_uuid, table_uuid): dataset = find_dataset(dataset_uuid, request.user, MasterDataset) source_table = get_object_or_404(SourceTable, id=table_uuid, dataset=dataset) columns = datasets_db.get_columns( source_table.database.memorable_name, schema=source_table.schema, table=source_table.table, include_types=True, ) return render( request, "datasets/source_table_column_details.html", context={ "dataset": dataset, "source_table": source_table, "columns": columns, }, ) class ReferenceDatasetColumnDetails(View): def get(self, request, dataset_uuid): dataset = find_dataset(dataset_uuid, request.user, ReferenceDataset) columns = datasets_db.get_columns( dataset.external_database.memorable_name, schema="public", table=dataset.table_name, include_types=True, ) return render( request, "datasets/referencedataset_column_details.html", context={"dataset": dataset, "columns": columns}, ) class ReferenceDatasetGridView(View): def get(self, request, dataset_uuid): dataset = find_dataset(dataset_uuid, request.user, ReferenceDataset) return render( request, "datasets/reference_dataset_grid.html", context={"model": dataset}, ) class RelatedDataView(View): def get(self, request, dataset_uuid): dataset = find_dataset(dataset_uuid, request.user) if dataset.type == DataSetType.DATACUT: form = RelatedMastersSortForm(request.GET) elif dataset.type == DataSetType.MASTER: form = RelatedDataCutsSortForm(request.GET) else: return HttpResponse(status=404) if form.is_valid(): related_datasets = dataset.related_datasets( order=form.cleaned_data.get("sort") or form.fields["sort"].initial ) return render( request, "datasets/related_data.html", context={ "dataset": dataset, "related_data": related_datasets, "form": form, }, ) return HttpResponse(status=500) class RelatedVisualisationsView(View): def get(self, request, dataset_uuid): dataset = find_dataset(dataset_uuid, request.user) form = RelatedVisualisationsSortForm(request.GET) if form.is_valid(): related_visualisations = dataset.related_visualisations.order_by( form.cleaned_data.get("sort") or form.fields["sort"].initial ) return render( request, "datasets/related_visualisations.html", context={ "dataset": dataset, "related_visualisations": related_visualisations, "form": form, }, ) return HttpResponse(status=500) class DataCutPreviewView(WaffleFlagMixin, DetailView): waffle_flag = settings.DATA_CUT_ENHANCED_PREVIEW_FLAG template_name = "datasets/data_cut_preview.html" def dispatch(self, request, *args, **kwargs): if not self.get_object().dataset.user_has_access(self.request.user): return HttpResponseForbidden() return super().dispatch(request, *args, **kwargs) def get_object(self, queryset=None): return get_object_or_404(self.kwargs["model_class"], pk=self.kwargs["object_id"]) def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) model = self.get_object() ctx.update( { "can_download": model.can_show_link_for_user(self.request.user), "form_action": model.get_absolute_url(), "can_filter_columns": model.show_column_filter(), "truncate_limit": 100, "fixed_table_height_limit": 10, } ) if model.user_can_preview(self.request.user): columns, records = model.get_preview_data() ctx.update( { "columns": columns, "records": records, "preview_limit": min( [len(records), settings.REFERENCE_DATASET_PREVIEW_NUM_OF_ROWS] ), } ) return ctx class DatasetUsageHistoryView(View): def get(self, request, dataset_uuid, **kwargs): dataset = find_dataset(dataset_uuid, request.user, kwargs["model_class"]) if dataset.type == DataSetType.MASTER: tables = list(dataset.sourcetable_set.values_list("table", flat=True)) return render( request, "datasets/dataset_usage_history.html", context={ "dataset": dataset, "event_description": "Queried", "rows": ToolQueryAuditLogTable.objects.filter(table__in=tables) .annotate(day=TruncDay("audit_log__timestamp")) .annotate(email=F("audit_log__user__email")) .annotate(object=F("table")) .order_by("-day") .values("day", "email", "object") .annotate(count=Count("id"))[:100], }, ) return render( request, "datasets/dataset_usage_history.html", context={ "dataset": dataset, "event_description": "Viewed" if dataset.type == DataSetType.VISUALISATION else "Downloaded", "rows": dataset.events.filter( event_type__in=[ EventLog.TYPE_DATASET_SOURCE_LINK_DOWNLOAD, EventLog.TYPE_DATASET_CUSTOM_QUERY_DOWNLOAD, EventLog.TYPE_VIEW_VISUALISATION_TEMPLATE, EventLog.TYPE_VIEW_SUPERSET_VISUALISATION, EventLog.TYPE_VIEW_QUICKSIGHT_VISUALISATION, ] ) .annotate(day=TruncDay("timestamp")) .annotate(email=F("user__email")) .annotate( object=Func( F("extra"), Value("fields"), Value("name"), function="jsonb_extract_path_text", output_field=CharField(), ), ) .order_by("-day") .values("day", "email", "object") .annotate(count=Count("id"))[:100], }, ) class DataCutSourceDetailView(DetailView): template_name = "datasets/data_cut_source_detail.html" def dispatch(self, request, *args, **kwargs): source = self.get_object() if not source.data_grid_enabled: raise DatasetPreviewDisabledError(source.dataset) if not source.dataset.user_has_access(self.request.user): raise DatasetPermissionDenied(source.dataset) return super().dispatch(request, *args, **kwargs) def get_object(self, queryset=None): dataset = find_dataset(self.kwargs["dataset_uuid"], self.request.user) return get_object_or_404( self.kwargs["model_class"], dataset=dataset, pk=self.kwargs["object_id"], ) class DataGridDataView(DetailView): def _user_can_access(self): source = self.get_object() return source.dataset.user_has_access(self.request.user) and source.data_grid_enabled def get_object(self, queryset=None): dataset = find_dataset(self.kwargs.get("dataset_uuid"), self.request.user) return get_object_or_404( self.kwargs["model_class"], dataset=dataset, pk=self.kwargs["object_id"], ) def dispatch(self, request, *args, **kwargs): if not self._user_can_access(): return HttpResponseForbidden() return super().dispatch(request, *args, **kwargs) @staticmethod def _get_rows(source, query, query_params): with psycopg2.connect( database_dsn(settings.DATABASES_DATA[source.database.memorable_name]) ) as connection: with connection.cursor( name="data-grid-data", cursor_factory=psycopg2.extras.RealDictCursor, ) as cursor: cursor.execute(query, query_params) return cursor.fetchall() def post(self, request, *args, **kwargs): source = self.get_object() if request.GET.get("download"): if not source.data_grid_download_enabled: return JsonResponse({}, status=403) filters = {} for filter_data in [json.loads(x) for x in request.POST.getlist("filters")]: filters.update(filter_data) column_config = [ x for x in source.get_column_config() if x["field"] in request.POST.getlist("columns", []) ] if not column_config: return JsonResponse({}, status=400) post_data = { "filters": filters, "limit": source.data_grid_download_limit, "sortDir": request.POST.get("sortDir", "ASC"), "sortField": request.POST.get("sortField", column_config[0]["field"]), } else: post_data = json.loads(request.body.decode("utf-8")) post_data["limit"] = min(post_data.get("limit", 100), 100) column_config = source.get_column_config() original_query = source.get_data_grid_query() query, params = build_filtered_dataset_query( original_query, column_config, post_data, ) if request.GET.get("download"): extra = { "correlation_id": str(uuid.uuid4()), **serializers.serialize("python", [source])[0], } log_event( request.user, EventLog.TYPE_DATASET_CUSTOM_QUERY_DOWNLOAD, source.dataset, extra=extra, ) def write_metrics_to_eventlog(log_data): logger.debug("write_metrics_to_eventlog %s", log_data) log_data.update(extra) log_event( request.user, EventLog.TYPE_DATASET_CUSTOM_QUERY_DOWNLOAD_COMPLETE, source.dataset, extra=log_data, ) return streaming_query_response( request.user.email, source.database.memorable_name, query, request.POST.get("export_file_name", f"custom-{source.dataset.slug}-export.csv"), params, original_query, write_metrics_to_eventlog, cursor_name=f'data-grid--{self.kwargs["model_class"].__name__}--{source.id}', ) records = self._get_rows(source, query, params) return JsonResponse({"records": records}) class DatasetVisualisationPreview(View): def _get_vega_definition(self, visualisation): vega_definition = json.loads(visualisation.vega_definition_json) if visualisation.query: with psycopg2.connect( database_dsn(settings.DATABASES_DATA[visualisation.database.memorable_name]) ) as connection: with connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cursor: cursor.execute(visualisation.query) data = cursor.fetchall() try: # vega-lite, 'data' is a dictionary vega_definition["data"]["values"] = data except TypeError: # vega, 'data' is a list, and we support setting the query # results as the first item vega_definition["data"][0]["values"] = data return vega_definition def get(self, request, dataset_uuid, object_id, **kwargs): model_class = kwargs["model_class"] dataset = find_dataset(dataset_uuid, request.user, model_class) if not dataset.user_has_access(request.user): return HttpResponseForbidden() visualisation = dataset.visualisations.get(id=object_id) vega_definition = self._get_vega_definition(visualisation) return JsonResponse(vega_definition) class DatasetVisualisationView(View): def get(self, request, dataset_uuid, object_id, **kwargs): model_class = kwargs["model_class"] dataset = find_dataset(dataset_uuid, self.request.user, model_class) if not dataset.user_has_access(request.user): return HttpResponseForbidden() visualisation = dataset.visualisations.live().get(id=object_id) return render( request, "datasets/visualisation.html", context={"dataset_uuid": dataset_uuid, "visualisation": visualisation}, ) class CustomQueryColumnDetails(View): def get(self, request, dataset_uuid, query_id): dataset = find_dataset(dataset_uuid, self.request.user, DataCutDataset) try: query = CustomDatasetQuery.objects.get(id=query_id, dataset__id=dataset_uuid) except CustomDatasetQuery.DoesNotExist: return HttpResponse(status=404) return render( request, "datasets/data_cut_column_details.html", context={ "dataset": dataset, "query": query, "columns": datasets_db.get_columns( query.database.memorable_name, query=query.query, include_types=True ), }, ) class SourceChangelogView(WaffleFlagMixin, DetailView): waffle_flag = settings.DATASET_CHANGELOG_PAGE_FLAG template_name = "datasets/source_changelog.html" context_object_name = "source" def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx["changelog"] = get_detailed_changelog(self.get_object()) return ctx def get_object(self, queryset=None): dataset = find_dataset(self.kwargs["dataset_uuid"], self.request.user) if self.kwargs["model_class"] == ReferenceDataset: return dataset return get_object_or_404( self.kwargs["model_class"], dataset=dataset, pk=self.kwargs["source_id"], ) class DatasetChartView(WaffleFlagMixin, View): waffle_flag = settings.CHART_BUILDER_PUBLISH_CHARTS_FLAG def get_object(self): dataset = find_dataset( self.kwargs["dataset_uuid"], self.request.user, self.kwargs["model_class"] ) return dataset.charts.get(id=self.kwargs["object_id"]) @csp_update(SCRIPT_SRC=["'unsafe-eval'", "blob:"], IMG_SRC=["blob:"]) def get(self, request, **kwargs): chart = self.get_object() if not chart.dataset.user_has_access(request.user): return HttpResponseForbidden() return render( request, "datasets/charts/chart.html", context={ "chart": chart, }, ) class DatasetChartDataView(DatasetChartView): waffle_flag = settings.CHART_BUILDER_PUBLISH_CHARTS_FLAG def get(self, request, **kwargs): dataset_chart = self.get_object() if not dataset_chart.dataset.user_has_access(request.user): return HttpResponseForbidden() chart = dataset_chart.chart return JsonResponse( { "total_rows": chart.query_log.rows, "duration": chart.query_log.duration, "data": chart.get_table_data(chart.get_required_columns()), } ) class EditBaseView(View): obj = None summary: str = None def dispatch(self, request, *args, **kwargs): try: dataset = DataSet.objects.live().get(pk=self.kwargs.get("pk")) except DataSet.DoesNotExist: dataset = None try: visualisation_catalogue_item = VisualisationCatalogueItem.objects.live().get( pk=self.kwargs.get("pk") ) except VisualisationCatalogueItem.DoesNotExist: raise Http404 # pylint: disable=W0707 if "summary_id" in self.kwargs: self.summary = get_object_or_404( PendingAuthorizedUsers.objects.all(), pk=self.kwargs.get("summary_id") ) self.obj = dataset or visualisation_catalogue_item if ( request.user not in [ self.obj.information_asset_owner, self.obj.information_asset_manager, ] and not request.user.is_superuser ): return HttpResponseForbidden() return super().dispatch(request, *args, **kwargs) class DatasetEditView(EditBaseView, UpdateView): model = DataSet form_class = DatasetEditForm template_name = "datasets/edit_dataset.html" def get_success_url(self): return self.object.get_absolute_url() def get_initial(self): return { "enquiries_contact": self.object.enquiries_contact.email if self.object.enquiries_contact else "", "authorized_email_domains": ",".join(self.object.authorized_email_domains), } def form_valid(self, form): if "authorized_email_domains" in form.changed_data: log_permission_change( self.request.user, self.object, EventLog.TYPE_CHANGED_AUTHORIZED_EMAIL_DOMAIN, {"authorized_email_domains": self.object.authorized_email_domains}, f"authorized_email_domains set to {self.object.authorized_email_domains}", ) # As the dataset's access type has changed, clear cached credentials for all # users to ensure they either: # - lose access if it went from REQUIRES_AUTHENTICATION/OPEN to REQUIRES_AUTHORIZATION # - get access if it went from REQUIRES_AUTHORIZATION to REQUIRES_AUTHENTICATION/OPEN invalidate_data_explorer_user_cached_credentials() invalidate_superset_user_cached_credentials() messages.success(self.request, "Dataset updated") return super().form_valid(form) class VisualisationCatalogueItemEditView(EditBaseView, UpdateView): model = VisualisationCatalogueItem form_class = VisualisationCatalogueItemEditForm template_name = "datasets/edit_visualisation_catalogue_item.html" def get_success_url(self): return self.object.get_absolute_url() def get_initial(self): return { "enquiries_contact": self.object.enquiries_contact.email if self.object.enquiries_contact else "", "secondary_enquiries_contact": self.object.secondary_enquiries_contact.email if self.object.secondary_enquiries_contact else "", "authorized_email_domains": ",".join(self.object.authorized_email_domains), } def form_valid(self, form): if "authorized_email_domains" in form.changed_data: log_permission_change( self.request.user, self.object, EventLog.TYPE_CHANGED_AUTHORIZED_EMAIL_DOMAIN, {"authorized_email_domains": self.object.authorized_email_domains}, f"authorized_email_domains set to {self.object.authorized_email_domains}", ) # As the dataset's access type has changed, clear cached credentials for all # users to ensure they either: # - lose access if it went from REQUIRES_AUTHENTICATION/OPEN to REQUIRES_AUTHORIZATION # - get access if it went from REQUIRES_AUTHORIZATION to REQUIRES_AUTHENTICATION/OPEN invalidate_data_explorer_user_cached_credentials() invalidate_superset_user_cached_credentials() messages.success(self.request, "Dataset updated") return super().form_valid(form) class UserSearchFormView(EditBaseView, FormView): form_class = UserSearchForm form: None def form_valid(self, form): self.form = form return super().form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) search_query = self.request.GET.get("search_query") if search_query: email_filter = Q(email__icontains=search_query) name_filter = Q(first_name__icontains=search_query) | Q( last_name__icontains=search_query ) users = get_user_model().objects.filter(Q(email_filter | name_filter)) context["search_results"] = users context["search_query"] = search_query context["obj"] = self.obj context["obj_edit_url"] = ( reverse("datasets:edit_dataset", args=[self.obj.pk]) if isinstance(self.obj, DataSet) else reverse("datasets:edit_visualisation_catalogue_item", args=[self.obj.pk]) ) return context class DatasetEnquiriesContactSearchView(UserSearchFormView): template_name = "datasets/search_enquiries_contact.html" def get_success_url(self): url = ( reverse( "datasets:search_enquiries_contact", args=[ self.obj.pk, ], ) + "?search_query=" + self.form.cleaned_data["search"] ) if self.request.GET.get("secondary_enquiries_contact"): url = ( url + "&secondary_enquiries_contact=" + self.request.GET.get("secondary_enquiries_contact") ) return url class DatasetSecondaryEnquiriesContactSearchView(UserSearchFormView): template_name = "datasets/search_secondary_enquiries_contact.html" def get_success_url(self): url = ( reverse( "datasets:search_secondary_enquiries_contact", args=[ self.obj.pk, ], ) + "?search_query=" + self.form.cleaned_data["search"] ) if self.request.GET.get("enquiries_contact"): url = url + "&enquiries_contact=" + self.request.GET.get("enquiries_contact") return url class DatasetEditPermissionsView(EditBaseView, View): def dispatch(self, request, *args, **kwargs): super().dispatch(request, *args, **kwargs) if isinstance(self.obj, DataSet): permissions = DataSetUserPermission.objects.filter(dataset=self.obj) else: permissions = VisualisationUserPermission.objects.filter(visualisation=self.obj) users = json.dumps([p.user.id for p in permissions]) summary = PendingAuthorizedUsers.objects.create(created_by=request.user, users=users) return HttpResponseRedirect( reverse("datasets:edit_permissions_summary", args=[self.obj.id, summary.id]) ) class DatasetEditPermissionsSummaryView(EditBaseView, TemplateView): template_name = "datasets/edit_permissions_summary.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["obj"] = self.obj context["obj_edit_url"] = ( reverse("datasets:edit_dataset", args=[self.obj.pk]) if isinstance(self.obj, DataSet) else reverse("datasets:edit_visualisation_catalogue_item", args=[self.obj.pk]) ) context["summary"] = self.summary context["authorised_users"] = get_user_model().objects.filter( id__in=json.loads(self.summary.users if self.summary.users else "[]") ) return context def post(self, request, *args, **kwargs): authorized_users = set( get_user_model().objects.filter( id__in=json.loads(self.summary.users if self.summary.users else "[]") ) ) if isinstance(self.obj, DataSet): process_dataset_authorized_users_change( authorized_users, request.user, self.obj, False, False, True ) messages.success(request, "Dataset permissions updated") return HttpResponseRedirect(reverse("datasets:edit_dataset", args=[self.obj.id])) else: process_visualisation_catalogue_item_authorized_users_change( authorized_users, request.user, self.obj, False, False ) messages.success(request, "Visualisation permissions updated") return HttpResponseRedirect( reverse("datasets:edit_visualisation_catalogue_item", args=[self.obj.id]) ) class DatasetAuthorisedUsersSearchView(UserSearchFormView): template_name = "datasets/search_authorised_users.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["summary_id"] = self.kwargs.get("summary_id") return context def get_success_url(self): return ( reverse( "datasets:search_authorized_users", args=[self.obj.pk, self.kwargs.get("summary_id")], ) + "?search_query=" + self.form.cleaned_data["search"] ) class DatasetAddAuthorisedUserView(EditBaseView, View): def get(self, request, *args, **kwargs): summary = PendingAuthorizedUsers.objects.get(id=self.kwargs.get("summary_id")) user = get_user_model().objects.get(id=self.kwargs.get("user_id")) users = json.loads(summary.users if summary.users else "[]") if user.id not in users: users.append(user.id) summary.users = json.dumps(users) summary.save() return HttpResponseRedirect( reverse( "datasets:edit_permissions_summary", args=[ self.obj.id, self.kwargs.get("summary_id"), ], ) ) class DatasetRemoveAuthorisedUserView(EditBaseView, View): def get(self, request, *args, **kwargs): summary = PendingAuthorizedUsers.objects.get(id=self.kwargs.get("summary_id")) user = get_user_model().objects.get(id=self.kwargs.get("user_id")) users = json.loads(summary.users if summary.users else "[]") if user.id in users: summary.users = json.dumps([user_id for user_id in users if user_id != user.id]) summary.save() return HttpResponseRedirect( reverse( "datasets:edit_permissions_summary", args=[ self.obj.id, self.kwargs.get("summary_id"), ], ) ) class SelectChartSourceView(WaffleFlagMixin, FormView): waffle_flag = settings.CHART_BUILDER_BUILD_CHARTS_FLAG form_class = ChartSourceSelectForm template_name = "datasets/charts/select_chart_source.html" def get_object(self, queryset=None): dataset = find_dataset(self.kwargs["pk"], self.request.user, DataSet) if not dataset.user_has_access(self.request.user): raise DatasetPermissionDenied(dataset) return dataset def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx["dataset"] = self.get_object() return ctx def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["dataset"] = self.get_object() return kwargs def form_valid(self, form): dataset = self.get_object() source_id = form.cleaned_data["source"] source = dataset.get_related_source(source_id) if source is None: raise Http404 chart = ChartBuilderChart.objects.create_from_source(source, self.request.user) run_chart_builder_query.delay(chart.id) if source.data_grid_enabled: return HttpResponseRedirect( reverse("datasets:filter_chart_data", args=(dataset.id, source.id)) ) return HttpResponseRedirect(f"{chart.get_edit_url()}?prev={self.request.path}") class FilterChartDataView(WaffleFlagMixin, DetailView): waffle_flag = settings.CHART_BUILDER_BUILD_CHARTS_FLAG form_class = ChartSourceSelectForm template_name = "datasets/charts/filter_chart_data.html" context_object_name = "source" def get_object(self, queryset=None): dataset = find_dataset(self.kwargs["pk"], self.request.user, DataSet) if not dataset.user_has_access(self.request.user): raise DatasetPermissionDenied(dataset) source = dataset.get_related_source(self.kwargs["source_id"]) if source is None: raise Http404 return source class CreateGridChartView(WaffleFlagMixin, View): waffle_flag = settings.CHART_BUILDER_BUILD_CHARTS_FLAG def post(self, request, dataset_uuid, source_id, *args, **kwargs): dataset = find_dataset(dataset_uuid, self.request.user) source = dataset.get_related_source(source_id) if source is None: raise Http404 filters = {} for filter_data in [json.loads(x) for x in request.POST.getlist("filters")]: filters.update(filter_data) column_config = [ x for x in source.get_column_config() if x["field"] in request.POST.getlist("columns", []) ] post_data = { "filters": filters, "sortDir": request.POST.get("sortDir", "ASC"), "sortField": request.POST.get("sortField", column_config[0]["field"]), } original_query = source.get_data_grid_query() query, params = build_filtered_dataset_query( original_query, column_config, post_data, ) db_name = list(settings.DATABASES_DATA.items())[0][0] with connections[db_name].cursor() as cursor: full_query = cursor.mogrify(query, params).decode() chart = ChartBuilderChart.objects.create_from_sql(str(full_query), request.user, db_name) run_chart_builder_query.delay(chart.id) return HttpResponseRedirect( f"{chart.get_edit_url()}?prev={request.META.get('HTTP_REFERER')}" ) class DatasetChartsView(WaffleFlagMixin, View): waffle_flag = settings.CHART_BUILDER_PUBLISH_CHARTS_FLAG @csp_update(SCRIPT_SRC=["'unsafe-eval'", "blob:"]) def get(self, request, **kwargs): dataset = find_dataset(self.kwargs["dataset_uuid"], self.request.user, DataSet) if not dataset.user_has_access(self.request.user): return HttpResponseForbidden() return render( self.request, "datasets/charts/charts.html", context={"charts": dataset.related_charts(), "dataset": dataset}, ) def find_data_dictionary_view(request, schema_name, table_name): query = SourceTable.objects.filter(schema=schema_name, table=table_name) if not query.exists(): raise Http404 return redirect("datasets:data_dictionary", source_uuid=query.first().id) class DataDictionaryBaseView(View): def get_dictionary(self, source_table): columns = datasets_db.get_columns( source_table.database.memorable_name, schema=source_table.schema, table=source_table.table, include_types=True, ) fields = source_table.field_definitions.all() dictionary = [] for name, data_type in columns: definition = "" if fields.filter(field=name).exists(): definition = fields.filter(field=name).first() dictionary.append( ( name, data_type, definition, ) ) return columns, fields, dictionary class DataDictionaryView(DataDictionaryBaseView): def get(self, request, source_uuid): source_table = get_object_or_404(SourceTable, pk=source_uuid) dataset = None if request.GET.get("dataset_uuid"): dataset = find_dataset(request.GET.get("dataset_uuid"), self.request.user, DataSet) columns, fields, dictionary = self.get_dictionary(source_table) return render( request, "datasets/data_dictionary.html", context={ "source_table": source_table, "dataset": dataset, "columns": columns, "fields": fields, "dictionary": dictionary, }, ) class DataDictionaryEditView(DataDictionaryBaseView): def dispatch(self, request, *args, **kwargs): dataset = DataSet.objects.live().get(pk=self.kwargs.get("dataset_uuid")) if ( request.user not in [ dataset.information_asset_owner, dataset.information_asset_manager, ] and not request.user.is_superuser ): return HttpResponseForbidden() return super().dispatch(request, *args, **kwargs) def get(self, request, dataset_uuid, source_uuid): source_table = get_object_or_404(SourceTable, pk=source_uuid) dataset = find_dataset(dataset_uuid, self.request.user, DataSet) columns, fields, dictionary = self.get_dictionary(source_table) return render( request, "datasets/edit_data_dictionary.html", context={ "source_table": source_table, "dataset": dataset, "columns": columns, "fields": fields, "dictionary": dictionary, }, ) def post(self, request, dataset_uuid, source_uuid): source_table = get_object_or_404(SourceTable, pk=source_uuid) dataset = find_dataset(dataset_uuid, self.request.user, DataSet) for name, value in request.POST.items(): if name == "csrfmiddlewaretoken": continue field, _ = SourceTableFieldDefinition.objects.get_or_create( source_table=source_table, field=name ) field.description = value[:1024] field.save() messages.success(self.request, "Changes saved successfully") redirect_url = ( reverse("datasets:data_dictionary", args=[source_table.id]) + "?dataset_uuid=" + str(dataset.id) ) return redirect(redirect_url)
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import click import pickle import re import copy import numpy as np import torch import dnnlib from torch_utils import misc #---------------------------------------------------------------------------- def load_network_pkl(f, force_fp16=False): data = _LegacyUnpickler(f).load() # Legacy TensorFlow pickle => convert. if isinstance(data, tuple) and len(data) == 3 and all(isinstance(net, _TFNetworkStub) for net in data): tf_G, tf_D, tf_Gs = data G = convert_tf_generator(tf_G) D = convert_tf_discriminator(tf_D) G_ema = convert_tf_generator(tf_Gs) data = dict(G=G, D=D, G_ema=G_ema) # Add missing fields. if 'training_set_kwargs' not in data: data['training_set_kwargs'] = None if 'augment_pipe' not in data: data['augment_pipe'] = None # Validate contents. assert isinstance(data['G'], torch.nn.Module) assert isinstance(data['D'], torch.nn.Module) assert isinstance(data['G_ema'], torch.nn.Module) assert isinstance(data['training_set_kwargs'], (dict, type(None))) assert isinstance(data['augment_pipe'], (torch.nn.Module, type(None))) # Force FP16. if force_fp16: for key in ['G', 'D', 'G_ema']: old = data[key] kwargs = copy.deepcopy(old.init_kwargs) if key.startswith('G'): kwargs.synthesis_kwargs = dnnlib.EasyDict(kwargs.get('synthesis_kwargs', {})) kwargs.synthesis_kwargs.num_fp16_res = 4 kwargs.synthesis_kwargs.conv_clamp = 256 if key.startswith('D'): kwargs.num_fp16_res = 4 kwargs.conv_clamp = 256 if kwargs != old.init_kwargs: new = type(old)(**kwargs).eval().requires_grad_(False) misc.copy_params_and_buffers(old, new, require_all=True) data[key] = new return data #---------------------------------------------------------------------------- class _TFNetworkStub(dnnlib.EasyDict): pass class _LegacyUnpickler(pickle.Unpickler): def find_class(self, module, name): if module == 'dnnlib.tflib.network' and name == 'Network': return _TFNetworkStub return super().find_class(module, name) #---------------------------------------------------------------------------- def _collect_tf_params(tf_net): # pylint: disable=protected-access tf_params = dict() def recurse(prefix, tf_net): for name, value in tf_net.variables: tf_params[prefix + name] = value for name, comp in tf_net.components.items(): recurse(prefix + name + '/', comp) recurse('', tf_net) return tf_params #---------------------------------------------------------------------------- def _populate_module_params(module, *patterns): for name, tensor in misc.named_params_and_buffers(module): found = False value = None for pattern, value_fn in zip(patterns[0::2], patterns[1::2]): match = re.fullmatch(pattern, name) if match: found = True if value_fn is not None: value = value_fn(*match.groups()) break try: assert found if value is not None: tensor.copy_(torch.from_numpy(np.array(value))) except: print(name, list(tensor.shape)) raise #---------------------------------------------------------------------------- def convert_tf_generator(tf_G): if tf_G.version < 4: raise ValueError('TensorFlow pickle version too low') # Collect kwargs. tf_kwargs = tf_G.static_kwargs known_kwargs = set() def kwarg(tf_name, default=None, none=None): known_kwargs.add(tf_name) val = tf_kwargs.get(tf_name, default) return val if val is not None else none # Convert kwargs. kwargs = dnnlib.EasyDict( z_dim = kwarg('latent_size', 1024), c_dim = kwarg('label_size', 0), w_dim = kwarg('dlatent_size', 1024), img_resolution = kwarg('resolution', 1024), img_channels = kwarg('num_channels', 3), mapping_kwargs = dnnlib.EasyDict( num_layers = kwarg('mapping_layers', 4), embed_features = kwarg('label_fmaps', None), layer_features = kwarg('mapping_fmaps', None), activation = kwarg('mapping_nonlinearity', 'lrelu'), lr_multiplier = kwarg('mapping_lrmul', 0.01), w_avg_beta = kwarg('w_avg_beta', 0.995, none=1), ), synthesis_kwargs = dnnlib.EasyDict( channel_base = kwarg('fmap_base', 32768) * 2, channel_max = kwarg('fmap_max', 1024), num_fp16_res = kwarg('num_fp16_res', 0), conv_clamp = kwarg('conv_clamp', None), architecture = kwarg('architecture', 'skip'), resample_filter = kwarg('resample_kernel', [1,3,3,1]), use_noise = kwarg('use_noise', True), activation = kwarg('nonlinearity', 'lrelu'), ), ) # Check for unknown kwargs. kwarg('truncation_psi') kwarg('truncation_cutoff') kwarg('style_mixing_prob') kwarg('structure') kwarg('resolution_h') kwarg('resolution_w') unknown_kwargs = list(set(tf_kwargs.keys()) - known_kwargs) if len(unknown_kwargs) > 0: raise ValueError('Unknown TensorFlow kwarg', unknown_kwargs[0]) # Collect params. tf_params = _collect_tf_params(tf_G) for name, value in list(tf_params.items()): match = re.fullmatch(r'ToRGB_lod(\d+)/(.*)', name) if match: r = kwargs.img_resolution // (2 ** int(match.group(1))) tf_params[f'{r}x{r}/ToRGB/{match.group(2)}'] = value kwargs.synthesis.kwargs.architecture = 'orig' #for name, value in tf_params.items(): print(f'{name:<50s}{list(value.shape)}') # Convert params. from training import networks G = networks.Generator(**kwargs).eval().requires_grad_(False) # pylint: disable=unnecessary-lambda _populate_module_params(G, r'mapping\.w_avg', lambda: tf_params[f'dlatent_avg'], r'mapping\.embed\.weight', lambda: tf_params[f'mapping/LabelEmbed/weight'].transpose(), r'mapping\.embed\.bias', lambda: tf_params[f'mapping/LabelEmbed/bias'], r'mapping\.fc(\d+)\.weight', lambda i: tf_params[f'mapping/Dense{i}/weight'].transpose(), r'mapping\.fc(\d+)\.bias', lambda i: tf_params[f'mapping/Dense{i}/bias'], r'synthesis\.b4\.const', lambda: tf_params[f'synthesis/4x4/Const/const'][0], r'synthesis\.b4\.conv1\.weight', lambda: tf_params[f'synthesis/4x4/Conv/weight'].transpose(3, 2, 0, 1), r'synthesis\.b4\.conv1\.bias', lambda: tf_params[f'synthesis/4x4/Conv/bias'], r'synthesis\.b4\.conv1\.noise_const', lambda: tf_params[f'synthesis/noise0'][0, 0], r'synthesis\.b4\.conv1\.noise_strength', lambda: tf_params[f'synthesis/4x4/Conv/noise_strength'], r'synthesis\.b4\.conv1\.affine\.weight', lambda: tf_params[f'synthesis/4x4/Conv/mod_weight'].transpose(), r'synthesis\.b4\.conv1\.affine\.bias', lambda: tf_params[f'synthesis/4x4/Conv/mod_bias'] + 1, r'synthesis\.b(\d+)\.conv0\.weight', lambda r: tf_params[f'synthesis/{r}x{r}/Conv0_up/weight'][::-1, ::-1].transpose(3, 2, 0, 1), r'synthesis\.b(\d+)\.conv0\.bias', lambda r: tf_params[f'synthesis/{r}x{r}/Conv0_up/bias'], r'synthesis\.b(\d+)\.conv0\.noise_const', lambda r: tf_params[f'synthesis/noise{int(np.log2(int(r)))*2-5}'][0, 0], r'synthesis\.b(\d+)\.conv0\.noise_strength', lambda r: tf_params[f'synthesis/{r}x{r}/Conv0_up/noise_strength'], r'synthesis\.b(\d+)\.conv0\.affine\.weight', lambda r: tf_params[f'synthesis/{r}x{r}/Conv0_up/mod_weight'].transpose(), r'synthesis\.b(\d+)\.conv0\.affine\.bias', lambda r: tf_params[f'synthesis/{r}x{r}/Conv0_up/mod_bias'] + 1, r'synthesis\.b(\d+)\.conv1\.weight', lambda r: tf_params[f'synthesis/{r}x{r}/Conv1/weight'].transpose(3, 2, 0, 1), r'synthesis\.b(\d+)\.conv1\.bias', lambda r: tf_params[f'synthesis/{r}x{r}/Conv1/bias'], r'synthesis\.b(\d+)\.conv1\.noise_const', lambda r: tf_params[f'synthesis/noise{int(np.log2(int(r)))*2-4}'][0, 0], r'synthesis\.b(\d+)\.conv1\.noise_strength', lambda r: tf_params[f'synthesis/{r}x{r}/Conv1/noise_strength'], r'synthesis\.b(\d+)\.conv1\.affine\.weight', lambda r: tf_params[f'synthesis/{r}x{r}/Conv1/mod_weight'].transpose(), r'synthesis\.b(\d+)\.conv1\.affine\.bias', lambda r: tf_params[f'synthesis/{r}x{r}/Conv1/mod_bias'] + 1, r'synthesis\.b(\d+)\.torgb\.weight', lambda r: tf_params[f'synthesis/{r}x{r}/ToRGB/weight'].transpose(3, 2, 0, 1), r'synthesis\.b(\d+)\.torgb\.bias', lambda r: tf_params[f'synthesis/{r}x{r}/ToRGB/bias'], r'synthesis\.b(\d+)\.torgb\.affine\.weight', lambda r: tf_params[f'synthesis/{r}x{r}/ToRGB/mod_weight'].transpose(), r'synthesis\.b(\d+)\.torgb\.affine\.bias', lambda r: tf_params[f'synthesis/{r}x{r}/ToRGB/mod_bias'] + 1, r'synthesis\.b(\d+)\.skip\.weight', lambda r: tf_params[f'synthesis/{r}x{r}/Skip/weight'][::-1, ::-1].transpose(3, 2, 0, 1), r'.*\.resample_filter', None, ) return G #---------------------------------------------------------------------------- def convert_tf_discriminator(tf_D): if tf_D.version < 4: raise ValueError('TensorFlow pickle version too low') # Collect kwargs. tf_kwargs = tf_D.static_kwargs known_kwargs = set() def kwarg(tf_name, default=None): known_kwargs.add(tf_name) return tf_kwargs.get(tf_name, default) # Convert kwargs. kwargs = dnnlib.EasyDict( c_dim = kwarg('label_size', 0), img_resolution = kwarg('resolution', 1024), img_channels = kwarg('num_channels', 3), architecture = kwarg('architecture', 'resnet'), channel_base = kwarg('fmap_base', 16384) * 2, channel_max = kwarg('fmap_max', 512), num_fp16_res = kwarg('num_fp16_res', 0), conv_clamp = kwarg('conv_clamp', None), cmap_dim = kwarg('mapping_fmaps', None), block_kwargs = dnnlib.EasyDict( activation = kwarg('nonlinearity', 'lrelu'), resample_filter = kwarg('resample_kernel', [1,3,3,1]), freeze_layers = kwarg('freeze_layers', 0), ), mapping_kwargs = dnnlib.EasyDict( num_layers = kwarg('mapping_layers', 0), embed_features = kwarg('mapping_fmaps', None), layer_features = kwarg('mapping_fmaps', None), activation = kwarg('nonlinearity', 'lrelu'), lr_multiplier = kwarg('mapping_lrmul', 0.1), ), epilogue_kwargs = dnnlib.EasyDict( mbstd_group_size = kwarg('mbstd_group_size', 32), mbstd_num_channels = kwarg('mbstd_num_features', 4), activation = kwarg('nonlinearity', 'lrelu'), ), ) # Check for unknown kwargs. kwarg('structure') kwarg('resolution_h') kwarg('resolution_w') unknown_kwargs = list(set(tf_kwargs.keys()) - known_kwargs) if len(unknown_kwargs) > 0: raise ValueError('Unknown TensorFlow kwarg', unknown_kwargs[0]) # Collect params. tf_params = _collect_tf_params(tf_D) for name, value in list(tf_params.items()): match = re.fullmatch(r'FromRGB_lod(\d+)/(.*)', name) if match: r = kwargs.img_resolution // (2 ** int(match.group(1))) tf_params[f'{r}x{r}/FromRGB/{match.group(2)}'] = value kwargs.architecture = 'orig' #for name, value in tf_params.items(): print(f'{name:<50s}{list(value.shape)}') # Convert params. from training import networks D = networks.Discriminator(**kwargs).eval().requires_grad_(False) # pylint: disable=unnecessary-lambda _populate_module_params(D, r'b(\d+)\.fromrgb\.weight', lambda r: tf_params[f'{r}x{r}/FromRGB/weight'].transpose(3, 2, 0, 1), r'b(\d+)\.fromrgb\.bias', lambda r: tf_params[f'{r}x{r}/FromRGB/bias'], r'b(\d+)\.conv(\d+)\.weight', lambda r, i: tf_params[f'{r}x{r}/Conv{i}{['','_down'][int(i)]}/weight'].transpose(3, 2, 0, 1), r'b(\d+)\.conv(\d+)\.bias', lambda r, i: tf_params[f'{r}x{r}/Conv{i}{['','_down'][int(i)]}/bias'], r'b(\d+)\.skip\.weight', lambda r: tf_params[f'{r}x{r}/Skip/weight'].transpose(3, 2, 0, 1), r'mapping\.embed\.weight', lambda: tf_params[f'LabelEmbed/weight'].transpose(), r'mapping\.embed\.bias', lambda: tf_params[f'LabelEmbed/bias'], r'mapping\.fc(\d+)\.weight', lambda i: tf_params[f'Mapping{i}/weight'].transpose(), r'mapping\.fc(\d+)\.bias', lambda i: tf_params[f'Mapping{i}/bias'], r'b4\.conv\.weight', lambda: tf_params[f'4x4/Conv/weight'].transpose(3, 2, 0, 1), r'b4\.conv\.bias', lambda: tf_params[f'4x4/Conv/bias'], r'b4\.fc\.weight', lambda: tf_params[f'4x4/Dense0/weight'].transpose(), r'b4\.fc\.bias', lambda: tf_params[f'4x4/Dense0/bias'], r'b4\.out\.weight', lambda: tf_params[f'Output/weight'].transpose(), r'b4\.out\.bias', lambda: tf_params[f'Output/bias'], r'.*\.resample_filter', None, ) return D #---------------------------------------------------------------------------- @click.command() @click.option('--source', help='Input pickle', required=True, metavar='PATH') @click.option('--dest', help='Output pickle', required=True, metavar='PATH') @click.option('--force-fp16', help='Force the networks to use FP16', type=bool, default=False, metavar='BOOL', show_default=True) def convert_network_pickle(source, dest, force_fp16): """Convert legacy network pickle into the native PyTorch format. The tool is able to load the main network configurations exported using the TensorFlow version of StyleGAN2 or StyleGAN2-ADA. It does not support e.g. StyleGAN2-ADA comparison methods, StyleGAN2 configs A-D, or StyleGAN1 networks. Example: \b python legacy.py \\ --source=https://nvlabs-fi-cdn.nvidia.com/stylegan2/networks/stylegan2-cat-config-f.pkl \\ --dest=stylegan2-cat-config-f.pkl """ print(f'Loading "{source}"...') with dnnlib.util.open_url(source) as f: data = load_network_pkl(f, force_fp16=force_fp16) print(f'Saving "{dest}"...') with open(dest, 'wb') as f: pickle.dump(data, f) print('Done.') #---------------------------------------------------------------------------- if __name__ == "__main__": convert_network_pickle() # pylint: disable=no-value-for-parameter #----------------------------------------------------------------------------
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import click import pickle import re import copy import numpy as np import torch import dnnlib from torch_utils import misc #---------------------------------------------------------------------------- def load_network_pkl(f, force_fp16=False): data = _LegacyUnpickler(f).load() # Legacy TensorFlow pickle => convert. if isinstance(data, tuple) and len(data) == 3 and all(isinstance(net, _TFNetworkStub) for net in data): tf_G, tf_D, tf_Gs = data G = convert_tf_generator(tf_G) D = convert_tf_discriminator(tf_D) G_ema = convert_tf_generator(tf_Gs) data = dict(G=G, D=D, G_ema=G_ema) # Add missing fields. if 'training_set_kwargs' not in data: data['training_set_kwargs'] = None if 'augment_pipe' not in data: data['augment_pipe'] = None # Validate contents. assert isinstance(data['G'], torch.nn.Module) assert isinstance(data['D'], torch.nn.Module) assert isinstance(data['G_ema'], torch.nn.Module) assert isinstance(data['training_set_kwargs'], (dict, type(None))) assert isinstance(data['augment_pipe'], (torch.nn.Module, type(None))) # Force FP16. if force_fp16: for key in ['G', 'D', 'G_ema']: old = data[key] kwargs = copy.deepcopy(old.init_kwargs) if key.startswith('G'): kwargs.synthesis_kwargs = dnnlib.EasyDict(kwargs.get('synthesis_kwargs', {})) kwargs.synthesis_kwargs.num_fp16_res = 4 kwargs.synthesis_kwargs.conv_clamp = 256 if key.startswith('D'): kwargs.num_fp16_res = 4 kwargs.conv_clamp = 256 if kwargs != old.init_kwargs: new = type(old)(**kwargs).eval().requires_grad_(False) misc.copy_params_and_buffers(old, new, require_all=True) data[key] = new return data #---------------------------------------------------------------------------- class _TFNetworkStub(dnnlib.EasyDict): pass class _LegacyUnpickler(pickle.Unpickler): def find_class(self, module, name): if module == 'dnnlib.tflib.network' and name == 'Network': return _TFNetworkStub return super().find_class(module, name) #---------------------------------------------------------------------------- def _collect_tf_params(tf_net): # pylint: disable=protected-access tf_params = dict() def recurse(prefix, tf_net): for name, value in tf_net.variables: tf_params[prefix + name] = value for name, comp in tf_net.components.items(): recurse(prefix + name + '/', comp) recurse('', tf_net) return tf_params #---------------------------------------------------------------------------- def _populate_module_params(module, *patterns): for name, tensor in misc.named_params_and_buffers(module): found = False value = None for pattern, value_fn in zip(patterns[0::2], patterns[1::2]): match = re.fullmatch(pattern, name) if match: found = True if value_fn is not None: value = value_fn(*match.groups()) break try: assert found if value is not None: tensor.copy_(torch.from_numpy(np.array(value))) except: print(name, list(tensor.shape)) raise #---------------------------------------------------------------------------- def convert_tf_generator(tf_G): if tf_G.version < 4: raise ValueError('TensorFlow pickle version too low') # Collect kwargs. tf_kwargs = tf_G.static_kwargs known_kwargs = set() def kwarg(tf_name, default=None, none=None): known_kwargs.add(tf_name) val = tf_kwargs.get(tf_name, default) return val if val is not None else none # Convert kwargs. kwargs = dnnlib.EasyDict( z_dim = kwarg('latent_size', 1024), c_dim = kwarg('label_size', 0), w_dim = kwarg('dlatent_size', 1024), img_resolution = kwarg('resolution', 1024), img_channels = kwarg('num_channels', 3), mapping_kwargs = dnnlib.EasyDict( num_layers = kwarg('mapping_layers', 4), embed_features = kwarg('label_fmaps', None), layer_features = kwarg('mapping_fmaps', None), activation = kwarg('mapping_nonlinearity', 'lrelu'), lr_multiplier = kwarg('mapping_lrmul', 0.01), w_avg_beta = kwarg('w_avg_beta', 0.995, none=1), ), synthesis_kwargs = dnnlib.EasyDict( channel_base = kwarg('fmap_base', 32768) * 2, channel_max = kwarg('fmap_max', 1024), num_fp16_res = kwarg('num_fp16_res', 0), conv_clamp = kwarg('conv_clamp', None), architecture = kwarg('architecture', 'skip'), resample_filter = kwarg('resample_kernel', [1,3,3,1]), use_noise = kwarg('use_noise', True), activation = kwarg('nonlinearity', 'lrelu'), ), ) # Check for unknown kwargs. kwarg('truncation_psi') kwarg('truncation_cutoff') kwarg('style_mixing_prob') kwarg('structure') kwarg('resolution_h') kwarg('resolution_w') unknown_kwargs = list(set(tf_kwargs.keys()) - known_kwargs) if len(unknown_kwargs) > 0: raise ValueError('Unknown TensorFlow kwarg', unknown_kwargs[0]) # Collect params. tf_params = _collect_tf_params(tf_G) for name, value in list(tf_params.items()): match = re.fullmatch(r'ToRGB_lod(\d+)/(.*)', name) if match: r = kwargs.img_resolution // (2 ** int(match.group(1))) tf_params[f'{r}x{r}/ToRGB/{match.group(2)}'] = value kwargs.synthesis.kwargs.architecture = 'orig' #for name, value in tf_params.items(): print(f'{name:<50s}{list(value.shape)}') # Convert params. from training import networks G = networks.Generator(**kwargs).eval().requires_grad_(False) # pylint: disable=unnecessary-lambda _populate_module_params(G, r'mapping\.w_avg', lambda: tf_params[f'dlatent_avg'], r'mapping\.embed\.weight', lambda: tf_params[f'mapping/LabelEmbed/weight'].transpose(), r'mapping\.embed\.bias', lambda: tf_params[f'mapping/LabelEmbed/bias'], r'mapping\.fc(\d+)\.weight', lambda i: tf_params[f'mapping/Dense{i}/weight'].transpose(), r'mapping\.fc(\d+)\.bias', lambda i: tf_params[f'mapping/Dense{i}/bias'], r'synthesis\.b4\.const', lambda: tf_params[f'synthesis/4x4/Const/const'][0], r'synthesis\.b4\.conv1\.weight', lambda: tf_params[f'synthesis/4x4/Conv/weight'].transpose(3, 2, 0, 1), r'synthesis\.b4\.conv1\.bias', lambda: tf_params[f'synthesis/4x4/Conv/bias'], r'synthesis\.b4\.conv1\.noise_const', lambda: tf_params[f'synthesis/noise0'][0, 0], r'synthesis\.b4\.conv1\.noise_strength', lambda: tf_params[f'synthesis/4x4/Conv/noise_strength'], r'synthesis\.b4\.conv1\.affine\.weight', lambda: tf_params[f'synthesis/4x4/Conv/mod_weight'].transpose(), r'synthesis\.b4\.conv1\.affine\.bias', lambda: tf_params[f'synthesis/4x4/Conv/mod_bias'] + 1, r'synthesis\.b(\d+)\.conv0\.weight', lambda r: tf_params[f'synthesis/{r}x{r}/Conv0_up/weight'][::-1, ::-1].transpose(3, 2, 0, 1), r'synthesis\.b(\d+)\.conv0\.bias', lambda r: tf_params[f'synthesis/{r}x{r}/Conv0_up/bias'], r'synthesis\.b(\d+)\.conv0\.noise_const', lambda r: tf_params[f'synthesis/noise{int(np.log2(int(r)))*2-5}'][0, 0], r'synthesis\.b(\d+)\.conv0\.noise_strength', lambda r: tf_params[f'synthesis/{r}x{r}/Conv0_up/noise_strength'], r'synthesis\.b(\d+)\.conv0\.affine\.weight', lambda r: tf_params[f'synthesis/{r}x{r}/Conv0_up/mod_weight'].transpose(), r'synthesis\.b(\d+)\.conv0\.affine\.bias', lambda r: tf_params[f'synthesis/{r}x{r}/Conv0_up/mod_bias'] + 1, r'synthesis\.b(\d+)\.conv1\.weight', lambda r: tf_params[f'synthesis/{r}x{r}/Conv1/weight'].transpose(3, 2, 0, 1), r'synthesis\.b(\d+)\.conv1\.bias', lambda r: tf_params[f'synthesis/{r}x{r}/Conv1/bias'], r'synthesis\.b(\d+)\.conv1\.noise_const', lambda r: tf_params[f'synthesis/noise{int(np.log2(int(r)))*2-4}'][0, 0], r'synthesis\.b(\d+)\.conv1\.noise_strength', lambda r: tf_params[f'synthesis/{r}x{r}/Conv1/noise_strength'], r'synthesis\.b(\d+)\.conv1\.affine\.weight', lambda r: tf_params[f'synthesis/{r}x{r}/Conv1/mod_weight'].transpose(), r'synthesis\.b(\d+)\.conv1\.affine\.bias', lambda r: tf_params[f'synthesis/{r}x{r}/Conv1/mod_bias'] + 1, r'synthesis\.b(\d+)\.torgb\.weight', lambda r: tf_params[f'synthesis/{r}x{r}/ToRGB/weight'].transpose(3, 2, 0, 1), r'synthesis\.b(\d+)\.torgb\.bias', lambda r: tf_params[f'synthesis/{r}x{r}/ToRGB/bias'], r'synthesis\.b(\d+)\.torgb\.affine\.weight', lambda r: tf_params[f'synthesis/{r}x{r}/ToRGB/mod_weight'].transpose(), r'synthesis\.b(\d+)\.torgb\.affine\.bias', lambda r: tf_params[f'synthesis/{r}x{r}/ToRGB/mod_bias'] + 1, r'synthesis\.b(\d+)\.skip\.weight', lambda r: tf_params[f'synthesis/{r}x{r}/Skip/weight'][::-1, ::-1].transpose(3, 2, 0, 1), r'.*\.resample_filter', None, ) return G #---------------------------------------------------------------------------- def convert_tf_discriminator(tf_D): if tf_D.version < 4: raise ValueError('TensorFlow pickle version too low') # Collect kwargs. tf_kwargs = tf_D.static_kwargs known_kwargs = set() def kwarg(tf_name, default=None): known_kwargs.add(tf_name) return tf_kwargs.get(tf_name, default) # Convert kwargs. kwargs = dnnlib.EasyDict( c_dim = kwarg('label_size', 0), img_resolution = kwarg('resolution', 1024), img_channels = kwarg('num_channels', 3), architecture = kwarg('architecture', 'resnet'), channel_base = kwarg('fmap_base', 16384) * 2, channel_max = kwarg('fmap_max', 512), num_fp16_res = kwarg('num_fp16_res', 0), conv_clamp = kwarg('conv_clamp', None), cmap_dim = kwarg('mapping_fmaps', None), block_kwargs = dnnlib.EasyDict( activation = kwarg('nonlinearity', 'lrelu'), resample_filter = kwarg('resample_kernel', [1,3,3,1]), freeze_layers = kwarg('freeze_layers', 0), ), mapping_kwargs = dnnlib.EasyDict( num_layers = kwarg('mapping_layers', 0), embed_features = kwarg('mapping_fmaps', None), layer_features = kwarg('mapping_fmaps', None), activation = kwarg('nonlinearity', 'lrelu'), lr_multiplier = kwarg('mapping_lrmul', 0.1), ), epilogue_kwargs = dnnlib.EasyDict( mbstd_group_size = kwarg('mbstd_group_size', 32), mbstd_num_channels = kwarg('mbstd_num_features', 4), activation = kwarg('nonlinearity', 'lrelu'), ), ) # Check for unknown kwargs. kwarg('structure') kwarg('resolution_h') kwarg('resolution_w') unknown_kwargs = list(set(tf_kwargs.keys()) - known_kwargs) if len(unknown_kwargs) > 0: raise ValueError('Unknown TensorFlow kwarg', unknown_kwargs[0]) # Collect params. tf_params = _collect_tf_params(tf_D) for name, value in list(tf_params.items()): match = re.fullmatch(r'FromRGB_lod(\d+)/(.*)', name) if match: r = kwargs.img_resolution // (2 ** int(match.group(1))) tf_params[f'{r}x{r}/FromRGB/{match.group(2)}'] = value kwargs.architecture = 'orig' #for name, value in tf_params.items(): print(f'{name:<50s}{list(value.shape)}') # Convert params. from training import networks D = networks.Discriminator(**kwargs).eval().requires_grad_(False) # pylint: disable=unnecessary-lambda _populate_module_params(D, r'b(\d+)\.fromrgb\.weight', lambda r: tf_params[f'{r}x{r}/FromRGB/weight'].transpose(3, 2, 0, 1), r'b(\d+)\.fromrgb\.bias', lambda r: tf_params[f'{r}x{r}/FromRGB/bias'], r'b(\d+)\.conv(\d+)\.weight', lambda r, i: tf_params[f'{r}x{r}/Conv{i}{["","_down"][int(i)]}/weight'].transpose(3, 2, 0, 1), r'b(\d+)\.conv(\d+)\.bias', lambda r, i: tf_params[f'{r}x{r}/Conv{i}{["","_down"][int(i)]}/bias'], r'b(\d+)\.skip\.weight', lambda r: tf_params[f'{r}x{r}/Skip/weight'].transpose(3, 2, 0, 1), r'mapping\.embed\.weight', lambda: tf_params[f'LabelEmbed/weight'].transpose(), r'mapping\.embed\.bias', lambda: tf_params[f'LabelEmbed/bias'], r'mapping\.fc(\d+)\.weight', lambda i: tf_params[f'Mapping{i}/weight'].transpose(), r'mapping\.fc(\d+)\.bias', lambda i: tf_params[f'Mapping{i}/bias'], r'b4\.conv\.weight', lambda: tf_params[f'4x4/Conv/weight'].transpose(3, 2, 0, 1), r'b4\.conv\.bias', lambda: tf_params[f'4x4/Conv/bias'], r'b4\.fc\.weight', lambda: tf_params[f'4x4/Dense0/weight'].transpose(), r'b4\.fc\.bias', lambda: tf_params[f'4x4/Dense0/bias'], r'b4\.out\.weight', lambda: tf_params[f'Output/weight'].transpose(), r'b4\.out\.bias', lambda: tf_params[f'Output/bias'], r'.*\.resample_filter', None, ) return D #---------------------------------------------------------------------------- @click.command() @click.option('--source', help='Input pickle', required=True, metavar='PATH') @click.option('--dest', help='Output pickle', required=True, metavar='PATH') @click.option('--force-fp16', help='Force the networks to use FP16', type=bool, default=False, metavar='BOOL', show_default=True) def convert_network_pickle(source, dest, force_fp16): """Convert legacy network pickle into the native PyTorch format. The tool is able to load the main network configurations exported using the TensorFlow version of StyleGAN2 or StyleGAN2-ADA. It does not support e.g. StyleGAN2-ADA comparison methods, StyleGAN2 configs A-D, or StyleGAN1 networks. Example: \b python legacy.py \\ --source=https://nvlabs-fi-cdn.nvidia.com/stylegan2/networks/stylegan2-cat-config-f.pkl \\ --dest=stylegan2-cat-config-f.pkl """ print(f'Loading "{source}"...') with dnnlib.util.open_url(source) as f: data = load_network_pkl(f, force_fp16=force_fp16) print(f'Saving "{dest}"...') with open(dest, 'wb') as f: pickle.dump(data, f) print('Done.') #---------------------------------------------------------------------------- if __name__ == "__main__": convert_network_pickle() # pylint: disable=no-value-for-parameter #----------------------------------------------------------------------------
""" Crie um programa que leia nome e duas notas de vários alunos e guarte tudo em uma lista composta. No final, mostre um boletim contendo a média de cada um e permita que o usuário possa mostrar as notas de cada aluno individualmente.""" lista_main = [] while True: nome = str(input('Nome: ')) nota1 = float(input('nota 1: ')) nota2 = float(input('Nota 2: ')) media = nota1 + nota2 / 2 lista_main.append([nome, [nota1, nota2], media]) resp = str(input('Quer continuar?[S/N] ')) if resp in 'Nn': break print('-'*22) print(f'{'nª':<4}{'nome':<10}{'média':>8}') print('-'*22) for indice, aluno in enumerate(lista_main): print(f'{indice:<4}{aluno[0]:<10}{aluno[2]:>8.1f}') while True: print('-'*30) opc = int(input('Mostrar notas de qual aluno? (digite "999" para finalizar)')) if opc == 999: print('FINALIZANDO...') break if opc <= len(lista_main) - 1: print(f'Notas de {lista_main[opc][0]} são {lista_main[opc][1]}')
""" Crie um programa que leia nome e duas notas de vários alunos e guarte tudo em uma lista composta. No final, mostre um boletim contendo a média de cada um e permita que o usuário possa mostrar as notas de cada aluno individualmente.""" lista_main = [] while True: nome = str(input('Nome: ')) nota1 = float(input('nota 1: ')) nota2 = float(input('Nota 2: ')) media = nota1 + nota2 / 2 lista_main.append([nome, [nota1, nota2], media]) resp = str(input('Quer continuar?[S/N] ')) if resp in 'Nn': break print('-'*22) print(f'{"nª":<4}{"nome":<10}{"média":>8}') print('-'*22) for indice, aluno in enumerate(lista_main): print(f'{indice:<4}{aluno[0]:<10}{aluno[2]:>8.1f}') while True: print('-'*30) opc = int(input('Mostrar notas de qual aluno? (digite "999" para finalizar)')) if opc == 999: print('FINALIZANDO...') break if opc <= len(lista_main) - 1: print(f'Notas de {lista_main[opc][0]} são {lista_main[opc][1]}')
# -*- coding=utf-8 -*- import datetime import pathlib import os import re import sys import invoke from parver import Version from towncrier._builder import ( find_fragments, render_fragments, split_fragments ) from towncrier._settings import load_config from pipenv.__version__ import __version__ from pipenv.vendor.vistir.contextmanagers import temp_environ from .vendoring import _get_git_root, drop_dir VERSION_FILE = 'pipenv/__version__.py' ROOT = pathlib.Path(".").parent.parent.absolute() PACKAGE_NAME = "pipenv" def log(msg): print('[release] %s' % msg) def get_version_file(ctx): return _get_git_root(ctx).joinpath(VERSION_FILE) def find_version(ctx): version_file = get_version_file(ctx).read_text() version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.") def get_history_file(ctx): return _get_git_root(ctx).joinpath('HISTORY.txt') def get_dist_dir(ctx): return _get_git_root(ctx) / 'dist' def get_build_dir(ctx): return _get_git_root(ctx) / 'build' def _render_log(): """Totally tap into Towncrier internals to get an in-memory result. """ config = load_config(ROOT) definitions = config['types'] fragments, fragment_filenames = find_fragments( pathlib.Path(config['directory']).absolute(), config['sections'], None, definitions, ) rendered = render_fragments( pathlib.Path(config['template']).read_text(encoding='utf-8'), config['issue_format'], split_fragments(fragments, definitions), definitions, config['underlines'][1:], False, # Don't add newlines to wrapped text. ) return rendered @invoke.task def release(ctx, dry_run=False): drop_dist_dirs(ctx) bump_version(ctx, dry_run=dry_run) version = find_version(ctx) tag_content = _render_log() if dry_run: ctx.run('towncrier --draft > CHANGELOG.draft.rst') log('would remove: news/*') log('would remove: CHANGELOG.draft.rst') log(f'Would commit with message: "Release v{version}"') else: ctx.run('towncrier') ctx.run("git add CHANGELOG.rst news/") ctx.run("git rm CHANGELOG.draft.rst") ctx.run(f'git commit -m "Release v{version}"') tag_content = tag_content.replace('"', '\\"') if dry_run: log(f"Generated tag content: {tag_content}") markdown = ctx.run("pandoc CHANGELOG.draft.rst -f rst -t markdown", hide=True).stdout.strip() content = clean_mdchangelog(ctx, markdown) log(f"would generate markdown: {content}") else: generate_markdown(ctx) clean_mdchangelog(ctx) ctx.run(f'git tag -a v{version} -m "Version v{version}\n\n{tag_content}"') build_dists(ctx) if dry_run: dist_pattern = f'{PACKAGE_NAME.replace('-', '[-_]')}-*' artifacts = list(ROOT.joinpath('dist').glob(dist_pattern)) filename_display = '\n'.join(f' {a}' for a in artifacts) log(f"Would upload dists: {filename_display}") else: upload_dists(ctx) bump_version(ctx, dev=True) def drop_dist_dirs(ctx): log('Dropping Dist dir...') drop_dir(get_dist_dir(ctx)) log('Dropping build dir...') drop_dir(get_build_dir(ctx)) @invoke.task def build_dists(ctx): drop_dist_dirs(ctx) for py_version in ['3.6', '2.7']: env = {'PIPENV_PYTHON': py_version} with ctx.cd(ROOT.as_posix()), temp_environ(): executable = ctx.run("python -c 'import sys; print(sys.executable)'", hide=True).stdout.strip() log('Building sdist using %s ....' % executable) os.environ["PIPENV_PYTHON"] = py_version ctx.run('pipenv install --dev', env=env) ctx.run('pipenv run pip install -e . --upgrade --upgrade-strategy=eager', env=env) log('Building wheel using python %s ....' % py_version) if py_version == '3.6': ctx.run('pipenv run python setup.py sdist bdist_wheel', env=env) else: ctx.run('pipenv run python setup.py bdist_wheel', env=env) @invoke.task(build_dists) def upload_dists(ctx, repo="pypi"): dist_pattern = f'{PACKAGE_NAME.replace('-', '[-_]')}-*' artifacts = list(ROOT.joinpath('dist').glob(dist_pattern)) filename_display = '\n'.join(f' {a}' for a in artifacts) print(f'[release] Will upload:\n{filename_display}') try: input('[release] Release ready. ENTER to upload, CTRL-C to abort: ') except KeyboardInterrupt: print('\nAborted!') return arg_display = ' '.join(f'"{n}"' for n in artifacts) ctx.run(f'twine upload --repository="{repo}" {arg_display}') @invoke.task def generate_markdown(ctx): log('Generating markdown from changelog...') ctx.run('pandoc CHANGELOG.rst -f rst -t markdown -o CHANGELOG.md') @invoke.task def generate_changelog(ctx, commit=False, draft=False): log('Generating changelog...') if draft: commit = False log('Writing draft to file...') ctx.run('towncrier --draft > CHANGELOG.draft.rst') else: ctx.run('towncrier') if commit: log('Committing...') ctx.run('git add CHANGELOG.rst') ctx.run('git rm CHANGELOG.draft.rst') ctx.run('git commit -m "Update changelog."') @invoke.task def clean_mdchangelog(ctx, content=None): changelog = None if not content: changelog = _get_git_root(ctx) / "CHANGELOG.md" content = changelog.read_text() content = re.sub(r"([^\n]+)\n?\s+\[[\\]+(#\d+)\]\(https://github\.com/pypa/[\w\-]+/issues/\d+\)", r"\1 \2", content, flags=re.MULTILINE) if changelog: changelog.write_text(content) else: return content @invoke.task def tag_version(ctx, push=False): version = find_version(ctx) version = Version.parse(version) log('Tagging revision: v%s' % version.normalize()) ctx.run('git tag v%s' % version.normalize()) if push: log('Pushing tags...') ctx.run('git push origin master') ctx.run('git push --tags') @invoke.task def bump_version(ctx, dry_run=False, dev=False, pre=False, tag=None, commit=False): current_version = Version.parse(__version__) today = datetime.date.today() tomorrow = today + datetime.timedelta(days=1) next_month = datetime.date.today().replace(month=today.month+1, day=1) next_year = datetime.date.today().replace(year=today.year+1, month=1, day=1) if pre and not tag: print('Using "pre" requires a corresponding tag.') return if not (dev or pre or tag): new_version = current_version.replace(release=today.timetuple()[:3]).clear(pre=True, dev=True) if pre and dev: raise RuntimeError("Can't use 'pre' and 'dev' together!") if dev or pre: new_version = current_version.replace(release=tomorrow.timetuple()[:3]).clear(pre=True, dev=True) if dev: new_version = new_version.bump_dev() else: new_version = new_version.bump_pre(tag=tag) log('Updating version to %s' % new_version.normalize()) version = find_version(ctx) log('Found current version: %s' % version) if dry_run: log('Would update to: %s' % new_version.normalize()) else: log('Updating to: %s' % new_version.normalize()) version_file = get_version_file(ctx) file_contents = version_file.read_text() version_file.write_text(file_contents.replace(version, str(new_version.normalize()))) if commit: ctx.run('git add {0}'.format(version_file.as_posix())) log('Committing...') ctx.run('git commit -s -m "Bumped version."')
# -*- coding=utf-8 -*- import datetime import pathlib import os import re import sys import invoke from parver import Version from towncrier._builder import ( find_fragments, render_fragments, split_fragments ) from towncrier._settings import load_config from pipenv.__version__ import __version__ from pipenv.vendor.vistir.contextmanagers import temp_environ from .vendoring import _get_git_root, drop_dir VERSION_FILE = 'pipenv/__version__.py' ROOT = pathlib.Path(".").parent.parent.absolute() PACKAGE_NAME = "pipenv" def log(msg): print('[release] %s' % msg) def get_version_file(ctx): return _get_git_root(ctx).joinpath(VERSION_FILE) def find_version(ctx): version_file = get_version_file(ctx).read_text() version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.") def get_history_file(ctx): return _get_git_root(ctx).joinpath('HISTORY.txt') def get_dist_dir(ctx): return _get_git_root(ctx) / 'dist' def get_build_dir(ctx): return _get_git_root(ctx) / 'build' def _render_log(): """Totally tap into Towncrier internals to get an in-memory result. """ config = load_config(ROOT) definitions = config['types'] fragments, fragment_filenames = find_fragments( pathlib.Path(config['directory']).absolute(), config['sections'], None, definitions, ) rendered = render_fragments( pathlib.Path(config['template']).read_text(encoding='utf-8'), config['issue_format'], split_fragments(fragments, definitions), definitions, config['underlines'][1:], False, # Don't add newlines to wrapped text. ) return rendered @invoke.task def release(ctx, dry_run=False): drop_dist_dirs(ctx) bump_version(ctx, dry_run=dry_run) version = find_version(ctx) tag_content = _render_log() if dry_run: ctx.run('towncrier --draft > CHANGELOG.draft.rst') log('would remove: news/*') log('would remove: CHANGELOG.draft.rst') log(f'Would commit with message: "Release v{version}"') else: ctx.run('towncrier') ctx.run("git add CHANGELOG.rst news/") ctx.run("git rm CHANGELOG.draft.rst") ctx.run(f'git commit -m "Release v{version}"') tag_content = tag_content.replace('"', '\\"') if dry_run: log(f"Generated tag content: {tag_content}") markdown = ctx.run("pandoc CHANGELOG.draft.rst -f rst -t markdown", hide=True).stdout.strip() content = clean_mdchangelog(ctx, markdown) log(f"would generate markdown: {content}") else: generate_markdown(ctx) clean_mdchangelog(ctx) ctx.run(f'git tag -a v{version} -m "Version v{version}\n\n{tag_content}"') build_dists(ctx) if dry_run: dist_pattern = f'{PACKAGE_NAME.replace("-", "[-_]")}-*' artifacts = list(ROOT.joinpath('dist').glob(dist_pattern)) filename_display = '\n'.join(f' {a}' for a in artifacts) log(f"Would upload dists: {filename_display}") else: upload_dists(ctx) bump_version(ctx, dev=True) def drop_dist_dirs(ctx): log('Dropping Dist dir...') drop_dir(get_dist_dir(ctx)) log('Dropping build dir...') drop_dir(get_build_dir(ctx)) @invoke.task def build_dists(ctx): drop_dist_dirs(ctx) for py_version in ['3.6', '2.7']: env = {'PIPENV_PYTHON': py_version} with ctx.cd(ROOT.as_posix()), temp_environ(): executable = ctx.run("python -c 'import sys; print(sys.executable)'", hide=True).stdout.strip() log('Building sdist using %s ....' % executable) os.environ["PIPENV_PYTHON"] = py_version ctx.run('pipenv install --dev', env=env) ctx.run('pipenv run pip install -e . --upgrade --upgrade-strategy=eager', env=env) log('Building wheel using python %s ....' % py_version) if py_version == '3.6': ctx.run('pipenv run python setup.py sdist bdist_wheel', env=env) else: ctx.run('pipenv run python setup.py bdist_wheel', env=env) @invoke.task(build_dists) def upload_dists(ctx, repo="pypi"): dist_pattern = f'{PACKAGE_NAME.replace("-", "[-_]")}-*' artifacts = list(ROOT.joinpath('dist').glob(dist_pattern)) filename_display = '\n'.join(f' {a}' for a in artifacts) print(f'[release] Will upload:\n{filename_display}') try: input('[release] Release ready. ENTER to upload, CTRL-C to abort: ') except KeyboardInterrupt: print('\nAborted!') return arg_display = ' '.join(f'"{n}"' for n in artifacts) ctx.run(f'twine upload --repository="{repo}" {arg_display}') @invoke.task def generate_markdown(ctx): log('Generating markdown from changelog...') ctx.run('pandoc CHANGELOG.rst -f rst -t markdown -o CHANGELOG.md') @invoke.task def generate_changelog(ctx, commit=False, draft=False): log('Generating changelog...') if draft: commit = False log('Writing draft to file...') ctx.run('towncrier --draft > CHANGELOG.draft.rst') else: ctx.run('towncrier') if commit: log('Committing...') ctx.run('git add CHANGELOG.rst') ctx.run('git rm CHANGELOG.draft.rst') ctx.run('git commit -m "Update changelog."') @invoke.task def clean_mdchangelog(ctx, content=None): changelog = None if not content: changelog = _get_git_root(ctx) / "CHANGELOG.md" content = changelog.read_text() content = re.sub(r"([^\n]+)\n?\s+\[[\\]+(#\d+)\]\(https://github\.com/pypa/[\w\-]+/issues/\d+\)", r"\1 \2", content, flags=re.MULTILINE) if changelog: changelog.write_text(content) else: return content @invoke.task def tag_version(ctx, push=False): version = find_version(ctx) version = Version.parse(version) log('Tagging revision: v%s' % version.normalize()) ctx.run('git tag v%s' % version.normalize()) if push: log('Pushing tags...') ctx.run('git push origin master') ctx.run('git push --tags') @invoke.task def bump_version(ctx, dry_run=False, dev=False, pre=False, tag=None, commit=False): current_version = Version.parse(__version__) today = datetime.date.today() tomorrow = today + datetime.timedelta(days=1) next_month = datetime.date.today().replace(month=today.month+1, day=1) next_year = datetime.date.today().replace(year=today.year+1, month=1, day=1) if pre and not tag: print('Using "pre" requires a corresponding tag.') return if not (dev or pre or tag): new_version = current_version.replace(release=today.timetuple()[:3]).clear(pre=True, dev=True) if pre and dev: raise RuntimeError("Can't use 'pre' and 'dev' together!") if dev or pre: new_version = current_version.replace(release=tomorrow.timetuple()[:3]).clear(pre=True, dev=True) if dev: new_version = new_version.bump_dev() else: new_version = new_version.bump_pre(tag=tag) log('Updating version to %s' % new_version.normalize()) version = find_version(ctx) log('Found current version: %s' % version) if dry_run: log('Would update to: %s' % new_version.normalize()) else: log('Updating to: %s' % new_version.normalize()) version_file = get_version_file(ctx) file_contents = version_file.read_text() version_file.write_text(file_contents.replace(version, str(new_version.normalize()))) if commit: ctx.run('git add {0}'.format(version_file.as_posix())) log('Committing...') ctx.run('git commit -s -m "Bumped version."')
from aioify import aioify from discord.ext import commands, tasks import aiohttp import aiosqlite import asyncio import discord import json import os import shutil class Events(commands.Cog): def __init__(self, bot): self.bot = bot self.os = aioify(os, name='os') self.shutil = aioify(shutil, name='shutil') self.utils = self.bot.get_cog('Utils') self.auto_clean_db.start() self.signing_party_detection.start() self.auto_invalid_device_check.start() @tasks.loop() async def auto_clean_db(self) -> None: async with aiosqlite.connect('Data/autotss.db') as db, db.execute('SELECT devices from autotss') as cursor: data = await cursor.fetchall() for user_devices in data: devices = json.loads(user_devices[0]) if devices == list(): async with aiosqlite.connect('Data/autotss.db') as db: await db.execute('DELETE FROM autotss WHERE devices = ?', (user_devices[0],)) await db.commit() await asyncio.sleep(300) @auto_clean_db.before_loop async def before_auto_clean_db(self) -> None: await self.bot.wait_until_ready() await asyncio.sleep(3) # If first run, give on_ready() some time to create the database @tasks.loop() async def signing_party_detection(self) -> None: async with aiohttp.ClientSession() as session: async with session.get('https://api.ipsw.me/v4/devices') as resp: devices = await resp.json() devices = [d for d in devices if any(x in d['identifier'] for x in ('iPhone', 'AppleTV', 'iPod', 'iPad'))] api = dict() for device in [d['identifier'] for d in devices]: api[device] = await self.utils.get_firms(session, device) try: self._api except AttributeError: self._api = api return for device in self._api.keys(): for firm in [x for x in self._api[device] if x['signed'] == False]: if any(new_firm['signed'] == True for new_firm in api[device] if new_firm['buildid'] == firm['buildid']): print(f"[SIGN] Detected resigned firmware for: {device}, iOS {firm["version"]}") await self.utils.update_auto_saver_frequency(60) # Set blob saver frequency to 1 minute tss = self.bot.get_cog('TSS') # Get TSS class tss.blobs_loop = False tss.auto_blob_saver.cancel() # Restart auto blob saver await asyncio.sleep(1) await self.utils.update_device_count() tss.auto_blob_saver.start() await asyncio.sleep(600) # Wait 10 minutes await self.utils.update_auto_saver_frequency() # Set blob saver frequency back to 3 hours tss.auto_blob_saver.cancel() # Restart auto blob saver await asyncio.sleep(1) tss.auto_blob_saver.start() return else: self._api[device] = api[device] await asyncio.sleep(30) @signing_party_detection.before_loop async def before_signing_party_detection(self) -> None: await self.bot.wait_until_ready() await asyncio.sleep(3) # If first run, give on_ready() some time to create the database @tasks.loop() async def auto_invalid_device_check(self) -> None: # If any users are saving SHSH blobs for A12+ devices without using custom apnonces, attempt to DM them saying they need to re-add the device async with aiosqlite.connect('Data/autotss.db') as db, db.execute('SELECT * FROM autotss') as cursor: data = await cursor.fetchall() if len(data) == 0: return invalid_devices = dict() async with aiohttp.ClientSession() as session: for userinfo in data: userid = userinfo[0] devices = json.loads(userinfo[1]) invalid_devices[userid] = list() for device in devices: cpid = await self.utils.get_cpid(session, device['identifier'], device['boardconfig']) if (device['apnonce'] is not None) and (await self.utils.check_apnonce(cpid, device['apnonce']) == False): invalid_devices[userid].append(device) continue if (device['generator'] is not None) and (await self.utils.check_generator(device['generator']) == False): invalid_devices[userid].append(device) continue if (32800 <= cpid < 35072) and (device['apnonce'] is None): invalid_devices[userid].append(device) for userid in [x for x in invalid_devices.keys() if len(invalid_devices[x]) > 0]: embed = discord.Embed(title='Hey!') msg = ( 'One or more of your devices were added incorrectly to AutoTSS, and are saving **invalid SHSH blobs**.', 'Due to this, they have been removed from AutoTSS so they are no longer continuing to save invalid SHSH blobs.' 'To fix this, please re-add the following devices to AutoTSS:' ) embed.description = '\n'.join(msg) for device in invalid_devices[userid]: device_info = [ f"Device Identifier: `{device["identifier"]}`", f"ECID: `{device["ecid"]}`", f"Boardconfig: `{device["boardconfig"]}`" ] if device['generator'] is not None: device_info.insert(-1, f"Custom generator: `{device["generator"]}`") if device['apnonce'] is not None: device_info.insert(-1, f"Custom ApNonce: `{device["apnonce"]}`") embed.add_field(name=f"**{device["name"]}**", value='\n'.join(device_info)) user = await self.bot.fetch_user(userid) try: await user.send(embed=embed) except: pass async with aiosqlite.connect('Data/autotss.db') as db: for device in invalid_devices[userid]: await self.shutil.rmtree(f"Data/Blobs/{device["ecid"]}") async with db.execute('SELECT devices FROM autotss WHERE user = ?', (userid,)) as cursor: devices = json.loads((await cursor.fetchone())[0]) devices.pop(next(devices.index(x) for x in devices if x['ecid'] == device['ecid'])) await db.execute('UPDATE autotss SET devices = ? WHERE user = ?', (json.dumps(devices), userid)) await db.commit() await asyncio.sleep(259200) @auto_invalid_device_check.before_loop async def before_invalid_device_check(self) -> None: await self.bot.wait_until_ready() await asyncio.sleep(3) # If first run, give on_ready() some time to create the database @commands.Cog.listener() async def on_guild_join(self, guild: discord.Guild) -> None: await self.bot.wait_until_ready() async with aiosqlite.connect('Data/autotss.db') as db: async with db.execute('SELECT prefix from prefix WHERE guild = ?', (guild.id,)) as cursor: if await cursor.fetchone() is not None: await db.execute('DELETE from prefix where guild = ?', (guild.id,)) await db.commit() await db.execute('INSERT INTO prefix(guild, prefix) VALUES(?,?)', (guild.id, 'b!')) await db.commit() embed = await self.utils.info_embed('b!', self.bot.user) for channel in guild.text_channels: try: await channel.send(embed=embed) break except: pass @commands.Cog.listener() async def on_guild_remove(self, guild: discord.Guild) -> None: await self.bot.wait_until_ready() async with aiosqlite.connect('Data/autotss.db') as db: await db.execute('DELETE from prefix where guild = ?', (guild.id,)) await db.commit() @commands.Cog.listener() async def on_member_join(self, member: discord.Member) -> None: await self.bot.wait_until_ready() async with aiosqlite.connect('Data/autotss.db') as db, db.execute('SELECT * from autotss WHERE user = ?', (member.id,)) as cursor: data = await cursor.fetchone() if data is None: return async with aiosqlite.connect('Data/autotss.db') as db: await db.execute('UPDATE autotss SET enabled = ? WHERE user = ?', (True, member.id)) await db.commit() await self.utils.update_device_count() @commands.Cog.listener() async def on_member_remove(self, member: discord.Member) -> None: await self.bot.wait_until_ready() async with aiosqlite.connect('Data/autotss.db') as db, db.execute('SELECT * from autotss WHERE user = ?', (member.id,)) as cursor: data = await cursor.fetchone() if data is None: return if len(member.mutual_guilds) == 0: async with aiosqlite.connect('Data/autotss.db') as db: await db.execute('UPDATE autotss SET enabled = ? WHERE user = ?', (False, member.id)) await db.commit() await self.utils.update_device_count() @commands.Cog.listener() async def on_message(self, message: discord.Message) -> None: await self.bot.wait_until_ready() if message.channel.type == discord.ChannelType.private: return if message.content.replace(' ', '').replace('!', '') == self.bot.user.mention: whitelist = await self.utils.get_whitelist(message.guild.id) if (whitelist is not None) and (whitelist.id != message.channel.id): return prefix = await self.utils.get_prefix(message.guild.id) embed = discord.Embed(title='AutoTSS', description=f'My prefix is `{prefix}`. To see all of my commands, run `{prefix}help`.') embed.set_footer(text=message.author.name, icon_url=message.author.avatar_url_as(static_format='png')) try: await message.reply(embed=embed) except: pass @commands.Cog.listener() async def on_ready(self) -> None: await self.os.makedirs('Data', exist_ok=True) async with aiosqlite.connect('Data/autotss.db') as db: await db.execute(''' CREATE TABLE IF NOT EXISTS autotss( user INTEGER, devices JSON, enabled BOOLEAN ) ''') await db.commit() await db.execute(''' CREATE TABLE IF NOT EXISTS prefix( guild INTEGER, prefix TEXT ) ''') await db.commit() await db.execute(''' CREATE TABLE IF NOT EXISTS whitelist( guild INTEGER, channel INTEGER, enabled BOOLEAN ) ''') await db.commit() await db.execute(''' CREATE TABLE IF NOT EXISTS auto_frequency( time INTEGER ) ''') await db.commit() await self.utils.update_device_count() await self.utils.update_auto_saver_frequency() print('AutoTSS is now online.') @commands.Cog.listener() async def on_command_error(self, ctx: commands.Context, error) -> None: await self.bot.wait_until_ready() embed = discord.Embed(title='Error') if ctx.message.channel.type == discord.ChannelType.private: embed.description = 'AutoTSS cannot be used in DMs. Please use AutoTSS in a Discord server.' await ctx.reply(embed=embed) return if await self.utils.whitelist_check(ctx) != True: return prefix = await self.utils.get_prefix(ctx.guild.id) if isinstance(error, commands.CommandNotFound): if ctx.prefix.replace('!', '').replace(' ', '') == self.bot.user.mention: return embed.description = f"That command doesn't exist! Use `{prefix}help` to see all the commands I can run." await ctx.reply(embed=embed) elif isinstance(error, commands.MaxConcurrencyReached): embed.description = f"`{prefix + ctx.command.qualified_name}` cannot be ran more than once at the same time!" await ctx.reply(embed=embed) elif isinstance(error, commands.errors.CommandInvokeError): if isinstance(error.original, discord.errors.Forbidden): embed.description = f"I don't have the proper permissions to run correctly! \ Please ping an Administrator and tell them to kick & re-invite me using \ [this]({self.utils.invite}) link to fix this issue." message_sent = False for channel in ctx.guild.text_channels: try: await channel.send(embed=embed) message_sent = True break except: pass if message_sent: return try: embed.description = f"I don't have the proper permissions to run correctly! \ Please kick me from `{ctx.guild.name}` & re-invite me using \ [this]({self.utils.invite}) link to fix this issue." await ctx.guild.owner.send(embed=embed) except: # We can't tell the user to tell an admin to fix our permissions, we can't DM the owner to fix it, we might as well leave. await ctx.guild.leave() else: raise error elif isinstance(error, commands.ChannelNotFound): embed = discord.Embed(title='Error', description='That channel does not exist.') await ctx.reply(embed=embed) elif (isinstance(error, commands.errors.NotOwner)) or \ (isinstance(error, commands.MissingPermissions)): return else: raise error def setup(bot): bot.add_cog(Events(bot))
from aioify import aioify from discord.ext import commands, tasks import aiohttp import aiosqlite import asyncio import discord import json import os import shutil class Events(commands.Cog): def __init__(self, bot): self.bot = bot self.os = aioify(os, name='os') self.shutil = aioify(shutil, name='shutil') self.utils = self.bot.get_cog('Utils') self.auto_clean_db.start() self.signing_party_detection.start() self.auto_invalid_device_check.start() @tasks.loop() async def auto_clean_db(self) -> None: async with aiosqlite.connect('Data/autotss.db') as db, db.execute('SELECT devices from autotss') as cursor: data = await cursor.fetchall() for user_devices in data: devices = json.loads(user_devices[0]) if devices == list(): async with aiosqlite.connect('Data/autotss.db') as db: await db.execute('DELETE FROM autotss WHERE devices = ?', (user_devices[0],)) await db.commit() await asyncio.sleep(300) @auto_clean_db.before_loop async def before_auto_clean_db(self) -> None: await self.bot.wait_until_ready() await asyncio.sleep(3) # If first run, give on_ready() some time to create the database @tasks.loop() async def signing_party_detection(self) -> None: async with aiohttp.ClientSession() as session: async with session.get('https://api.ipsw.me/v4/devices') as resp: devices = await resp.json() devices = [d for d in devices if any(x in d['identifier'] for x in ('iPhone', 'AppleTV', 'iPod', 'iPad'))] api = dict() for device in [d['identifier'] for d in devices]: api[device] = await self.utils.get_firms(session, device) try: self._api except AttributeError: self._api = api return for device in self._api.keys(): for firm in [x for x in self._api[device] if x['signed'] == False]: if any(new_firm['signed'] == True for new_firm in api[device] if new_firm['buildid'] == firm['buildid']): print(f"[SIGN] Detected resigned firmware for: {device}, iOS {firm['version']}") await self.utils.update_auto_saver_frequency(60) # Set blob saver frequency to 1 minute tss = self.bot.get_cog('TSS') # Get TSS class tss.blobs_loop = False tss.auto_blob_saver.cancel() # Restart auto blob saver await asyncio.sleep(1) await self.utils.update_device_count() tss.auto_blob_saver.start() await asyncio.sleep(600) # Wait 10 minutes await self.utils.update_auto_saver_frequency() # Set blob saver frequency back to 3 hours tss.auto_blob_saver.cancel() # Restart auto blob saver await asyncio.sleep(1) tss.auto_blob_saver.start() return else: self._api[device] = api[device] await asyncio.sleep(30) @signing_party_detection.before_loop async def before_signing_party_detection(self) -> None: await self.bot.wait_until_ready() await asyncio.sleep(3) # If first run, give on_ready() some time to create the database @tasks.loop() async def auto_invalid_device_check(self) -> None: # If any users are saving SHSH blobs for A12+ devices without using custom apnonces, attempt to DM them saying they need to re-add the device async with aiosqlite.connect('Data/autotss.db') as db, db.execute('SELECT * FROM autotss') as cursor: data = await cursor.fetchall() if len(data) == 0: return invalid_devices = dict() async with aiohttp.ClientSession() as session: for userinfo in data: userid = userinfo[0] devices = json.loads(userinfo[1]) invalid_devices[userid] = list() for device in devices: cpid = await self.utils.get_cpid(session, device['identifier'], device['boardconfig']) if (device['apnonce'] is not None) and (await self.utils.check_apnonce(cpid, device['apnonce']) == False): invalid_devices[userid].append(device) continue if (device['generator'] is not None) and (await self.utils.check_generator(device['generator']) == False): invalid_devices[userid].append(device) continue if (32800 <= cpid < 35072) and (device['apnonce'] is None): invalid_devices[userid].append(device) for userid in [x for x in invalid_devices.keys() if len(invalid_devices[x]) > 0]: embed = discord.Embed(title='Hey!') msg = ( 'One or more of your devices were added incorrectly to AutoTSS, and are saving **invalid SHSH blobs**.', 'Due to this, they have been removed from AutoTSS so they are no longer continuing to save invalid SHSH blobs.' 'To fix this, please re-add the following devices to AutoTSS:' ) embed.description = '\n'.join(msg) for device in invalid_devices[userid]: device_info = [ f"Device Identifier: `{device['identifier']}`", f"ECID: `{device['ecid']}`", f"Boardconfig: `{device['boardconfig']}`" ] if device['generator'] is not None: device_info.insert(-1, f"Custom generator: `{device['generator']}`") if device['apnonce'] is not None: device_info.insert(-1, f"Custom ApNonce: `{device['apnonce']}`") embed.add_field(name=f"**{device['name']}**", value='\n'.join(device_info)) user = await self.bot.fetch_user(userid) try: await user.send(embed=embed) except: pass async with aiosqlite.connect('Data/autotss.db') as db: for device in invalid_devices[userid]: await self.shutil.rmtree(f"Data/Blobs/{device['ecid']}") async with db.execute('SELECT devices FROM autotss WHERE user = ?', (userid,)) as cursor: devices = json.loads((await cursor.fetchone())[0]) devices.pop(next(devices.index(x) for x in devices if x['ecid'] == device['ecid'])) await db.execute('UPDATE autotss SET devices = ? WHERE user = ?', (json.dumps(devices), userid)) await db.commit() await asyncio.sleep(259200) @auto_invalid_device_check.before_loop async def before_invalid_device_check(self) -> None: await self.bot.wait_until_ready() await asyncio.sleep(3) # If first run, give on_ready() some time to create the database @commands.Cog.listener() async def on_guild_join(self, guild: discord.Guild) -> None: await self.bot.wait_until_ready() async with aiosqlite.connect('Data/autotss.db') as db: async with db.execute('SELECT prefix from prefix WHERE guild = ?', (guild.id,)) as cursor: if await cursor.fetchone() is not None: await db.execute('DELETE from prefix where guild = ?', (guild.id,)) await db.commit() await db.execute('INSERT INTO prefix(guild, prefix) VALUES(?,?)', (guild.id, 'b!')) await db.commit() embed = await self.utils.info_embed('b!', self.bot.user) for channel in guild.text_channels: try: await channel.send(embed=embed) break except: pass @commands.Cog.listener() async def on_guild_remove(self, guild: discord.Guild) -> None: await self.bot.wait_until_ready() async with aiosqlite.connect('Data/autotss.db') as db: await db.execute('DELETE from prefix where guild = ?', (guild.id,)) await db.commit() @commands.Cog.listener() async def on_member_join(self, member: discord.Member) -> None: await self.bot.wait_until_ready() async with aiosqlite.connect('Data/autotss.db') as db, db.execute('SELECT * from autotss WHERE user = ?', (member.id,)) as cursor: data = await cursor.fetchone() if data is None: return async with aiosqlite.connect('Data/autotss.db') as db: await db.execute('UPDATE autotss SET enabled = ? WHERE user = ?', (True, member.id)) await db.commit() await self.utils.update_device_count() @commands.Cog.listener() async def on_member_remove(self, member: discord.Member) -> None: await self.bot.wait_until_ready() async with aiosqlite.connect('Data/autotss.db') as db, db.execute('SELECT * from autotss WHERE user = ?', (member.id,)) as cursor: data = await cursor.fetchone() if data is None: return if len(member.mutual_guilds) == 0: async with aiosqlite.connect('Data/autotss.db') as db: await db.execute('UPDATE autotss SET enabled = ? WHERE user = ?', (False, member.id)) await db.commit() await self.utils.update_device_count() @commands.Cog.listener() async def on_message(self, message: discord.Message) -> None: await self.bot.wait_until_ready() if message.channel.type == discord.ChannelType.private: return if message.content.replace(' ', '').replace('!', '') == self.bot.user.mention: whitelist = await self.utils.get_whitelist(message.guild.id) if (whitelist is not None) and (whitelist.id != message.channel.id): return prefix = await self.utils.get_prefix(message.guild.id) embed = discord.Embed(title='AutoTSS', description=f'My prefix is `{prefix}`. To see all of my commands, run `{prefix}help`.') embed.set_footer(text=message.author.name, icon_url=message.author.avatar_url_as(static_format='png')) try: await message.reply(embed=embed) except: pass @commands.Cog.listener() async def on_ready(self) -> None: await self.os.makedirs('Data', exist_ok=True) async with aiosqlite.connect('Data/autotss.db') as db: await db.execute(''' CREATE TABLE IF NOT EXISTS autotss( user INTEGER, devices JSON, enabled BOOLEAN ) ''') await db.commit() await db.execute(''' CREATE TABLE IF NOT EXISTS prefix( guild INTEGER, prefix TEXT ) ''') await db.commit() await db.execute(''' CREATE TABLE IF NOT EXISTS whitelist( guild INTEGER, channel INTEGER, enabled BOOLEAN ) ''') await db.commit() await db.execute(''' CREATE TABLE IF NOT EXISTS auto_frequency( time INTEGER ) ''') await db.commit() await self.utils.update_device_count() await self.utils.update_auto_saver_frequency() print('AutoTSS is now online.') @commands.Cog.listener() async def on_command_error(self, ctx: commands.Context, error) -> None: await self.bot.wait_until_ready() embed = discord.Embed(title='Error') if ctx.message.channel.type == discord.ChannelType.private: embed.description = 'AutoTSS cannot be used in DMs. Please use AutoTSS in a Discord server.' await ctx.reply(embed=embed) return if await self.utils.whitelist_check(ctx) != True: return prefix = await self.utils.get_prefix(ctx.guild.id) if isinstance(error, commands.CommandNotFound): if ctx.prefix.replace('!', '').replace(' ', '') == self.bot.user.mention: return embed.description = f"That command doesn't exist! Use `{prefix}help` to see all the commands I can run." await ctx.reply(embed=embed) elif isinstance(error, commands.MaxConcurrencyReached): embed.description = f"`{prefix + ctx.command.qualified_name}` cannot be ran more than once at the same time!" await ctx.reply(embed=embed) elif isinstance(error, commands.errors.CommandInvokeError): if isinstance(error.original, discord.errors.Forbidden): embed.description = f"I don't have the proper permissions to run correctly! \ Please ping an Administrator and tell them to kick & re-invite me using \ [this]({self.utils.invite}) link to fix this issue." message_sent = False for channel in ctx.guild.text_channels: try: await channel.send(embed=embed) message_sent = True break except: pass if message_sent: return try: embed.description = f"I don't have the proper permissions to run correctly! \ Please kick me from `{ctx.guild.name}` & re-invite me using \ [this]({self.utils.invite}) link to fix this issue." await ctx.guild.owner.send(embed=embed) except: # We can't tell the user to tell an admin to fix our permissions, we can't DM the owner to fix it, we might as well leave. await ctx.guild.leave() else: raise error elif isinstance(error, commands.ChannelNotFound): embed = discord.Embed(title='Error', description='That channel does not exist.') await ctx.reply(embed=embed) elif (isinstance(error, commands.errors.NotOwner)) or \ (isinstance(error, commands.MissingPermissions)): return else: raise error def setup(bot): bot.add_cog(Events(bot))
# This file is part of sner4 project governed by MIT license, see the LICENSE.txt file. """ agent basic tests """ import json from pathlib import Path from uuid import uuid4 from flask import url_for from sner.agent.core import main as agent_main from sner.lib import file_from_zip from sner.server.scheduler.models import Job, Queue def test_version(tmpworkdir): # pylint: disable=unused-argument """test print version""" result = agent_main(['--version']) assert result == 0 def test_commandline_assignment(tmpworkdir): # pylint: disable=unused-argument """test custom assignment passed from command line""" test_a = {'id': str(uuid4()), 'config': {'module': 'dummy', 'args': '--arg1'}, 'targets': []} result = agent_main(['--assignment', json.dumps(test_a)]) assert result == 0 assert Path(f'{test_a['id']}.zip').exists() def test_exception_in_module(tmpworkdir): # pylint: disable=unused-argument """test exception handling during agent module execution""" test_a = {'id': str(uuid4()), 'config': {'module': 'notexist'}, 'targets': []} result = agent_main(['--assignment', json.dumps(test_a)]) assert result == 1 assert Path(f'{test_a['id']}.zip').exists() def test_run_with_liveserver(tmpworkdir, live_server, apikey, dummy_target): # pylint: disable=unused-argument """test basic agent's networking codepath; fetch, execute, pack and upload assignment""" result = agent_main([ '--server', url_for('index_route', _external=True), '--apikey', apikey, '--queue', Queue.query.get(dummy_target.queue_id).name, '--caps', 'cap1', 'cap2', '--oneshot', '--debug', ]) assert result == 0 job = Job.query.filter(Job.queue_id == dummy_target.queue_id).one() assert dummy_target.target in file_from_zip(job.output_abspath, 'assignment.json').decode('utf-8')
# This file is part of sner4 project governed by MIT license, see the LICENSE.txt file. """ agent basic tests """ import json from pathlib import Path from uuid import uuid4 from flask import url_for from sner.agent.core import main as agent_main from sner.lib import file_from_zip from sner.server.scheduler.models import Job, Queue def test_version(tmpworkdir): # pylint: disable=unused-argument """test print version""" result = agent_main(['--version']) assert result == 0 def test_commandline_assignment(tmpworkdir): # pylint: disable=unused-argument """test custom assignment passed from command line""" test_a = {'id': str(uuid4()), 'config': {'module': 'dummy', 'args': '--arg1'}, 'targets': []} result = agent_main(['--assignment', json.dumps(test_a)]) assert result == 0 assert Path(f'{test_a["id"]}.zip').exists() def test_exception_in_module(tmpworkdir): # pylint: disable=unused-argument """test exception handling during agent module execution""" test_a = {'id': str(uuid4()), 'config': {'module': 'notexist'}, 'targets': []} result = agent_main(['--assignment', json.dumps(test_a)]) assert result == 1 assert Path(f'{test_a["id"]}.zip').exists() def test_run_with_liveserver(tmpworkdir, live_server, apikey, dummy_target): # pylint: disable=unused-argument """test basic agent's networking codepath; fetch, execute, pack and upload assignment""" result = agent_main([ '--server', url_for('index_route', _external=True), '--apikey', apikey, '--queue', Queue.query.get(dummy_target.queue_id).name, '--caps', 'cap1', 'cap2', '--oneshot', '--debug', ]) assert result == 0 job = Job.query.filter(Job.queue_id == dummy_target.queue_id).one() assert dummy_target.target in file_from_zip(job.output_abspath, 'assignment.json').decode('utf-8')
import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * ''' IMPORTS ''' import json import requests import base64 import email import hashlib from typing import List from dateutil.parser import parse from typing import Dict, Tuple, Any, Optional, Union from threading import Timer # Disable insecure warnings requests.packages.urllib3.disable_warnings() ''' GLOBALS/PARAMS ''' INTEGRATION_NAME = 'CrowdStrike Falcon' CLIENT_ID = demisto.params().get('client_id') SECRET = demisto.params().get('secret') # Remove trailing slash to prevent wrong URL path to service SERVER = demisto.params()['url'][:-1] if (demisto.params()['url'] and demisto.params()['url'].endswith('/')) else \ demisto.params()['url'] # Should we use SSL USE_SSL = not demisto.params().get('insecure', False) # How many time before the first fetch to retrieve incidents FETCH_TIME = demisto.params().get('fetch_time', '3 days') BYTE_CREDS = '{name}:{password}'.format(name=CLIENT_ID, password=SECRET).encode('utf-8') # Headers to be sent in requests HEADERS = { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': 'Basic {}'.format(base64.b64encode(BYTE_CREDS).decode()) } # Note: True life time of token is actually 30 mins TOKEN_LIFE_TIME = 28 INCIDENTS_PER_FETCH = int(demisto.params().get('incidents_per_fetch', 15)) # Remove proxy if not set to true in params handle_proxy() ''' KEY DICTIONARY ''' DETECTIONS_BASE_KEY_MAP = { 'device.hostname': 'System', 'device.cid': 'CustomerID', 'hostinfo.domain': 'MachineDomain', 'detection_id': 'ID', 'created_timestamp': 'ProcessStartTime', 'max_severity': 'MaxSeverity', 'show_in_ui': 'ShowInUi', 'status': 'Status' } DETECTIONS_BEHAVIORS_KEY_MAP = { 'filename': 'FileName', 'scenario': 'Scenario', 'md5': 'MD5', 'sha256': 'SHA256', 'ioc_type': 'IOCType', 'ioc_value': 'IOCValue', 'cmdline': 'CommandLine', 'user_name': 'UserName', 'behavior_id': 'ID', } IOC_KEY_MAP = { 'type': 'Type', 'value': 'Value', 'policy': 'Policy', 'source': 'Source', 'share_level': 'ShareLevel', 'expiration': 'Expiration', 'description': 'Description', 'created_on': 'CreatedTime', 'created_by': 'CreatedBy', 'modified_on': 'ModifiedTime', 'modified_by': 'ModifiedBy', 'id': 'ID', 'platforms': 'Platforms', 'action': 'Action', 'severity': 'Severity', 'tags': 'Tags', } IOC_DEVICE_COUNT_MAP = { 'id': 'ID', 'type': 'Type', 'value': 'Value', 'device_count': 'DeviceCount' } SEARCH_DEVICE_KEY_MAP = { 'device_id': 'ID', 'external_ip': 'ExternalIP', 'local_ip': 'LocalIP', 'hostname': 'Hostname', 'os_version': 'OS', 'mac_address': 'MacAddress', 'first_seen': 'FirstSeen', 'last_seen': 'LastSeen', 'status': 'Status', } ENDPOINT_KEY_MAP = { 'device_id': 'ID', 'local_ip': 'IPAddress', 'os_version': 'OS', 'hostname': 'Hostname', 'status': 'Status', } ''' SPLIT KEY DICTIONARY ''' """ Pattern: { 'Path': 'Path to item', 'NewKey': 'Value of output key', 'Delim': 'Delimiter char', 'Index': Split Array Index } """ DETECTIONS_BEHAVIORS_SPLIT_KEY_MAP = [ { 'Path': 'parent_details.parent_process_graph_id', 'NewKey': 'SensorID', 'Delim': ':', 'Index': 1 }, { 'Path': 'parent_details.parent_process_graph_id', 'NewKey': 'ParentProcessID', 'Delim': ':', 'Index': 2 }, { 'Path': 'triggering_process_graph_id', 'NewKey': 'ProcessID', 'Delim': ':', 'Index': 2 }, ] HOST_GROUP_HEADERS = ['id', 'name', 'group_type', 'description', 'assignment_rule', 'created_by', 'created_timestamp', 'modified_by', 'modified_timestamp'] STATUS_TEXT_TO_NUM = {'New': "20", 'Reopened': "25", 'In Progress': "30", 'Closed': "40"} STATUS_NUM_TO_TEXT = {20: 'New', 25: 'Reopened', 30: 'In Progress', 40: 'Closed'} ''' HELPER FUNCTIONS ''' def http_request(method, url_suffix, params=None, data=None, files=None, headers=HEADERS, safe=False, get_token_flag=True, no_json=False, json=None, status_code=None): """ A wrapper for requests lib to send our requests and handle requests and responses better. :param json: JSON body :type json ``dict`` or ``list`` :type method: ``str`` :param method: HTTP method for the request. :type url_suffix: ``str`` :param url_suffix: The suffix of the URL (endpoint) :type params: ``dict`` :param params: The URL params to be passed. :type data: ``str`` :param data: The body data of the request. :type headers: ``dict`` :param headers: Request headers :type safe: ``bool`` :param safe: If set to true will return None in case of http error :type get_token_flag: ``bool`` :param get_token_flag: If set to True will call get_token() :type no_json: ``bool`` :param no_json: If set to true will not parse the content and will return the raw response object for successful response :type status_code: ``int`` :param: status_code: The request codes to accept as OK. :return: Returns the http request response json :rtype: ``dict`` """ if get_token_flag: token = get_token() headers['Authorization'] = 'Bearer {}'.format(token) url = SERVER + url_suffix try: res = requests.request( method, url, verify=USE_SSL, params=params, data=data, headers=headers, files=files, json=json, ) except requests.exceptions.RequestException as e: return_error(f'Error in connection to the server. Please make sure you entered the URL correctly.' f' Exception is {str(e)}.') try: valid_status_codes = {200, 201, 202, 204} # Handling a case when we want to return an entry for 404 status code. if status_code: valid_status_codes.add(status_code) if res.status_code not in valid_status_codes: res_json = res.json() reason = res.reason resources = res_json.get('resources', {}) if resources: if isinstance(resources, list): reason += f'\n{str(resources)}' else: for host_id, resource in resources.items(): errors = resource.get('errors', []) if errors: error_message = errors[0].get('message') reason += f'\nHost ID {host_id} - {error_message}' elif res_json.get('errors'): errors = res_json.get('errors', []) for error in errors: reason += f"\n{error.get("message")}" err_msg = 'Error in API call to CrowdStrike Falcon: code: {code} - reason: {reason}'.format( code=res.status_code, reason=reason ) # try to create a new token if res.status_code == 403 and get_token_flag: LOG(err_msg) token = get_token(new_token=True) headers['Authorization'] = 'Bearer {}'.format(token) return http_request( method=method, url_suffix=url_suffix, params=params, data=data, headers=headers, files=files, json=json, safe=safe, get_token_flag=False, status_code=status_code, no_json=no_json, ) elif safe: return None return_error(err_msg) return res if no_json else res.json() except ValueError as exception: raise ValueError( f'Failed to parse json object from response: {exception} - {res.content}') # type: ignore[str-bytes-safe] def create_entry_object(contents: Union[List[Any], Dict[str, Any]] = {}, ec: Union[List[Any], Dict[str, Any]] = None, hr: str = ''): """ Creates an entry object :type contents: ``dict`` :param contents: Raw response to output :type ec: ``dict`` :param ec: Entry context of the entry object :type hr: ``str`` :param hr: Human readable :return: Entry object :rtype: ``dict`` """ return { 'Type': entryTypes['note'], 'Contents': contents, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': hr, 'EntryContext': ec } def detection_to_incident(detection): """ Creates an incident of a detection. :type detection: ``dict`` :param detection: Single detection object :return: Incident representation of a detection :rtype ``dict`` """ incident = { 'name': 'Detection ID: ' + str(detection.get('detection_id')), 'occurred': str(detection.get('created_timestamp')), 'rawJSON': json.dumps(detection), 'severity': severity_string_to_int(detection.get('max_severity_displayname')) } return incident def incident_to_incident_context(incident): """ Creates an incident context of a incident. :type incident: ``dict`` :param incident: Single detection object :return: Incident context representation of a incident :rtype ``dict`` """ incident_id = str(incident.get('incident_id')) incident_context = { 'name': f'Incident ID: {incident_id}', 'occurred': str(incident.get('start')), 'rawJSON': json.dumps(incident) } return incident_context def severity_string_to_int(severity): """ Converts a severity string to DBot score representation :type severity: ``str`` :param severity: String representation of a severity :return: DBot score representation of the severity :rtype ``int`` """ if severity in ('Critical', 'High'): return 3 elif severity in ('Medium', 'Low'): return 2 return 0 def get_trasnformed_dict(old_dict, transformation_dict): """ Returns a dictionary with the same values as old_dict, with the correlating key:value in transformation_dict :type old_dict: ``dict`` :param old_dict: Old dictionary to pull values from :type transformation_dict: ``dict`` :param transformation_dict: Transformation dictionary that contains oldkeys:newkeys :return Transformed dictionart (according to transformation_dict values) :rtype ``dict`` """ new_dict = {} for k in list(old_dict.keys()): if k in transformation_dict: new_dict[transformation_dict[k]] = old_dict[k] return new_dict def extract_transformed_dict_with_split(old_dict, transformation_dict_arr): """ Extracts new values out of old_dict using a json structure of: {'Path': 'Path to item', 'NewKey': 'Value of output key', 'Delim': 'Delimiter char', 'Index': Split Array Index} """ new_dict = {} for trans_dict in transformation_dict_arr: try: val = demisto.get(old_dict, trans_dict['Path']) if 'split' in dir(val): i = trans_dict['Index'] new_dict[trans_dict['NewKey']] = val.split(trans_dict['Delim'])[i] except Exception as ex: LOG('Error {exception} with: {tdict}'.format(exception=ex, tdict=trans_dict)) return new_dict def get_passed_mins(start_time, end_time_str): """ Returns the time passed in mins :param start_time: Start time in datetime :param end_time_str: End time in str :return: The passed mins in int """ time_delta = start_time - datetime.fromtimestamp(end_time_str) return time_delta.seconds / 60 def handle_response_errors(raw_res: dict, err_msg: str = None): """ Raise exception if raw_res is empty or contains errors """ if not err_msg: err_msg = "The server was unable to return a result, please run the command again." if not raw_res: raise DemistoException(err_msg) if raw_res.get('errors'): raise DemistoException(raw_res.get('errors')) return ''' COMMAND SPECIFIC FUNCTIONS ''' def init_rtr_single_session(host_id: str) -> str: """ Start a session with single host. :param host_id: Host agent ID to initialize a RTR session on. :return: The session ID to execute the command on """ endpoint_url = '/real-time-response/entities/sessions/v1' body = json.dumps({ 'device_id': host_id }) response = http_request('POST', endpoint_url, data=body) resources = response.get('resources') if resources and isinstance(resources, list) and isinstance(resources[0], dict): session_id = resources[0].get('session_id') if isinstance(session_id, str): return session_id raise ValueError('No session id found in the response') def init_rtr_batch_session(host_ids: list) -> str: """ Start a session with one or more hosts :param host_ids: List of host agent ID’s to initialize a RTR session on. :return: The session batch ID to execute the command on """ endpoint_url = '/real-time-response/combined/batch-init-session/v1' body = json.dumps({ 'host_ids': host_ids }) response = http_request('POST', endpoint_url, data=body) return response.get('batch_id') def refresh_session(host_id: str) -> Dict: """ Refresh a session timeout on a single host. :param host_id: Host agent ID to run RTR command on. :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/entities/refresh-session/v1' body = json.dumps({ 'device_id': host_id }) response = http_request('POST', endpoint_url, data=body) return response def batch_refresh_session(batch_id: str) -> None: """ Batch refresh a RTR session on multiple hosts. :param batch_id: Batch ID to execute the command on. """ demisto.debug('Starting session refresh') endpoint_url = '/real-time-response/combined/batch-refresh-session/v1' body = json.dumps({ 'batch_id': batch_id }) response = http_request('POST', endpoint_url, data=body) demisto.debug(f'Refresh session response: {response}') demisto.debug('Finished session refresh') def run_batch_read_cmd(batch_id: str, command_type: str, full_command: str) -> Dict: """ Sends RTR command scope with read access :param batch_id: Batch ID to execute the command on. :param command_type: Read-only command type we are going to execute, for example: ls or cd. :param full_command: Full command string for the command. :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/combined/batch-command/v1' body = json.dumps({ 'base_command': command_type, 'batch_id': batch_id, 'command_string': full_command }) response = http_request('POST', endpoint_url, data=body) return response def run_batch_write_cmd(batch_id: str, command_type: str, full_command: str) -> Dict: """ Sends RTR command scope with write access :param batch_id: Batch ID to execute the command on. :param command_type: Read-only command type we are going to execute, for example: ls or cd. :param full_command: Full command string for the command. :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/combined/batch-active-responder-command/v1' body = json.dumps({ 'base_command': command_type, 'batch_id': batch_id, 'command_string': full_command }) response = http_request('POST', endpoint_url, data=body) return response def run_batch_admin_cmd(batch_id: str, command_type: str, full_command: str, timeout: int = 30) -> Dict: """ Sends RTR command scope with write access :param batch_id: Batch ID to execute the command on. :param command_type: Read-only command type we are going to execute, for example: ls or cd. :param full_command: Full command string for the command. :param timeout: Timeout for how long to wait for the request in seconds. :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/combined/batch-admin-command/v1' params = { 'timeout': timeout } body = json.dumps({ 'base_command': command_type, 'batch_id': batch_id, 'command_string': full_command }) response = http_request('POST', endpoint_url, data=body, params=params) return response def run_batch_get_cmd(host_ids: list, file_path: str, optional_hosts: list = None, timeout: int = None, timeout_duration: str = None) -> Dict: """ Batch executes `get` command across hosts to retrieve files. After this call is made `/real-time-response/combined/batch-get-command/v1` is used to query for the results. :param host_ids: List of host agent ID’s to run RTR command on. :param file_path: Full path to the file that is to be retrieved from each host in the batch. :param optional_hosts: List of a subset of hosts we want to run the command on. If this list is supplied, only these hosts will receive the command. :param timeout: Timeout for how long to wait for the request in seconds :param timeout_duration: Timeout duration for for how long to wait for the request in duration syntax :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/combined/batch-get-command/v1' batch_id = init_rtr_batch_session(host_ids) body = assign_params(batch_id=batch_id, file_path=file_path, optional_hosts=optional_hosts) params = assign_params(timeout=timeout, timeout_duration=timeout_duration) response = http_request('POST', endpoint_url, data=json.dumps(body), params=params) return response def status_get_cmd(request_id: str, timeout: int = None, timeout_duration: str = None) -> Dict: """ Retrieves the status of the specified batch get command. Will return successful files when they are finished processing. :param request_id: ID to the request of `get` command. :param timeout: Timeout for how long to wait for the request in seconds :param timeout_duration: Timeout duration for for how long to wait for the request in duration syntax :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/combined/batch-get-command/v1' params = assign_params(timeout=timeout, timeout_duration=timeout_duration, batch_get_cmd_req_id=request_id) response = http_request('GET', endpoint_url, params=params) return response def run_single_read_cmd(host_id: str, command_type: str, full_command: str) -> Dict: """ Sends RTR command scope with read access :param host_id: Host agent ID to run RTR command on. :param command_type: Active-Responder command type we are going to execute, for example: get or cp. :param full_command: Full command string for the command. :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/entities/command/v1' session_id = init_rtr_single_session(host_id) body = json.dumps({ 'base_command': command_type, 'command_string': full_command, 'session_id': session_id }) response = http_request('POST', endpoint_url, data=body) return response def run_single_write_cmd(host_id: str, command_type: str, full_command: str) -> Dict: """ Sends RTR command scope with write access :param host_id: Host agent ID to run RTR command on. :param command_type: Active-Responder command type we are going to execute, for example: get or cp. :param full_command: Full command string for the command. :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/entities/active-responder-command/v1' session_id = init_rtr_single_session(host_id) body = json.dumps({ 'base_command': command_type, 'command_string': full_command, 'session_id': session_id }) response = http_request('POST', endpoint_url, data=body) return response def run_single_admin_cmd(host_id: str, command_type: str, full_command: str) -> Dict: """ Sends RTR command scope with admin access :param host_id: Host agent ID to run RTR command on. :param command_type: Active-Responder command type we are going to execute, for example: get or cp. :param full_command: Full command string for the command. :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/entities/admin-command/v1' session_id = init_rtr_single_session(host_id) body = json.dumps({ 'base_command': command_type, 'command_string': full_command, 'session_id': session_id }) response = http_request('POST', endpoint_url, data=body) return response def status_read_cmd(request_id: str, sequence_id: Optional[int]) -> Dict: """ Get status of an executed command with read access on a single host. :param request_id: Cloud Request ID of the executed command to query :param sequence_id: Sequence ID that we want to retrieve. Command responses are chunked across sequences """ endpoint_url = '/real-time-response/entities/command/v1' params = { 'cloud_request_id': request_id, 'sequence_id': sequence_id or 0 } response = http_request('GET', endpoint_url, params=params) return response def status_write_cmd(request_id: str, sequence_id: Optional[int]) -> Dict: """ Get status of an executed command with write access on a single host. :param request_id: Cloud Request ID of the executed command to query :param sequence_id: Sequence ID that we want to retrieve. Command responses are chunked across sequences """ endpoint_url = '/real-time-response/entities/active-responder-command/v1' params = { 'cloud_request_id': request_id, 'sequence_id': sequence_id or 0 } response = http_request('GET', endpoint_url, params=params) return response def status_admin_cmd(request_id: str, sequence_id: Optional[int]) -> Dict: """ Get status of an executed command with admin access on a single host. :param request_id: Cloud Request ID of the executed command to query :param sequence_id: Sequence ID that we want to retrieve. Command responses are chunked across sequences """ endpoint_url = '/real-time-response/entities/admin-command/v1' params = { 'cloud_request_id': request_id, 'sequence_id': sequence_id or 0 } response = http_request('GET', endpoint_url, params=params) return response def list_host_files(host_id: str) -> Dict: """ Get a list of files for the specified RTR session on a host. :param host_id: Host agent ID to run RTR command on. :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/entities/file/v1' session_id = init_rtr_single_session(host_id) params = { 'session_id': session_id } response = http_request('GET', endpoint_url, params=params) return response def upload_script(name: str, permission_type: str, content: str, entry_id: str) -> Dict: """ Uploads a script by either given content or file :param name: Script name to upload :param permission_type: Permissions type of script to upload :param content: PowerShell script content :param entry_id: Script file to upload :return: Response JSON which contains errors (if exist) and how many resources were affected """ endpoint_url = '/real-time-response/entities/scripts/v1' body: Dict[str, Tuple[Any, Any]] = { 'name': (None, name), 'permission_type': (None, permission_type) } temp_file = None try: if content: body['content'] = (None, content) else: # entry_id was provided file_ = demisto.getFilePath(entry_id) file_name = file_.get('name') # pylint: disable=E1101 temp_file = open(file_.get('path'), 'rb') # pylint: disable=E1101 body['file'] = (file_name, temp_file) headers = { 'Authorization': HEADERS['Authorization'], 'Accept': 'application/json' } response = http_request('POST', endpoint_url, files=body, headers=headers) return response finally: if temp_file: temp_file.close() def get_script(script_id: list) -> Dict: """ Retrieves a script given its ID :param script_id: ID of script to get :return: Response JSON which contains errors (if exist) and retrieved resource """ endpoint_url = '/real-time-response/entities/scripts/v1' params = { 'ids': script_id } response = http_request('GET', endpoint_url, params=params) return response def delete_script(script_id: str) -> Dict: """ Deletes a script given its ID :param script_id: ID of script to delete :return: Response JSON which contains errors (if exist) and how many resources were affected """ endpoint_url = '/real-time-response/entities/scripts/v1' params = { 'ids': script_id } response = http_request('DELETE', endpoint_url, params=params) return response def list_scripts() -> Dict: """ Retrieves list of scripts :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/entities/scripts/v1' response = http_request('GET', endpoint_url) return response def get_extracted_file(host_id: str, sha256: str, filename: str = None): """ Get RTR extracted file contents for specified session and sha256. :param host_id: The host agent ID to initialize the RTR session on. :param sha256: Extracted SHA256 :param filename: Filename to use for the archive name and the file within the archive. """ endpoint_url = '/real-time-response/entities/extracted-file-contents/v1' session_id = init_rtr_single_session(host_id) params = { 'session_id': session_id, 'sha256': sha256 } if filename: params['filename'] = filename response = http_request('GET', endpoint_url, params=params, no_json=True) return response def upload_file(entry_id: str, description: str) -> Tuple: """ Uploads a file given entry ID :param entry_id: The entry ID of the file to upload :param description: String description of file to upload :return: Response JSON which contains errors (if exist) and how many resources were affected and the file name """ endpoint_url = '/real-time-response/entities/put-files/v1' temp_file = None try: file_ = demisto.getFilePath(entry_id) file_name = file_.get('name') # pylint: disable=E1101 temp_file = open(file_.get('path'), 'rb') # pylint: disable=E1101 body = { 'name': (None, file_name), 'description': (None, description), 'file': (file_name, temp_file) } headers = { 'Authorization': HEADERS['Authorization'], 'Accept': 'application/json' } response = http_request('POST', endpoint_url, files=body, headers=headers) return response, file_name finally: if temp_file: temp_file.close() def delete_file(file_id: str) -> Dict: """ Delete a put-file based on the ID given :param file_id: ID of file to delete :return: Response JSON which contains errors (if exist) and how many resources were affected """ endpoint_url = '/real-time-response/entities/put-files/v1' params = { 'ids': file_id } response = http_request('DELETE', endpoint_url, params=params) return response def get_file(file_id: list) -> Dict: """ Get put-files based on the ID's given :param file_id: ID of file to get :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/entities/put-files/v1' params = { 'ids': file_id } response = http_request('GET', endpoint_url, params=params) return response def list_files() -> Dict: """ Get a list of put-file ID's that are available to the user for the put command. :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/entities/put-files/v1' response = http_request('GET', endpoint_url) return response def get_token(new_token=False): """ Retrieves the token from the server if it's expired and updates the global HEADERS to include it :param new_token: If set to True will generate a new token regardless of time passed :rtype: ``str`` :return: Token """ now = datetime.now() ctx = demisto.getIntegrationContext() if ctx and not new_token: passed_mins = get_passed_mins(now, ctx.get('time')) if passed_mins >= TOKEN_LIFE_TIME: # token expired auth_token = get_token_request() demisto.setIntegrationContext({'auth_token': auth_token, 'time': date_to_timestamp(now) / 1000}) else: # token hasn't expired auth_token = ctx.get('auth_token') else: # there is no token auth_token = get_token_request() demisto.setIntegrationContext({'auth_token': auth_token, 'time': date_to_timestamp(now) / 1000}) return auth_token def get_token_request(): """ Sends token request :rtype ``str`` :return: Access token """ body = { 'client_id': CLIENT_ID, 'client_secret': SECRET } headers = { 'Content-Type': 'application/x-www-form-urlencoded' } token_res = http_request('POST', '/oauth2/token', data=body, headers=headers, safe=True, get_token_flag=False) if not token_res: err_msg = 'Authorization Error: User has no authorization to create a token. Please make sure you entered the' \ ' credentials correctly.' raise Exception(err_msg) return token_res.get('access_token') def get_detections(last_behavior_time=None, behavior_id=None, filter_arg=None): """ Sends detections request. The function will ignore the arguments passed according to priority: filter_arg > behavior_id > last_behavior_time :param last_behavior_time: 3rd priority. The last behavior time of results will be greater than this value :param behavior_id: 2nd priority. The result will only contain the detections with matching behavior id :param filter_arg: 1st priority. The result will be filtered using this argument. :return: Response json of the get detection endpoint (IDs of the detections) """ endpoint_url = '/detects/queries/detects/v1' params = { 'sort': 'first_behavior.asc' } if filter_arg: params['filter'] = filter_arg elif behavior_id: params['filter'] = "behaviors.behavior_id:'{0}'".format(behavior_id) elif last_behavior_time: params['filter'] = "first_behavior:>'{0}'".format(last_behavior_time) response = http_request('GET', endpoint_url, params) return response def get_fetch_detections(last_created_timestamp=None, filter_arg=None, offset: int = 0): """ Sends detection request, based on the created_timestamp field. Used for fetch-incidents Args: last_created_timestamp: last created timestamp of the results will be greater than this value. filter_arg: The result will be filtered using this argument. Returns: Response json of the get detection endpoint (IDs of the detections) """ endpoint_url = '/detects/queries/detects/v1' params = { 'sort': 'first_behavior.asc', 'offset': offset, 'limit': INCIDENTS_PER_FETCH } if filter_arg: params['filter'] = filter_arg elif last_created_timestamp: params['filter'] = "created_timestamp:>'{0}'".format(last_created_timestamp) response = http_request('GET', endpoint_url, params) return response def get_detections_entities(detections_ids): """ Sends detection entities request :param detections_ids: IDs of the requested detections. :return: Response json of the get detection entities endpoint (detection objects) """ ids_json = {'ids': detections_ids} if detections_ids: response = http_request( 'POST', '/detects/entities/summaries/GET/v1', data=json.dumps(ids_json) ) return response return detections_ids def get_incidents_ids(last_created_timestamp=None, filter_arg=None, offset: int = 0): get_incidents_endpoint = '/incidents/queries/incidents/v1' params = { 'sort': 'start.asc', 'offset': offset, 'limit': INCIDENTS_PER_FETCH } if filter_arg: params['filter'] = filter_arg elif last_created_timestamp: params['filter'] = "start:>'{0}'".format(last_created_timestamp) response = http_request('GET', get_incidents_endpoint, params) return response def get_incidents_entities(incidents_ids): ids_json = {'ids': incidents_ids} response = http_request( 'POST', '/incidents/entities/incidents/GET/v1', data=json.dumps(ids_json) ) return response def upload_ioc(ioc_type, value, policy=None, expiration_days=None, share_level=None, description=None, source=None): """ Create a new IOC (or replace an existing one) """ payload = assign_params( type=ioc_type, value=value, policy=policy, share_level=share_level, expiration_days=expiration_days, source=source, description=description, ) return http_request('POST', '/indicators/entities/iocs/v1', json=[payload]) def update_ioc(ioc_type, value, policy=None, expiration_days=None, share_level=None, description=None, source=None): """ Update an existing IOC """ body = assign_params( type=ioc_type, value=value, policy=policy, share_level=share_level, expiration_days=expiration_days, source=source, description=description, ) params = assign_params( type=ioc_type, value=value ) return http_request('PATCH', '/indicators/entities/iocs/v1', json=body, params=params) def search_iocs(types=None, values=None, policies=None, sources=None, expiration_from=None, expiration_to=None, limit=None, share_levels=None, ids=None, sort=None, offset=None): """ :param types: A list of indicator types. Separate multiple types by comma. :param values: Comma-separated list of indicator values :param policies: Comma-separated list of indicator policies :param sources: Comma-separated list of IOC sources :param expiration_from: Start of date range to search (YYYY-MM-DD format). :param expiration_to: End of date range to search (YYYY-MM-DD format). :param share_levels: A list of share levels. Only red is supported. :param limit: The maximum number of records to return. The minimum is 1 and the maximum is 500. Default is 100. :param sort: The order of the results. Format :param offset: The offset to begin the list from """ if not ids: payload = assign_params( types=argToList(types), values=argToList(values), policies=argToList(policies), sources=argToList(sources), share_levels=argToList(share_levels), sort=sort, offset=offset, limit=limit or '50', ) if expiration_from: payload['from.expiration_timestamp'] = expiration_from if expiration_to: payload['to.expiration_timestamp'] = expiration_to ids = http_request('GET', '/indicators/queries/iocs/v1', payload).get('resources') if not ids: return None else: ids = str(ids) payload = { 'ids': ids } return http_request('GET', '/indicators/entities/iocs/v1', params=payload) def enrich_ioc_dict_with_ids(ioc_dict): """ Enriches the provided ioc_dict with IOC ID :param ioc_dict: IOC dict transformed using the SEARCH_IOC_KEY_MAP :return: ioc_dict with its ID key:value updated """ for ioc in ioc_dict: ioc['ID'] = '{type}:{val}'.format(type=ioc.get('Type'), val=ioc.get('Value')) return ioc_dict def delete_ioc(ioc_type, value): """ Delete an IOC """ payload = assign_params( type=ioc_type, value=value ) return http_request('DELETE', '/indicators/entities/iocs/v1', payload) def search_custom_iocs( types: Optional[Union[list, str]] = None, values: Optional[Union[list, str]] = None, sources: Optional[Union[list, str]] = None, expiration: Optional[str] = None, limit: str = '50', sort: Optional[str] = None, offset: Optional[str] = None, ) -> dict: """ :param types: A list of indicator types. Separate multiple types by comma. :param values: Comma-separated list of indicator values :param sources: Comma-separated list of IOC sources :param expiration: The date on which the indicator will become inactive. (YYYY-MM-DD format). :param limit: The maximum number of records to return. The minimum is 1 and the maximum is 500. Default is 100. :param sort: The order of the results. Format :param offset: The offset to begin the list from """ filter_list = [] if types: filter_list.append(f'type:{types}') if values: filter_list.append(f'value:{values}') if sources: filter_list.append(f'source:{sources}') if expiration: filter_list.append(f'expiration:"{expiration}"') params = { 'filter': '+'.join(filter_list), 'sort': sort, 'offset': offset, 'limit': limit, } return http_request('GET', '/iocs/combined/indicator/v1', params=params) def get_custom_ioc(ioc_id: str) -> dict: params = {'ids': ioc_id} return http_request('GET', '/iocs/entities/indicators/v1', params=params) def upload_custom_ioc( ioc_type: str, value: str, action: str, platforms: str, severity: Optional[str] = None, source: Optional[str] = None, description: Optional[str] = None, expiration: Optional[str] = None, applied_globally: Optional[bool] = None, host_groups: Optional[List[str]] = None, ) -> dict: """ Create a new IOC (or replace an existing one) """ payload = { 'indicators': [assign_params( type=ioc_type, value=value, action=action, platforms=platforms, severity=severity, source=source, description=description, expiration=expiration, applied_globally=applied_globally, host_groups=host_groups, )] } return http_request('POST', '/iocs/entities/indicators/v1', json=payload) def update_custom_ioc( ioc_id: str, action: Optional[str] = None, platforms: Optional[str] = None, severity: Optional[str] = None, source: Optional[str] = None, description: Optional[str] = None, expiration: Optional[str] = None, ) -> dict: """ Update an IOC """ payload = { 'indicators': [{ 'id': ioc_id, } | assign_params( action=action, platforms=platforms, severity=severity, source=source, description=description, expiration=expiration, )] } return http_request('PATCH', '/iocs/entities/indicators/v1', json=payload) def delete_custom_ioc(ids: str) -> dict: """ Delete an IOC """ params = {'ids': ids} return http_request('DELETE', '/iocs/entities/indicators/v1', params=params) def get_ioc_device_count(ioc_type, value): """ Gets the devices that encountered the IOC """ payload = assign_params( type=ioc_type, value=value ) response = http_request('GET', '/indicators/aggregates/devices-count/v1', payload, status_code=404) errors = response.get('errors', []) for error in errors: if error.get('code') == 404: return f'No results found for {ioc_type} - {value}' return response def get_process_details(ids): """ Get given processes details """ payload = assign_params(ids=ids) return http_request('GET', '/processes/entities/processes/v1', payload) def get_proccesses_ran_on(ioc_type, value, device_id): """ Get processes ids that ran on the given device_id that encountered the ioc """ payload = assign_params( type=ioc_type, value=value, device_id=device_id ) return http_request('GET', '/indicators/queries/processes/v1', payload) def search_device(): """ Searches for devices using the argument provided by the command execution. Returns empty result of no device was found :return: Search device response json """ args = demisto.args() input_arg_dict = { 'device_id': str(args.get('ids', '')).split(','), 'status': str(args.get('status', '')).split(','), 'hostname': str(args.get('hostname', '')).split(','), 'platform_name': str(args.get('platform_name', '')).split(','), 'site_name': str(args.get('site_name', '')).split(',') } url_filter = '{}'.format(str(args.get('filter', ''))) for k, arg in input_arg_dict.items(): if arg: if type(arg) is list: arg_filter = '' for arg_elem in arg: if arg_elem: first_arg = '{filter},{inp_arg}'.format(filter=arg_filter, inp_arg=k) if arg_filter else k arg_filter = "{first}:'{second}'".format(first=first_arg, second=arg_elem) if arg_filter: url_filter = "{url_filter}{arg_filter}".format(url_filter=url_filter + '+' if url_filter else '', arg_filter=arg_filter) else: # All args should be a list. this is a fallback url_filter = "{url_filter}+{inp_arg}:'{arg_val}'".format(url_filter=url_filter, inp_arg=k, arg_val=arg) raw_res = http_request('GET', '/devices/queries/devices/v1', params={'filter': url_filter}) device_ids = raw_res.get('resources') if not device_ids: return None return http_request('GET', '/devices/entities/devices/v1', params={'ids': device_ids}) def behavior_to_entry_context(behavior): """ Transforms a behavior to entry context representation :param behavior: Behavior dict in the format of crowdstrike's API response :return: Behavior in entry context representation """ raw_entry = get_trasnformed_dict(behavior, DETECTIONS_BEHAVIORS_KEY_MAP) raw_entry.update(extract_transformed_dict_with_split(behavior, DETECTIONS_BEHAVIORS_SPLIT_KEY_MAP)) return raw_entry def get_username_uuid(username: str): """ Obtain CrowdStrike user’s UUId by email. :param username: Username to get UUID of. :return: The user UUID """ response = http_request('GET', '/users/queries/user-uuids-by-email/v1', params={'uid': username}) resources: list = response.get('resources', []) if not resources: raise ValueError(f'User {username} was not found') return resources[0] def resolve_detection(ids, status, assigned_to_uuid, show_in_ui, comment): """ Sends a resolve detection request :param ids: Single or multiple ids in an array string format :param status: New status of the detection :param assigned_to_uuid: uuid to assign the detection to :param show_in_ui: Boolean flag in string format (true/false) :param comment: Optional comment to add to the detection :return: Resolve detection response json """ payload = { 'ids': ids } if status: payload['status'] = status if assigned_to_uuid: payload['assigned_to_uuid'] = assigned_to_uuid if show_in_ui: payload['show_in_ui'] = show_in_ui if comment: payload['comment'] = comment # We do this so show_in_ui value won't contain "" data = json.dumps(payload).replace('"show_in_ui": "false"', '"show_in_ui": false').replace('"show_in_ui": "true"', '"show_in_ui": true') return http_request('PATCH', '/detects/entities/detects/v2', data=data) def contain_host(ids): """ Contains host(s) with matching ids :param ids: IDs of host to contain :return: Contain host response json """ payload = { 'ids': ids } data = json.dumps(payload) params = { 'action_name': 'contain' } return http_request('POST', '/devices/entities/devices-actions/v2', data=data, params=params) def lift_host_containment(ids): """ Lifts off containment from host(s) with matchind ids :param ids: IDs of host to lift off containment from :return: Lift off containment response json """ payload = { 'ids': ids } data = json.dumps(payload) params = { 'action_name': 'lift_containment' } return http_request('POST', '/devices/entities/devices-actions/v2', data=data, params=params) def timestamp_length_equalization(timestamp1, timestamp2): """ Makes sure the timestamps are of the same length. Args: timestamp1: First timestamp to compare. timestamp2: Second timestamp to compare. Returns: the two timestamps in the same length (the longer one) """ diff_len = len(str(timestamp1)) - len(str(timestamp2)) # no difference in length if diff_len == 0: return int(timestamp1), int(timestamp2) # length of timestamp1 > timestamp2 if diff_len > 0: ten_times = pow(10, diff_len) timestamp2 = int(timestamp2) * ten_times # length of timestamp2 > timestamp1 else: ten_times = pow(10, diff_len * -1) timestamp1 = int(timestamp1) * ten_times return int(timestamp1), int(timestamp2) def change_host_group(is_post: bool, host_group_id: Optional[str] = None, name: Optional[str] = None, group_type: Optional[str] = None, description: Optional[str] = None, assignment_rule: Optional[str] = None) -> Dict: method = 'POST' if is_post else 'PATCH' data = {'resources': [{ 'id': host_group_id, "name": name, "description": description, "group_type": group_type, "assignment_rule": assignment_rule }]} response = http_request(method=method, url_suffix='/devices/entities/host-groups/v1', json=data) return response def change_host_group_members(action_name: str, host_group_id: str, host_ids: List[str]) -> Dict: allowed_actions = {'add-hosts', 'remove-hosts'} if action_name not in allowed_actions: raise DemistoException(f'CrowdStrike Falcon error: action name should be in {allowed_actions}') data = {'action_parameters': [{'name': 'filter', 'value': f"(device_id:{str(host_ids)})"}], 'ids': [host_group_id]} response = http_request(method='POST', url_suffix='/devices/entities/host-group-actions/v1', params={'action_name': action_name}, json=data) return response def host_group_members(filter: Optional[str], host_group_id: Optional[str], limit: Optional[str], offset: Optional[str]): params = {'id': host_group_id, 'filter': filter, 'offset': offset, 'limit': limit} response = http_request(method='GET', url_suffix='/devices/combined/host-group-members/v1', params=params) return response def resolve_incident(ids: List[str], status: str): if status not in STATUS_TEXT_TO_NUM: raise DemistoException(f'CrowdStrike Falcon Error: ' f'Status given is {status} and it is not in {STATUS_TEXT_TO_NUM.keys()}') data = { "action_parameters": [ { "name": "update_status", "value": STATUS_TEXT_TO_NUM[status] } ], "ids": ids } http_request(method='POST', url_suffix='/incidents/entities/incident-actions/v1', json=data) def list_host_groups(filter: Optional[str], limit: Optional[str], offset: Optional[str]) -> Dict: params = {'filter': filter, 'offset': offset, 'limit': limit} response = http_request(method='GET', url_suffix='/devices/combined/host-groups/v1', params=params) return response def delete_host_groups(host_group_ids: List[str]) -> Dict: params = {'ids': host_group_ids} response = http_request(method='DELETE', url_suffix='/devices/entities/host-groups/v1', params=params) return response ''' COMMANDS FUNCTIONS ''' def get_fetch_times_and_offset(incident_type): last_run = demisto.getLastRun() last_fetch_time = last_run.get(f'first_behavior_{incident_type}_time') offset = last_run.get(f'{incident_type}_offset', 0) if not last_fetch_time: last_fetch_time, _ = parse_date_range(FETCH_TIME, date_format='%Y-%m-%dT%H:%M:%SZ') prev_fetch = last_fetch_time last_fetch_timestamp = int(parse(last_fetch_time).timestamp() * 1000) return last_fetch_time, offset, prev_fetch, last_fetch_timestamp def fetch_incidents(): incidents = [] # type:List current_fetch_info = demisto.getLastRun() fetch_incidents_or_detections = demisto.params().get('fetch_incidents_or_detections') if 'Detections' in fetch_incidents_or_detections: incident_type = 'detection' last_fetch_time, offset, prev_fetch, last_fetch_timestamp = get_fetch_times_and_offset(incident_type) fetch_query = demisto.params().get('fetch_query') if fetch_query: fetch_query = "created_timestamp:>'{time}'+{query}".format(time=last_fetch_time, query=fetch_query) detections_ids = demisto.get(get_fetch_detections(filter_arg=fetch_query, offset=offset), 'resources') else: detections_ids = demisto.get(get_fetch_detections(last_created_timestamp=last_fetch_time, offset=offset), 'resources') if detections_ids: raw_res = get_detections_entities(detections_ids) if "resources" in raw_res: for detection in demisto.get(raw_res, "resources"): detection['incident_type'] = incident_type incident = detection_to_incident(detection) incident_date = incident['occurred'] incident_date_timestamp = int(parse(incident_date).timestamp() * 1000) # make sure that the two timestamps are in the same length if len(str(incident_date_timestamp)) != len(str(last_fetch_timestamp)): incident_date_timestamp, last_fetch_timestamp = timestamp_length_equalization( incident_date_timestamp, last_fetch_timestamp) # Update last run and add incident if the incident is newer than last fetch if incident_date_timestamp > last_fetch_timestamp: last_fetch_time = incident_date last_fetch_timestamp = incident_date_timestamp incidents.append(incident) if len(incidents) == INCIDENTS_PER_FETCH: current_fetch_info['first_behavior_detection_time'] = prev_fetch current_fetch_info['detection_offset'] = offset + INCIDENTS_PER_FETCH else: current_fetch_info['first_behavior_detection_time'] = last_fetch_time current_fetch_info['detection_offset'] = 0 if 'Incidents' in fetch_incidents_or_detections: incident_type = 'incident' last_fetch_time, offset, prev_fetch, last_fetch_timestamp = get_fetch_times_and_offset(incident_type) last_run = demisto.getLastRun() last_incident_fetched = last_run.get('last_fetched_incident') new_last_incident_fetched = '' fetch_query = demisto.params().get('incidents_fetch_query') if fetch_query: fetch_query = "start:>'{time}'+{query}".format(time=last_fetch_time, query=fetch_query) incidents_ids = demisto.get(get_incidents_ids(filter_arg=fetch_query, offset=offset), 'resources') else: incidents_ids = demisto.get(get_incidents_ids(last_created_timestamp=last_fetch_time, offset=offset), 'resources') if incidents_ids: raw_res = get_incidents_entities(incidents_ids) if "resources" in raw_res: for incident in demisto.get(raw_res, "resources"): incident['incident_type'] = incident_type incident_to_context = incident_to_incident_context(incident) incident_date = incident_to_context['occurred'] incident_date_timestamp = int(parse(incident_date).timestamp() * 1000) # make sure that the two timestamps are in the same length if len(str(incident_date_timestamp)) != len(str(last_fetch_timestamp)): incident_date_timestamp, last_fetch_timestamp = timestamp_length_equalization( incident_date_timestamp, last_fetch_timestamp) # Update last run and add incident if the incident is newer than last fetch if incident_date_timestamp > last_fetch_timestamp: last_fetch_time = incident_date last_fetch_timestamp = incident_date_timestamp new_last_incident_fetched = incident.get('incident_id') if last_incident_fetched != incident.get('incident_id'): incidents.append(incident_to_context) if len(incidents) == INCIDENTS_PER_FETCH: current_fetch_info['first_behavior_incident_time'] = prev_fetch current_fetch_info['incident_offset'] = offset + INCIDENTS_PER_FETCH current_fetch_info['last_fetched_incident'] = new_last_incident_fetched else: current_fetch_info['first_behavior_incident_time'] = last_fetch_time current_fetch_info['incident_offset'] = 0 current_fetch_info['last_fetched_incident'] = new_last_incident_fetched demisto.setLastRun(current_fetch_info) return incidents def upload_ioc_command(ioc_type=None, value=None, policy=None, expiration_days=None, share_level=None, description=None, source=None): """ :param ioc_type: The type of the indicator: :param policy :The policy to enact when the value is detected on a host. :param share_level: The level at which the indicator will be shared. :param expiration_days: This represents the days the indicator should be valid for. :param source: The source where this indicator originated. :param description: A meaningful description of the indicator. :param value: The string representation of the indicator. """ raw_res = upload_ioc(ioc_type, value, policy, expiration_days, share_level, description, source) handle_response_errors(raw_res) iocs = search_iocs(ids=f"{ioc_type}:{value}").get('resources') if not iocs: raise DemistoException("Failed to create IOC. Please try again.") ec = [get_trasnformed_dict(iocs[0], IOC_KEY_MAP)] enrich_ioc_dict_with_ids(ec) return create_entry_object(contents=raw_res, ec={'CrowdStrike.IOC(val.ID === obj.ID)': ec}, hr=tableToMarkdown('Custom IOC was created successfully', ec)) def update_ioc_command(ioc_type=None, value=None, policy=None, expiration_days=None, share_level=None, description=None, source=None): """ :param ioc_type: The type of the indicator: :param policy :The policy to enact when the value is detected on a host. :param share_level: The level at which the indicator will be shared. :param expiration_days: This represents the days the indicator should be valid for. :param source: The source where this indicator originated. :param description: A meaningful description of the indicator. :param value: The string representation of the indicator. """ raw_res = update_ioc(ioc_type, value, policy, expiration_days, share_level, description, source) handle_response_errors(raw_res) iocs = search_iocs(ids=f"{ioc_type}:{value}").get('resources') ec = [get_trasnformed_dict(iocs[0], IOC_KEY_MAP)] enrich_ioc_dict_with_ids(ec) return create_entry_object(contents=raw_res, ec={'CrowdStrike.IOC(val.ID === obj.ID)': ec}, hr=tableToMarkdown('Custom IOC was created successfully', ec)) def search_iocs_command(types=None, values=None, policies=None, sources=None, from_expiration_date=None, to_expiration_date=None, share_levels=None, limit=None, sort=None, offset=None): """ :param types: A list of indicator types. Separate multiple types by comma. :param values: Comma-separated list of indicator values :param policies: Comma-separated list of indicator policies :param sources: Comma-separated list of IOC sources :param from_expiration_date: Start of date range to search (YYYY-MM-DD format). :param to_expiration_date: End of date range to search (YYYY-MM-DD format). :param share_levels: A list of share levels. Only red is supported. :param limit: The maximum number of records to return. The minimum is 1 and the maximum is 500. Default is 100. :param sort: The order of the results. Format :param offset: The offset to begin the list from """ raw_res = search_iocs(types=types, values=values, policies=policies, sources=sources, sort=sort, offset=offset, expiration_from=from_expiration_date, expiration_to=to_expiration_date, share_levels=share_levels, limit=limit) if not raw_res: return create_entry_object(hr='Could not find any Indicators of Compromise.') handle_response_errors(raw_res) iocs = raw_res.get('resources') ec = [get_trasnformed_dict(ioc, IOC_KEY_MAP) for ioc in iocs] enrich_ioc_dict_with_ids(ec) return create_entry_object(contents=raw_res, ec={'CrowdStrike.IOC(val.ID === obj.ID)': ec}, hr=tableToMarkdown('Indicators of Compromise', ec)) def get_ioc_command(ioc_type: str, value: str): """ :param ioc_type: The type of the indicator :param value: The IOC value to retrieve """ raw_res = search_iocs(ids=f"{ioc_type}:{value}") handle_response_errors(raw_res, 'Could not find any Indicators of Compromise.') iocs = raw_res.get('resources') ec = [get_trasnformed_dict(ioc, IOC_KEY_MAP) for ioc in iocs] enrich_ioc_dict_with_ids(ec) return create_entry_object(contents=raw_res, ec={'CrowdStrike.IOC(val.ID === obj.ID)': ec}, hr=tableToMarkdown('Indicator of Compromise', ec)) def delete_ioc_command(ioc_type, value): """ :param ioc_type: The type of the indicator :param value: The IOC value to delete """ raw_res = delete_ioc(ioc_type, value) handle_response_errors(raw_res, "The server has not confirmed deletion, please manually confirm deletion.") ids = f"{ioc_type}:{value}" return create_entry_object(contents=raw_res, hr=f"Custom IOC {ids} was successfully deleted.") def search_custom_iocs_command( types: Optional[Union[list, str]] = None, values: Optional[Union[list, str]] = None, sources: Optional[Union[list, str]] = None, expiration: Optional[str] = None, limit: str = '50', sort: Optional[str] = None, offset: Optional[str] = None, ) -> dict: """ :param types: A list of indicator types. Separate multiple types by comma. :param values: Comma-separated list of indicator values :param sources: Comma-separated list of IOC sources :param expiration: The date on which the indicator will become inactive. (YYYY-MM-DD format). :param limit: The maximum number of records to return. The minimum is 1 and the maximum is 500. Default is 100. :param sort: The order of the results. Format :param offset: The offset to begin the list from """ raw_res = search_custom_iocs( types=argToList(types), values=argToList(values), sources=argToList(sources), sort=sort, offset=offset, expiration=expiration, limit=limit, ) iocs = raw_res.get('resources') if not iocs: return create_entry_object(hr='Could not find any Indicators of Compromise.') handle_response_errors(raw_res) ec = [get_trasnformed_dict(ioc, IOC_KEY_MAP) for ioc in iocs] return create_entry_object( contents=raw_res, ec={'CrowdStrike.IOC(val.ID === obj.ID)': ec}, hr=tableToMarkdown('Indicators of Compromise', ec), ) def get_custom_ioc_command( ioc_type: Optional[str] = None, value: Optional[str] = None, ioc_id: Optional[str] = None, ) -> dict: """ :param ioc_type: IOC type :param value: IOC value :param ioc_id: IOC ID """ if not ioc_id and not (ioc_type and value): raise ValueError('Either ioc_id or ioc_type and value must be provided.') if ioc_id: raw_res = get_custom_ioc(ioc_id) else: raw_res = search_custom_iocs( types=argToList(ioc_type), values=argToList(value), ) iocs = raw_res.get('resources') handle_response_errors(raw_res) if not iocs: return create_entry_object(hr='Could not find any Indicators of Compromise.') ec = [get_trasnformed_dict(ioc, IOC_KEY_MAP) for ioc in iocs] return create_entry_object( contents=raw_res, ec={'CrowdStrike.IOC(val.ID === obj.ID)': ec}, hr=tableToMarkdown('Indicator of Compromise', ec), ) def upload_custom_ioc_command( ioc_type: str, value: str, action: str, platforms: str, severity: Optional[str] = None, source: Optional[str] = None, description: Optional[str] = None, expiration: Optional[str] = None, applied_globally: Optional[bool] = None, host_groups: Optional[List[str]] = None, ) -> dict: """ :param ioc_type: The type of the indicator. :param value: The string representation of the indicator. :param action: Action to take when a host observes the custom IOC. :param platforms: The platforms that the indicator applies to. :param severity: The severity level to apply to this indicator. :param source: The source where this indicator originated. :param description: A meaningful description of the indicator. :param expiration: The date on which the indicator will become inactive. :param applied_globally: Whether the indicator is applied globally. :param host_groups: List of host group IDs that the indicator applies to. """ if action in {'prevent', 'detect'} and not severity: raise ValueError(f'Severity is required for action {action}.') raw_res = upload_custom_ioc( ioc_type, value, action, argToList(platforms), severity, source, description, expiration, argToBoolean(applied_globally) if applied_globally else None, argToList(host_groups), ) handle_response_errors(raw_res) iocs = raw_res.get('resources', []) ec = [get_trasnformed_dict(iocs[0], IOC_KEY_MAP)] return create_entry_object( contents=raw_res, ec={'CrowdStrike.IOC(val.ID === obj.ID)': ec}, hr=tableToMarkdown('Custom IOC was created successfully', ec), ) def update_custom_ioc_command( ioc_id: str, action: Optional[str] = None, platforms: Optional[str] = None, severity: Optional[str] = None, source: Optional[str] = None, description: Optional[str] = None, expiration: Optional[str] = None, ) -> dict: """ :param ioc_id: The ID of the indicator to update. :param action: Action to take when a host observes the custom IOC. :param platforms: The platforms that the indicator applies to. :param severity: The severity level to apply to this indicator. :param source: The source where this indicator originated. :param description: A meaningful description of the indicator. :param expiration: The date on which the indicator will become inactive. """ raw_res = update_custom_ioc( ioc_id, action, argToList(platforms), severity, source, description, expiration, ) handle_response_errors(raw_res) iocs = raw_res.get('resources', []) ec = [get_trasnformed_dict(iocs[0], IOC_KEY_MAP)] return create_entry_object( contents=raw_res, ec={'CrowdStrike.IOC(val.ID === obj.ID)': ec}, hr=tableToMarkdown('Custom IOC was updated successfully', ec), ) def delete_custom_ioc_command(ioc_id: str) -> dict: """ :param ioc_id: The ID of indicator to delete. """ raw_res = delete_custom_ioc(ioc_id) handle_response_errors(raw_res, "The server has not confirmed deletion, please manually confirm deletion.") return create_entry_object(contents=raw_res, hr=f"Custom IOC {ioc_id} was successfully deleted.") def get_ioc_device_count_command(ioc_type: str, value: str): """ :param ioc_type: The type of the indicator :param value: The IOC value """ raw_res = get_ioc_device_count(ioc_type, value) if 'No results found for' in raw_res: return raw_res else: handle_response_errors(raw_res) device_count_res = raw_res.get('resources') ioc_id = f"{ioc_type}:{value}" if not device_count_res: return create_entry_object(raw_res, hr=f"Could not find any devices the IOC **{ioc_id}** was detected in.") context = [get_trasnformed_dict(device_count, IOC_DEVICE_COUNT_MAP) for device_count in device_count_res] hr = f'Indicator of Compromise **{ioc_id}** device count: **{device_count_res[0].get('device_count')}**' return create_entry_object(contents=raw_res, ec={'CrowdStrike.IOC(val.ID === obj.ID)': context}, hr=hr) def get_process_details_command(ids: str): """ :param ids: proccess ids """ ids = argToList(ids) raw_res = get_process_details(ids) handle_response_errors(raw_res) proc = raw_res.get('resources') if not proc: return create_entry_object(raw_res, hr="Could not find any searched processes.") proc_hr_ids = str(ids)[1:-1].replace('\'', '') title = f"Details for process{"es" if len(ids) > 1 else ""}: {proc_hr_ids}." return create_entry_object(contents=raw_res, hr=tableToMarkdown(title, proc), ec={'CrowdStrike.Process(val.process_id === obj.process_id)': proc}) def get_proccesses_ran_on_command(ioc_type, value, device_id): """ :param device_id: Device id the IOC ran on :param ioc_type: The type of the indicator :param value: The IOC value """ raw_res = get_proccesses_ran_on(ioc_type, value, device_id) handle_response_errors(raw_res) proc_ids = raw_res.get('resources') ioc_id = f"{ioc_type}:{value}" if not proc_ids: return create_entry_object(raw_res, hr=f"Could not find any processes associated with the IOC **{ioc_id}**.") context = {'ID': ioc_id, 'Type': ioc_type, 'Value': value, 'Process': {'DeviceID': device_id, 'ID': proc_ids}} hr = tableToMarkdown(f"Processes with custom IOC {ioc_id} on device {device_id}.", proc_ids, headers="Process ID") return create_entry_object(contents=raw_res, hr=hr, ec={'CrowdStrike.IOC(val.ID === obj.ID)': context}) def search_device_command(): """ Searches for a device :return: EntryObject of search device command """ raw_res = search_device() if not raw_res: return create_entry_object(hr='Could not find any devices.') devices = raw_res.get('resources') command_results = [] for single_device in devices: status, is_isolated = generate_status_fields(single_device.get('status')) endpoint = Common.Endpoint( id=single_device.get('device_id'), hostname=single_device.get('hostname'), ip_address=single_device.get('local_ip'), os=single_device.get('platform_name'), os_version=single_device.get('os_version'), status=status, is_isolated=is_isolated, mac_address=single_device.get('mac_address'), vendor=INTEGRATION_NAME) entry = get_trasnformed_dict(single_device, SEARCH_DEVICE_KEY_MAP) headers = ['ID', 'Hostname', 'OS', 'MacAddress', 'LocalIP', 'ExternalIP', 'FirstSeen', 'LastSeen', 'Status'] command_results.append(CommandResults( outputs_prefix='CrowdStrike.Device', outputs_key_field='ID', outputs=entry, readable_output=tableToMarkdown('Devices', entry, headers=headers, headerTransform=pascalToSpace), raw_response=raw_res, indicator=endpoint, )) return command_results def search_device_by_ip(raw_res, ip_address): devices = raw_res.get('resources') filtered_devices = [] for single_device in devices: if single_device.get('local_ip') == ip_address: filtered_devices.append(single_device) if filtered_devices: raw_res['resources'] = filtered_devices else: raw_res = None return raw_res def generate_status_fields(endpoint_status): status = '' is_isolated = '' if endpoint_status.lower() == 'normal': status = 'Online' elif endpoint_status == 'containment_pending': is_isolated = 'Pending isolation' elif endpoint_status == 'contained': is_isolated = 'Yes' elif endpoint_status == 'lift_containment_pending': is_isolated = 'Pending unisolation' else: raise DemistoException(f'Error: Unknown endpoint status was given: {endpoint_status}') return status, is_isolated def generate_endpoint_by_contex_standard(devices): standard_endpoints = [] for single_device in devices: status, is_isolated = generate_status_fields(single_device.get('status')) endpoint = Common.Endpoint( id=single_device.get('device_id'), hostname=single_device.get('hostname'), ip_address=single_device.get('local_ip'), os=single_device.get('platform_name'), os_version=single_device.get('os_version'), status=status, is_isolated=is_isolated, mac_address=single_device.get('mac_address'), vendor=INTEGRATION_NAME) standard_endpoints.append(endpoint) return standard_endpoints def get_endpoint_command(): args = demisto.args() if 'id' in args.keys(): args['ids'] = args.get('id', '') # handles the search by id or by hostname raw_res = search_device() if ip := args.get('ip') and raw_res: # there is no option to filter by ip in an api call, therefore we would filter the devices in the code raw_res = search_device_by_ip(raw_res, ip) if not ip and not args.get('id') and not args.get('hostname'): # in order not to return all the devices return create_entry_object(hr='Please add a filter argument - ip, hostname or id.') if not raw_res: return create_entry_object(hr='Could not find any devices.') devices = raw_res.get('resources') standard_endpoints = generate_endpoint_by_contex_standard(devices) command_results = [] for endpoint in standard_endpoints: endpoint_context = endpoint.to_context().get(Common.Endpoint.CONTEXT_PATH) hr = tableToMarkdown('CrowdStrike Falcon Endpoint', endpoint_context) command_results.append(CommandResults( readable_output=hr, raw_response=raw_res, indicator=endpoint )) return command_results def get_behavior_command(): """ Gets a behavior by ID :return: EntryObject of get behavior command """ behavior_id = demisto.args().get('behavior_id') detections_ids = demisto.get(get_detections(behavior_id=behavior_id), 'resources') raw_res = get_detections_entities(detections_ids) entries = [] if "resources" in raw_res: for resource in demisto.get(raw_res, "resources"): for behavior in demisto.get(resource, 'behaviors'): entries.append(behavior_to_entry_context(behavior)) hr = tableToMarkdown('Behavior ID: {}'.format(behavior_id), entries, headerTransform=pascalToSpace) # no dt since behavior vary by more than their ID ec = {'CrowdStrike.Behavior': entries} return create_entry_object(contents=raw_res, ec=ec, hr=hr) def search_detections_command(): """ Searches for a detection :return: EntryObject of search detections command """ d_args = demisto.args() detections_ids = argToList(d_args.get('ids')) if not detections_ids: filter_arg = d_args.get('filter') if not filter_arg: return_error('Command Error: Please provide at least one argument.') detections_ids = get_detections(filter_arg=filter_arg).get('resources') raw_res = get_detections_entities(detections_ids) entries = [] headers = ['ID', 'Status', 'System', 'ProcessStartTime', 'CustomerID', 'MaxSeverity'] if "resources" in raw_res: for detection in demisto.get(raw_res, "resources"): detection_entry = {} for path, new_key in DETECTIONS_BASE_KEY_MAP.items(): detection_entry[new_key] = demisto.get(detection, path) behaviors = [] for behavior in demisto.get(detection, 'behaviors'): behaviors.append(behavior_to_entry_context(behavior)) detection_entry['Behavior'] = behaviors entries.append(detection_entry) hr = tableToMarkdown('Detections Found:', entries, headers=headers, removeNull=True, headerTransform=pascalToSpace) ec = {'CrowdStrike.Detection(val.ID === obj.ID)': entries} return create_entry_object(contents=raw_res, ec=ec, hr=hr) def resolve_detection_command(): """ Resolves single or multiple detections :return: EntryObject of resolve detection command """ args = demisto.args() ids = argToList(args.get('ids')) username = args.get('username') assigned_to_uuid = args.get('assigned_to_uuid') comment = args.get('comment') if username and assigned_to_uuid: raise ValueError('Only one of the arguments assigned_to_uuid or username should be provided, not both.') if username: assigned_to_uuid = get_username_uuid(username) status = args.get('status') show_in_ui = args.get('show_in_ui') if not (username or assigned_to_uuid or comment or status or show_in_ui): raise DemistoException("Please provide at least one argument to resolve the detection with.") raw_res = resolve_detection(ids, status, assigned_to_uuid, show_in_ui, comment) args.pop('ids') hr = "Detection {0} updated\n".format(str(ids)[1:-1]) hr += 'With the following values:\n' for k, arg in args.items(): hr += '\t{name}:{val}\n'.format(name=k, val=arg) return create_entry_object(contents=raw_res, hr=hr) def contain_host_command(): """ Contains hosts with user arg ids :return: EntryObject of contain host command """ ids = argToList(demisto.args().get('ids')) raw_res = contain_host(ids) hr = "Host {} contained".format(str(ids)[1:-1]) return create_entry_object(contents=raw_res, hr=hr) def lift_host_containment_command(): """ Lifts containment off a host :return: EntryObject of lift host containment """ ids = argToList(demisto.args().get('ids')) raw_res = lift_host_containment(ids) hr = "Containment has been lift off host {}".format(str(ids)[1:-1]) return create_entry_object(contents=raw_res, hr=hr) def run_command(): args = demisto.args() host_ids = argToList(args.get('host_ids')) command_type = args.get('command_type') full_command = args.get('full_command') scope = args.get('scope', 'read') target = args.get('target', 'batch') output = [] if target == 'batch': batch_id = init_rtr_batch_session(host_ids) timer = Timer(300, batch_refresh_session, kwargs={'batch_id': batch_id}) timer.start() try: if scope == 'read': response = run_batch_read_cmd(batch_id, command_type, full_command) elif scope == 'write': response = run_batch_write_cmd(batch_id, command_type, full_command) else: # scope = admin response = run_batch_admin_cmd(batch_id, command_type, full_command) finally: timer.cancel() resources: dict = response.get('combined', {}).get('resources', {}) for _, resource in resources.items(): errors = resource.get('errors', []) if errors: error_message = errors[0].get('message', '') if not error_message: error_message = f'Could not run command\n{errors}' return_error(error_message) output.append({ 'HostID': resource.get('aid'), 'SessionID': resource.get('session_id'), 'Stdout': resource.get('stdout'), 'Stderr': resource.get('stderr'), 'BaseCommand': resource.get('base_command'), 'Command': full_command }) human_readable = tableToMarkdown(f'Command {full_command} results', output, removeNull=True) entry_context_batch = { 'CrowdStrike': { 'Command': output } } return create_entry_object(contents=response, ec=entry_context_batch, hr=human_readable) else: # target = 'single' responses = [] for host_id in host_ids: if scope == 'read': response1 = run_single_read_cmd(host_id, command_type, full_command) elif scope == 'write': response1 = run_single_write_cmd(host_id, command_type, full_command) else: # scope = admin response1 = run_single_admin_cmd(host_id, command_type, full_command) responses.append(response1) for resource in response1.get('resources', []): errors = resource.get('errors', []) if errors: error_message = errors[0].get('message', '') if not error_message: error_message = f'Could not run command\n{errors}' return_error(error_message) output.append({ 'HostID': host_id, 'TaskID': resource.get('cloud_request_id'), 'SessionID': resource.get('session_id'), 'BaseCommand': command_type, 'Command': full_command, 'Complete': False, 'NextSequenceID': 0 }) human_readable = tableToMarkdown(f'Command {full_command} results', output, removeNull=True) entry_context_single = { 'CrowdStrike.Command(val.TaskID === obj.TaskID)': output } return create_entry_object(contents=responses, ec=entry_context_single, hr=human_readable) def upload_script_command(): args = demisto.args() name = args.get('name') permission_type = args.get('permission_type', 'private') content = args.get('content') entry_id = args.get('entry_id') if content and entry_id: raise ValueError('Only one of the arguments entry_id or content should be provided, not both.') elif not content and not entry_id: raise ValueError('One of the arguments entry_id or content must be provided, none given.') response = upload_script(name, permission_type, content, entry_id) return create_entry_object(contents=response, hr='The script was uploaded successfully') def get_script_command(): script_id = argToList(demisto.args().get('script_id')) response = get_script(script_id) resources: list = response.get('resources', []) if resources and isinstance(resources, list): resource = resources[0] script = { 'ID': resource.get('id'), 'CreatedBy': resource.get('created_by'), 'CreatedTime': resource.get('created_timestamp'), 'Description': resource.get('description'), 'ModifiedBy': resource.get('modified_by'), 'ModifiedTime': resource.get('modified_timestamp'), 'Name': resource.get('name'), 'Permission': resource.get('permission_type'), 'SHA256': resource.get('sha256'), 'RunAttemptCount': resource.get('run_attempt_count'), 'RunSuccessCount': resource.get('run_success_count'), 'WriteAccess': resource.get('write_access') } human_readable = tableToMarkdown(f'CrowdStrike Falcon script {script_id}', script) entry_context = { 'CrowdStrike.Script(val.ID === obj.ID)': script } script_content = resource.get('content') if script_content: demisto.results( fileResult( f"{resource.get("name", "script")}.ps1", script_content ) ) return create_entry_object(contents=response, ec=entry_context, hr=human_readable) else: return 'No script found.' def delete_script_command(): script_id = demisto.args().get('script_id') response = delete_script(script_id) return create_entry_object(contents=response, hr=f'Script {script_id} was deleted successfully') def list_scripts_command(): response = list_scripts() resources: list = response.get('resources', []) scripts = [] for resource in resources: scripts.append({ 'ID': resource.get('id'), 'CreatedBy': resource.get('created_by'), 'CreatedTime': resource.get('created_timestamp'), 'Description': resource.get('description'), 'ModifiedBy': resource.get('modified_by'), 'ModifiedTime': resource.get('modified_timestamp'), 'Name': resource.get('name'), 'Permission': resource.get('permission_type'), 'SHA256': resource.get('sha256'), 'RunAttemptCount': resource.get('run_attempt_count'), 'RunSuccessCount': resource.get('run_success_count'), 'Platform': resource.get('platform'), 'WriteAccess': resource.get('write_access') }) human_readable = tableToMarkdown('CrowdStrike Falcon scripts', scripts) entry_context = { 'CrowdStrike.Script(val.ID === obj.ID)': scripts } return create_entry_object(contents=response, ec=entry_context, hr=human_readable) def upload_file_command(): entry_id = demisto.args().get('entry_id') description = demisto.args().get('description', 'File uploaded from Demisto') response, file_name = upload_file(entry_id, description) return create_entry_object(contents=response, hr='File was uploaded successfully') def delete_file_command(): file_id = demisto.args().get('file_id') response = delete_file(file_id) return create_entry_object(contents=response, hr=f'File {file_id} was deleted successfully') def get_file_command(): file_id = argToList(demisto.args().get('file_id')) response = get_file(file_id) resources: list = response.get('resources', []) if resources and isinstance(resources, list): # will always be a list of one resource resource = resources[0] file_ = { 'ID': resource.get('id'), 'CreatedBy': resource.get('created_by'), 'CreatedTime': resource.get('created_timestamp'), 'Description': resource.get('description'), 'Type': resource.get('file_type'), 'ModifiedBy': resource.get('modified_by'), 'ModifiedTime': resource.get('modified_timestamp'), 'Name': resource.get('name'), 'Permission': resource.get('permission_type'), 'SHA256': resource.get('sha256'), } file_standard_context = { 'Type': resource.get('file_type'), 'Name': resource.get('name'), 'SHA256': resource.get('sha256'), 'Size': resource.get('size'), } human_readable = tableToMarkdown(f'CrowdStrike Falcon file {file_id}', file_) entry_context = { 'CrowdStrike.File(val.ID === obj.ID)': file_, outputPaths['file']: file_standard_context } file_content = resource.get('content') if file_content: demisto.results( fileResult( resource.get('name'), file_content ) ) return create_entry_object(contents=response, ec=entry_context, hr=human_readable) else: return 'No file found.' def list_files_command(): response = list_files() resources: list = response.get('resources', []) files_output = [] file_standard_context = [] for resource in resources: files_output.append({ 'ID': resource.get('id'), 'CreatedBy': resource.get('created_by'), 'CreatedTime': resource.get('created_timestamp'), 'Description': resource.get('description'), 'Type': resource.get('file_type'), 'ModifiedBy': resource.get('modified_by'), 'ModifiedTime': resource.get('modified_timestamp'), 'Name': resource.get('name'), 'Permission': resource.get('permission_type'), 'SHA256': resource.get('sha256'), }) file_standard_context.append({ 'Type': resource.get('file_type'), 'Name': resource.get('name'), 'SHA256': resource.get('sha256'), 'Size': resource.get('size'), }) human_readable = tableToMarkdown('CrowdStrike Falcon files', files_output) entry_context = { 'CrowdStrike.File(val.ID === obj.ID)': files_output, outputPaths['file']: file_standard_context } return create_entry_object(contents=response, ec=entry_context, hr=human_readable) def run_script_command(): args = demisto.args() script_name = args.get('script_name') raw = args.get('raw') host_ids = argToList(args.get('host_ids')) try: timeout = int(args.get('timeout', 30)) except ValueError as e: demisto.error(str(e)) raise ValueError('Timeout argument should be an integer, for example: 30') if script_name and raw: raise ValueError('Only one of the arguments script_name or raw should be provided, not both.') elif not script_name and not raw: raise ValueError('One of the arguments script_name or raw must be provided, none given.') elif script_name: full_command = f'runscript -CloudFile={script_name}' elif raw: full_command = f'runscript -Raw=```{raw}```' full_command += f' -Timeout={timeout}' command_type = 'runscript' batch_id = init_rtr_batch_session(host_ids) timer = Timer(300, batch_refresh_session, kwargs={'batch_id': batch_id}) timer.start() try: response = run_batch_admin_cmd(batch_id, command_type, full_command, timeout) finally: timer.cancel() resources: dict = response.get('combined', {}).get('resources', {}) output = [] for _, resource in resources.items(): errors = resource.get('errors', []) if errors: error_message = errors[0].get('message', '') if not error_message: error_message = f'Could not run command\n{errors}' return_error(error_message) full_command = full_command.replace('`', '') output.append({ 'HostID': resource.get('aid'), 'SessionID': resource.get('session_id'), 'Stdout': resource.get('stdout'), 'Stderr': resource.get('stderr'), 'BaseCommand': resource.get('base_command'), 'Command': full_command }) human_readable = tableToMarkdown(f'Command {full_command} results', output) entry_context = { 'CrowdStrike': { 'Command': output } } return create_entry_object(contents=response, ec=entry_context, hr=human_readable) def run_get_command(): args = demisto.args() host_ids = argToList(args.get('host_ids')) file_path = args.get('file_path') optional_hosts = argToList(args.get('optional_hosts')) timeout = args.get('timeout') timeout_duration = args.get('timeout_duration') timeout = timeout and int(timeout) response = run_batch_get_cmd(host_ids, file_path, optional_hosts, timeout, timeout_duration) resources: dict = response.get('combined', {}).get('resources', {}) output = [] for _, resource in resources.items(): errors = resource.get('errors', []) if errors: error_message = errors[0].get('message', '') if not error_message: error_message = f'Could not get command\n{errors}' return_error(error_message) output.append({ 'HostID': resource.get('aid'), 'Stdout': resource.get('stdout'), 'Stderr': resource.get('stderr'), 'BaseCommand': resource.get('base_command'), 'TaskID': resource.get('task_id'), 'GetRequestID': response.get('batch_get_cmd_req_id'), 'Complete': resource.get('complete') or False, 'FilePath': file_path }) human_readable = tableToMarkdown(f'Get command has requested for a file {file_path}', output) entry_context = { 'CrowdStrike.Command(val.TaskID === obj.TaskID)': output } return create_entry_object(contents=response, ec=entry_context, hr=human_readable) def status_get_command(): args = demisto.args() request_ids = argToList(args.get('request_ids')) timeout = args.get('timeout') timeout_duration = args.get('timeout_duration') timeout = timeout and int(timeout) responses = [] files_output = [] file_standard_context = [] for request_id in request_ids: response = status_get_cmd(request_id, timeout, timeout_duration) responses.append(response) resources: dict = response.get('resources', {}) for _, resource in resources.items(): errors = resource.get('errors', []) if errors: error_message = errors[0].get('message', '') if not error_message: error_message = f'Could not get command\n{errors}' return_error(error_message) files_output.append({ 'ID': resource.get('id'), 'TaskID': resource.get('cloud_request_id'), 'CreatedAt': resource.get('created_at'), 'DeletedAt': resource.get('deleted_at'), 'UpdatedAt': resource.get('updated_at'), 'Name': resource.get('name'), 'Size': resource.get('size'), 'SHA256': resource.get('sha256') }) file_standard_context.append({ 'Name': resource.get('name'), 'SHA256': resource.get('sha256'), 'Size': resource.get('size'), }) human_readable = tableToMarkdown('CrowdStrike Falcon files', files_output) entry_context = { 'CrowdStrike.File(val.ID === obj.ID || val.TaskID === obj.TaskID)': files_output, outputPaths['file']: file_standard_context } if len(responses) == 1: return create_entry_object(contents=responses[0], ec=entry_context, hr=human_readable) else: return create_entry_object(contents=response, ec=entry_context, hr=human_readable) def status_command(): args = demisto.args() request_id = args.get('request_id') sequence_id = args.get('sequence_id') scope = args.get('scope', 'read') sequence_id = None if sequence_id is None else int(sequence_id) if scope == 'read': response = status_read_cmd(request_id, sequence_id) elif scope == 'write': response = status_write_cmd(request_id, sequence_id) else: # scope = admin response = status_admin_cmd(request_id, sequence_id) resources: list = response.get('resources', []) output = [] for resource in resources: errors = resource.get('errors', []) if errors: error_message = errors[0].get('message', '') if not error_message: error_message = f'Could not run command\n{errors}' return_error(error_message) sequence_id = int(resource.get('sequence_id', 0)) output.append({ 'Complete': resource.get('complete') or False, 'Stdout': resource.get('stdout'), 'Stderr': resource.get('stderr'), 'BaseCommand': resource.get('base_command'), 'TaskID': resource.get('task_id'), 'SequenceID': sequence_id, 'NextSequenceID': sequence_id + 1 }) human_readable = tableToMarkdown('Command status results', output, removeNull=True) entry_context = { 'CrowdStrike.Command(val.TaskID === obj.TaskID)': output } return create_entry_object(contents=response, ec=entry_context, hr=human_readable) def get_extracted_file_command(): args = demisto.args() host_id = args.get('host_id') sha256 = args.get('sha256') filename = args.get('filename') response = get_extracted_file(host_id, sha256, filename) # save an extracted file content_type = response.headers.get('Content-Type', '').lower() if content_type == 'application/x-7z-compressed': content_disposition = response.headers.get('Content-Disposition', '').lower() if content_disposition: filename = email.message_from_string(f'Content-Disposition: {content_disposition}\n\n').get_filename() if not filename: sha256 = sha256 or hashlib.sha256(response.content).hexdigest() filename = sha256.lower() + '.7z' return fileResult(filename, response.content) return_error('An extracted file is missing in the response') def list_host_files_command(): args = demisto.args() host_id = args.get('host_id') response = list_host_files(host_id) resources: list = response.get('resources', []) files_output = [] file_standard_context = [] command_output = [] for resource in resources: errors = resource.get('errors', []) if errors: error_message = errors[0].get('message', '') if not error_message: error_message = f'Could not run command\n{errors}' return_error(error_message) command_output.append({ 'HostID': host_id, 'TaskID': resource.get('cloud_request_id'), 'SessionID': resource.get('session_id') }) files_output.append({ 'ID': resource.get('id'), 'CreatedAt': resource.get('created_at'), 'DeletedAt': resource.get('deleted_at'), 'UpdatedAt': resource.get('updated_at'), 'Name': resource.get('name'), 'SHA256': resource.get('sha256'), 'Size': resource.get('size'), 'Stdout': resource.get('stdout'), 'Stderr': resource.get('stderr') }) file_standard_context.append({ 'Name': resource.get('name'), 'SHA256': resource.get('sha256'), 'Size': resource.get('size'), }) if files_output: human_readable = tableToMarkdown('CrowdStrike Falcon files', files_output) else: human_readable = 'No result found' entry_context = { 'CrowdStrike.Command(val.TaskID === obj.TaskID)': command_output, 'CrowdStrike.File(val.ID === obj.ID)': files_output, outputPaths['file']: file_standard_context } return create_entry_object(contents=response, ec=entry_context, hr=human_readable) def refresh_session_command(): args = demisto.args() host_id = args.get('host_id') response = refresh_session(host_id) resources: list = response.get('resources', []) session_id = None for resource in resources: errors = resource.get('errors', []) if errors: error_message = errors[0].get('message', '') if not error_message: error_message = f'Could not run command\n{errors}' return_error(error_message) session_id = resource.get('session_id') return create_entry_object(contents=response, hr=f'CrowdStrike Session Refreshed: {session_id}') def build_error_message(raw_res): if raw_res.get('errors'): error_data = raw_res.get('errors')[0] else: error_data = {"code": 'None', "message": 'something got wrong, please try again'} error_code = error_data.get('code') error_message = error_data.get('message') return f'Error: error code: {error_code}, error_message: {error_message}.' def validate_response(raw_res): return 'resources' in raw_res.keys() def get_indicator_device_id(): args = demisto.args() ioc_type = args.get('type') ioc_value = args.get('value') params = assign_params( type=ioc_type, value=ioc_value ) raw_res = http_request('GET', '/indicators/queries/devices/v1', params=params, status_code=404) errors = raw_res.get('errors', []) for error in errors: if error.get('code') == 404: return f'No results found for {ioc_type} - {ioc_value}' context_output = '' if validate_response(raw_res): context_output = raw_res.get('resources') else: error_message = build_error_message(raw_res) return_error(error_message) ioc_id = f"{ioc_type}:{ioc_value}" readable_output = tableToMarkdown(f"Devices that encountered the IOC {ioc_id}", context_output, headers='Device ID') return CommandResults( readable_output=readable_output, outputs_prefix='CrowdStrike.DeviceID', outputs_key_field='DeviceID', outputs=context_output, raw_response=raw_res ) def detections_to_human_readable(detections): detections_readable_outputs = [] for detection in detections: readable_output = assign_params(status=detection.get('status'), max_severity=detection.get('max_severity_displayname'), detection_id=detection.get('detection_id'), created_time=detection.get('created_timestamp')) detections_readable_outputs.append(readable_output) headers = ['detection_id', 'created_time', 'status', 'max_severity'] human_readable = tableToMarkdown('CrowdStrike Detections', detections_readable_outputs, headers, removeNull=True) return human_readable def list_detection_summaries_command(): args = demisto.args() fetch_query = args.get('fetch_query') args_ids = args.get('ids') if args_ids: detections_ids = argToList(args_ids) elif fetch_query: fetch_query = "{query}".format(query=fetch_query) detections_ids = demisto.get(get_fetch_detections(filter_arg=fetch_query), 'resources') else: detections_ids = demisto.get(get_fetch_detections(), 'resources') detections_response_data = get_detections_entities(detections_ids) detections = [resource for resource in detections_response_data.get('resources')] detections_human_readable = detections_to_human_readable(detections) return CommandResults( readable_output=detections_human_readable, outputs_prefix='CrowdStrike.Detections', outputs_key_field='detection_id', outputs=detections ) def incidents_to_human_readable(incidents): incidents_readable_outputs = [] for incident in incidents: readable_output = assign_params(description=incident.get('description'), state=incident.get('state'), name=incident.get('name'), tags=incident.get('tags'), incident_id=incident.get('incident_id'), created_time=incident.get('created'), status=STATUS_NUM_TO_TEXT.get(incident.get('status'))) incidents_readable_outputs.append(readable_output) headers = ['incident_id', 'created_time', 'name', 'description', 'status', 'state', 'tags'] human_readable = tableToMarkdown('CrowdStrike Incidents', incidents_readable_outputs, headers, removeNull=True) return human_readable def list_incident_summaries_command(): args = demisto.args() fetch_query = args.get('fetch_query') args_ids = args.get('ids') if args_ids: ids = argToList(args_ids) else: if fetch_query: fetch_query = "{query}".format(query=fetch_query) incidents_ids = get_incidents_ids(filter_arg=fetch_query) else: incidents_ids = get_incidents_ids() handle_response_errors(incidents_ids) ids = incidents_ids.get('resources') if not ids: return CommandResults(readable_output='No incidents were found.') incidents_response_data = get_incidents_entities(ids) incidents = [resource for resource in incidents_response_data.get('resources')] incidents_human_readable = incidents_to_human_readable(incidents) return CommandResults( readable_output=incidents_human_readable, outputs_prefix='CrowdStrike.Incidents', outputs_key_field='incident_id', outputs=incidents ) def create_host_group_command(name: str, group_type: str = None, description: str = None, assignment_rule: str = None) -> CommandResults: response = change_host_group(is_post=True, name=name, group_type=group_type, description=description, assignment_rule=assignment_rule) host_groups = response.get('resources') return CommandResults(outputs_prefix='CrowdStrike.HostGroup', outputs_key_field='id', outputs=host_groups, readable_output=tableToMarkdown('Host Groups', host_groups, headers=HOST_GROUP_HEADERS), raw_response=response) def update_host_group_command(host_group_id: str, name: Optional[str] = None, description: Optional[str] = None, assignment_rule: Optional[str] = None) -> CommandResults: response = change_host_group(is_post=False, host_group_id=host_group_id, name=name, description=description, assignment_rule=assignment_rule) host_groups = response.get('resources') return CommandResults(outputs_prefix='CrowdStrike.HostGroup', outputs_key_field='id', outputs=host_groups, readable_output=tableToMarkdown('Host Groups', host_groups, headers=HOST_GROUP_HEADERS), raw_response=response) def list_host_group_members_command(host_group_id: Optional[str] = None, filter: Optional[str] = None, offset: Optional[str] = None, limit: Optional[str] = None) -> CommandResults: response = host_group_members(filter, host_group_id, limit, offset) devices = response.get('resources') if not devices: return CommandResults(readable_output='No hosts are found', raw_response=response) headers = list(SEARCH_DEVICE_KEY_MAP.values()) outputs = [get_trasnformed_dict(single_device, SEARCH_DEVICE_KEY_MAP) for single_device in devices] return CommandResults( outputs_prefix='CrowdStrike.Device', outputs_key_field='ID', outputs=outputs, readable_output=tableToMarkdown('Devices', outputs, headers=headers, headerTransform=pascalToSpace), raw_response=response ) def add_host_group_members_command(host_group_id: str, host_ids: List[str]) -> CommandResults: response = change_host_group_members(action_name='add-hosts', host_group_id=host_group_id, host_ids=host_ids) host_groups = response.get('resources') return CommandResults(outputs_prefix='CrowdStrike.HostGroup', outputs_key_field='id', outputs=host_groups, readable_output=tableToMarkdown('Host Groups', host_groups, headers=HOST_GROUP_HEADERS), raw_response=response) def remove_host_group_members_command(host_group_id: str, host_ids: List[str]) -> CommandResults: response = change_host_group_members(action_name='remove-hosts', host_group_id=host_group_id, host_ids=host_ids) host_groups = response.get('resources') return CommandResults(outputs_prefix='CrowdStrike.HostGroup', outputs_key_field='id', outputs=host_groups, readable_output=tableToMarkdown('Host Groups', host_groups, headers=HOST_GROUP_HEADERS), raw_response=response) def resolve_incident_command(ids: List[str], status: str): resolve_incident(ids, status) readable = '\n'.join([f'{incident_id} changed successfully to {status}' for incident_id in ids]) return CommandResults(readable_output=readable) def list_host_groups_command(filter: Optional[str] = None, offset: Optional[str] = None, limit: Optional[str] = None) \ -> CommandResults: response = list_host_groups(filter, limit, offset) host_groups = response.get('resources') return CommandResults(outputs_prefix='CrowdStrike.HostGroup', outputs_key_field='id', outputs=host_groups, readable_output=tableToMarkdown('Host Groups', host_groups, headers=HOST_GROUP_HEADERS), raw_response=response) def delete_host_groups_command(host_group_ids: List[str]) -> CommandResults: response = delete_host_groups(host_group_ids) deleted_ids = response.get('resources') readable = '\n'.join([f'Host groups {host_group_id} deleted successfully' for host_group_id in deleted_ids]) \ if deleted_ids else f'Host groups {host_group_ids} are not deleted' return CommandResults(readable_output=readable, raw_response=response) def test_module(): try: get_token(new_token=True) except ValueError: return 'Connection Error: The URL or The API key you entered is probably incorrect, please try again.' if demisto.params().get('isFetch'): try: fetch_incidents() except ValueError: return 'Error: Something is wrong with the filters you entered for the fetch incident, please try again.' return 'ok' ''' COMMANDS MANAGER / SWITCH PANEL ''' LOG('Command being called is {}'.format(demisto.command())) def main(): command = demisto.command() args = demisto.args() try: if command == 'test-module': result = test_module() return_results(result) elif command == 'fetch-incidents': demisto.incidents(fetch_incidents()) elif command in ('cs-device-ran-on', 'cs-falcon-device-ran-on'): return_results(get_indicator_device_id()) elif demisto.command() == 'cs-falcon-search-device': return_results(search_device_command()) elif command == 'cs-falcon-get-behavior': demisto.results(get_behavior_command()) elif command == 'cs-falcon-search-detection': demisto.results(search_detections_command()) elif command == 'cs-falcon-resolve-detection': demisto.results(resolve_detection_command()) elif command == 'cs-falcon-contain-host': demisto.results(contain_host_command()) elif command == 'cs-falcon-lift-host-containment': demisto.results(lift_host_containment_command()) elif command == 'cs-falcon-run-command': demisto.results(run_command()) elif command == 'cs-falcon-upload-script': demisto.results(upload_script_command()) elif command == 'cs-falcon-get-script': demisto.results(get_script_command()) elif command == 'cs-falcon-delete-script': demisto.results(delete_script_command()) elif command == 'cs-falcon-list-scripts': demisto.results(list_scripts_command()) elif command == 'cs-falcon-upload-file': demisto.results(upload_file_command()) elif command == 'cs-falcon-delete-file': demisto.results(delete_file_command()) elif command == 'cs-falcon-get-file': demisto.results(get_file_command()) elif command == 'cs-falcon-list-files': demisto.results(list_files_command()) elif command == 'cs-falcon-run-script': demisto.results(run_script_command()) elif command == 'cs-falcon-run-get-command': demisto.results(run_get_command()) elif command == 'cs-falcon-status-get-command': demisto.results(status_get_command()) elif command == 'cs-falcon-status-command': demisto.results(status_command()) elif command == 'cs-falcon-get-extracted-file': demisto.results(get_extracted_file_command()) elif command == 'cs-falcon-list-host-files': demisto.results(list_host_files_command()) elif command == 'cs-falcon-refresh-session': demisto.results(refresh_session_command()) elif command == 'cs-falcon-list-detection-summaries': return_results(list_detection_summaries_command()) elif command == 'cs-falcon-list-incident-summaries': return_results(list_incident_summaries_command()) elif command == 'cs-falcon-search-iocs': return_results(search_iocs_command(**args)) elif command == 'cs-falcon-get-ioc': return_results(get_ioc_command(ioc_type=args.get('type'), value=args.get('value'))) elif command == 'cs-falcon-upload-ioc': return_results(upload_ioc_command(**args)) elif command == 'cs-falcon-update-ioc': return_results(update_ioc_command(**args)) elif command == 'cs-falcon-delete-ioc': return_results(delete_ioc_command(ioc_type=args.get('type'), value=args.get('value'))) elif command == 'cs-falcon-search-custom-iocs': return_results(search_custom_iocs_command(**args)) elif command == 'cs-falcon-get-custom-ioc': return_results(get_custom_ioc_command( ioc_type=args.get('type'), value=args.get('value'), ioc_id=args.get('ioc_id'))) elif command == 'cs-falcon-upload-custom-ioc': return_results(upload_custom_ioc_command(**args)) elif command == 'cs-falcon-update-custom-ioc': return_results(update_custom_ioc_command(**args)) elif command == 'cs-falcon-delete-custom-ioc': return_results(delete_custom_ioc_command(ioc_id=args.get('ioc_id'))) elif command == 'cs-falcon-device-count-ioc': return_results(get_ioc_device_count_command(ioc_type=args.get('type'), value=args.get('value'))) elif command == 'cs-falcon-process-details': return_results(get_process_details_command(**args)) elif command == 'cs-falcon-processes-ran-on': return_results( get_proccesses_ran_on_command( ioc_type=args.get('type'), value=args.get('value'), device_id=args.get('device_id') ) ) elif command == 'endpoint': return_results(get_endpoint_command()) elif command == 'cs-falcon-create-host-group': return_results(create_host_group_command(**args)) elif command == 'cs-falcon-update-host-group': return_results(update_host_group_command(**args)) elif command == 'cs-falcon-list-host-groups': return_results(list_host_groups_command(**args)) elif command == 'cs-falcon-delete-host-groups': return_results(delete_host_groups_command(host_group_ids=argToList(args.get('host_group_id')))) elif command == 'cs-falcon-list-host-group-members': return_results(list_host_group_members_command(**args)) elif command == 'cs-falcon-add-host-group-members': return_results(add_host_group_members_command(host_group_id=args.get('host_group_id'), host_ids=argToList(args.get('host_ids')))) elif command == 'cs-falcon-remove-host-group-members': return_results(remove_host_group_members_command(host_group_id=args.get('host_group_id'), host_ids=argToList(args.get('host_ids')))) elif command == 'cs-falcon-resolve-incident': return_results(resolve_incident_command(status=args.get('status'), ids=argToList(args.get('ids')))) else: raise NotImplementedError(f'CrowdStrike Falcon error: ' f'command {command} is not implemented') except Exception as e: return_error(str(e)) if __name__ in ('__main__', 'builtin', 'builtins'): main()
import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * ''' IMPORTS ''' import json import requests import base64 import email import hashlib from typing import List from dateutil.parser import parse from typing import Dict, Tuple, Any, Optional, Union from threading import Timer # Disable insecure warnings requests.packages.urllib3.disable_warnings() ''' GLOBALS/PARAMS ''' INTEGRATION_NAME = 'CrowdStrike Falcon' CLIENT_ID = demisto.params().get('client_id') SECRET = demisto.params().get('secret') # Remove trailing slash to prevent wrong URL path to service SERVER = demisto.params()['url'][:-1] if (demisto.params()['url'] and demisto.params()['url'].endswith('/')) else \ demisto.params()['url'] # Should we use SSL USE_SSL = not demisto.params().get('insecure', False) # How many time before the first fetch to retrieve incidents FETCH_TIME = demisto.params().get('fetch_time', '3 days') BYTE_CREDS = '{name}:{password}'.format(name=CLIENT_ID, password=SECRET).encode('utf-8') # Headers to be sent in requests HEADERS = { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': 'Basic {}'.format(base64.b64encode(BYTE_CREDS).decode()) } # Note: True life time of token is actually 30 mins TOKEN_LIFE_TIME = 28 INCIDENTS_PER_FETCH = int(demisto.params().get('incidents_per_fetch', 15)) # Remove proxy if not set to true in params handle_proxy() ''' KEY DICTIONARY ''' DETECTIONS_BASE_KEY_MAP = { 'device.hostname': 'System', 'device.cid': 'CustomerID', 'hostinfo.domain': 'MachineDomain', 'detection_id': 'ID', 'created_timestamp': 'ProcessStartTime', 'max_severity': 'MaxSeverity', 'show_in_ui': 'ShowInUi', 'status': 'Status' } DETECTIONS_BEHAVIORS_KEY_MAP = { 'filename': 'FileName', 'scenario': 'Scenario', 'md5': 'MD5', 'sha256': 'SHA256', 'ioc_type': 'IOCType', 'ioc_value': 'IOCValue', 'cmdline': 'CommandLine', 'user_name': 'UserName', 'behavior_id': 'ID', } IOC_KEY_MAP = { 'type': 'Type', 'value': 'Value', 'policy': 'Policy', 'source': 'Source', 'share_level': 'ShareLevel', 'expiration': 'Expiration', 'description': 'Description', 'created_on': 'CreatedTime', 'created_by': 'CreatedBy', 'modified_on': 'ModifiedTime', 'modified_by': 'ModifiedBy', 'id': 'ID', 'platforms': 'Platforms', 'action': 'Action', 'severity': 'Severity', 'tags': 'Tags', } IOC_DEVICE_COUNT_MAP = { 'id': 'ID', 'type': 'Type', 'value': 'Value', 'device_count': 'DeviceCount' } SEARCH_DEVICE_KEY_MAP = { 'device_id': 'ID', 'external_ip': 'ExternalIP', 'local_ip': 'LocalIP', 'hostname': 'Hostname', 'os_version': 'OS', 'mac_address': 'MacAddress', 'first_seen': 'FirstSeen', 'last_seen': 'LastSeen', 'status': 'Status', } ENDPOINT_KEY_MAP = { 'device_id': 'ID', 'local_ip': 'IPAddress', 'os_version': 'OS', 'hostname': 'Hostname', 'status': 'Status', } ''' SPLIT KEY DICTIONARY ''' """ Pattern: { 'Path': 'Path to item', 'NewKey': 'Value of output key', 'Delim': 'Delimiter char', 'Index': Split Array Index } """ DETECTIONS_BEHAVIORS_SPLIT_KEY_MAP = [ { 'Path': 'parent_details.parent_process_graph_id', 'NewKey': 'SensorID', 'Delim': ':', 'Index': 1 }, { 'Path': 'parent_details.parent_process_graph_id', 'NewKey': 'ParentProcessID', 'Delim': ':', 'Index': 2 }, { 'Path': 'triggering_process_graph_id', 'NewKey': 'ProcessID', 'Delim': ':', 'Index': 2 }, ] HOST_GROUP_HEADERS = ['id', 'name', 'group_type', 'description', 'assignment_rule', 'created_by', 'created_timestamp', 'modified_by', 'modified_timestamp'] STATUS_TEXT_TO_NUM = {'New': "20", 'Reopened': "25", 'In Progress': "30", 'Closed': "40"} STATUS_NUM_TO_TEXT = {20: 'New', 25: 'Reopened', 30: 'In Progress', 40: 'Closed'} ''' HELPER FUNCTIONS ''' def http_request(method, url_suffix, params=None, data=None, files=None, headers=HEADERS, safe=False, get_token_flag=True, no_json=False, json=None, status_code=None): """ A wrapper for requests lib to send our requests and handle requests and responses better. :param json: JSON body :type json ``dict`` or ``list`` :type method: ``str`` :param method: HTTP method for the request. :type url_suffix: ``str`` :param url_suffix: The suffix of the URL (endpoint) :type params: ``dict`` :param params: The URL params to be passed. :type data: ``str`` :param data: The body data of the request. :type headers: ``dict`` :param headers: Request headers :type safe: ``bool`` :param safe: If set to true will return None in case of http error :type get_token_flag: ``bool`` :param get_token_flag: If set to True will call get_token() :type no_json: ``bool`` :param no_json: If set to true will not parse the content and will return the raw response object for successful response :type status_code: ``int`` :param: status_code: The request codes to accept as OK. :return: Returns the http request response json :rtype: ``dict`` """ if get_token_flag: token = get_token() headers['Authorization'] = 'Bearer {}'.format(token) url = SERVER + url_suffix try: res = requests.request( method, url, verify=USE_SSL, params=params, data=data, headers=headers, files=files, json=json, ) except requests.exceptions.RequestException as e: return_error(f'Error in connection to the server. Please make sure you entered the URL correctly.' f' Exception is {str(e)}.') try: valid_status_codes = {200, 201, 202, 204} # Handling a case when we want to return an entry for 404 status code. if status_code: valid_status_codes.add(status_code) if res.status_code not in valid_status_codes: res_json = res.json() reason = res.reason resources = res_json.get('resources', {}) if resources: if isinstance(resources, list): reason += f'\n{str(resources)}' else: for host_id, resource in resources.items(): errors = resource.get('errors', []) if errors: error_message = errors[0].get('message') reason += f'\nHost ID {host_id} - {error_message}' elif res_json.get('errors'): errors = res_json.get('errors', []) for error in errors: reason += f"\n{error.get('message')}" err_msg = 'Error in API call to CrowdStrike Falcon: code: {code} - reason: {reason}'.format( code=res.status_code, reason=reason ) # try to create a new token if res.status_code == 403 and get_token_flag: LOG(err_msg) token = get_token(new_token=True) headers['Authorization'] = 'Bearer {}'.format(token) return http_request( method=method, url_suffix=url_suffix, params=params, data=data, headers=headers, files=files, json=json, safe=safe, get_token_flag=False, status_code=status_code, no_json=no_json, ) elif safe: return None return_error(err_msg) return res if no_json else res.json() except ValueError as exception: raise ValueError( f'Failed to parse json object from response: {exception} - {res.content}') # type: ignore[str-bytes-safe] def create_entry_object(contents: Union[List[Any], Dict[str, Any]] = {}, ec: Union[List[Any], Dict[str, Any]] = None, hr: str = ''): """ Creates an entry object :type contents: ``dict`` :param contents: Raw response to output :type ec: ``dict`` :param ec: Entry context of the entry object :type hr: ``str`` :param hr: Human readable :return: Entry object :rtype: ``dict`` """ return { 'Type': entryTypes['note'], 'Contents': contents, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': hr, 'EntryContext': ec } def detection_to_incident(detection): """ Creates an incident of a detection. :type detection: ``dict`` :param detection: Single detection object :return: Incident representation of a detection :rtype ``dict`` """ incident = { 'name': 'Detection ID: ' + str(detection.get('detection_id')), 'occurred': str(detection.get('created_timestamp')), 'rawJSON': json.dumps(detection), 'severity': severity_string_to_int(detection.get('max_severity_displayname')) } return incident def incident_to_incident_context(incident): """ Creates an incident context of a incident. :type incident: ``dict`` :param incident: Single detection object :return: Incident context representation of a incident :rtype ``dict`` """ incident_id = str(incident.get('incident_id')) incident_context = { 'name': f'Incident ID: {incident_id}', 'occurred': str(incident.get('start')), 'rawJSON': json.dumps(incident) } return incident_context def severity_string_to_int(severity): """ Converts a severity string to DBot score representation :type severity: ``str`` :param severity: String representation of a severity :return: DBot score representation of the severity :rtype ``int`` """ if severity in ('Critical', 'High'): return 3 elif severity in ('Medium', 'Low'): return 2 return 0 def get_trasnformed_dict(old_dict, transformation_dict): """ Returns a dictionary with the same values as old_dict, with the correlating key:value in transformation_dict :type old_dict: ``dict`` :param old_dict: Old dictionary to pull values from :type transformation_dict: ``dict`` :param transformation_dict: Transformation dictionary that contains oldkeys:newkeys :return Transformed dictionart (according to transformation_dict values) :rtype ``dict`` """ new_dict = {} for k in list(old_dict.keys()): if k in transformation_dict: new_dict[transformation_dict[k]] = old_dict[k] return new_dict def extract_transformed_dict_with_split(old_dict, transformation_dict_arr): """ Extracts new values out of old_dict using a json structure of: {'Path': 'Path to item', 'NewKey': 'Value of output key', 'Delim': 'Delimiter char', 'Index': Split Array Index} """ new_dict = {} for trans_dict in transformation_dict_arr: try: val = demisto.get(old_dict, trans_dict['Path']) if 'split' in dir(val): i = trans_dict['Index'] new_dict[trans_dict['NewKey']] = val.split(trans_dict['Delim'])[i] except Exception as ex: LOG('Error {exception} with: {tdict}'.format(exception=ex, tdict=trans_dict)) return new_dict def get_passed_mins(start_time, end_time_str): """ Returns the time passed in mins :param start_time: Start time in datetime :param end_time_str: End time in str :return: The passed mins in int """ time_delta = start_time - datetime.fromtimestamp(end_time_str) return time_delta.seconds / 60 def handle_response_errors(raw_res: dict, err_msg: str = None): """ Raise exception if raw_res is empty or contains errors """ if not err_msg: err_msg = "The server was unable to return a result, please run the command again." if not raw_res: raise DemistoException(err_msg) if raw_res.get('errors'): raise DemistoException(raw_res.get('errors')) return ''' COMMAND SPECIFIC FUNCTIONS ''' def init_rtr_single_session(host_id: str) -> str: """ Start a session with single host. :param host_id: Host agent ID to initialize a RTR session on. :return: The session ID to execute the command on """ endpoint_url = '/real-time-response/entities/sessions/v1' body = json.dumps({ 'device_id': host_id }) response = http_request('POST', endpoint_url, data=body) resources = response.get('resources') if resources and isinstance(resources, list) and isinstance(resources[0], dict): session_id = resources[0].get('session_id') if isinstance(session_id, str): return session_id raise ValueError('No session id found in the response') def init_rtr_batch_session(host_ids: list) -> str: """ Start a session with one or more hosts :param host_ids: List of host agent ID’s to initialize a RTR session on. :return: The session batch ID to execute the command on """ endpoint_url = '/real-time-response/combined/batch-init-session/v1' body = json.dumps({ 'host_ids': host_ids }) response = http_request('POST', endpoint_url, data=body) return response.get('batch_id') def refresh_session(host_id: str) -> Dict: """ Refresh a session timeout on a single host. :param host_id: Host agent ID to run RTR command on. :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/entities/refresh-session/v1' body = json.dumps({ 'device_id': host_id }) response = http_request('POST', endpoint_url, data=body) return response def batch_refresh_session(batch_id: str) -> None: """ Batch refresh a RTR session on multiple hosts. :param batch_id: Batch ID to execute the command on. """ demisto.debug('Starting session refresh') endpoint_url = '/real-time-response/combined/batch-refresh-session/v1' body = json.dumps({ 'batch_id': batch_id }) response = http_request('POST', endpoint_url, data=body) demisto.debug(f'Refresh session response: {response}') demisto.debug('Finished session refresh') def run_batch_read_cmd(batch_id: str, command_type: str, full_command: str) -> Dict: """ Sends RTR command scope with read access :param batch_id: Batch ID to execute the command on. :param command_type: Read-only command type we are going to execute, for example: ls or cd. :param full_command: Full command string for the command. :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/combined/batch-command/v1' body = json.dumps({ 'base_command': command_type, 'batch_id': batch_id, 'command_string': full_command }) response = http_request('POST', endpoint_url, data=body) return response def run_batch_write_cmd(batch_id: str, command_type: str, full_command: str) -> Dict: """ Sends RTR command scope with write access :param batch_id: Batch ID to execute the command on. :param command_type: Read-only command type we are going to execute, for example: ls or cd. :param full_command: Full command string for the command. :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/combined/batch-active-responder-command/v1' body = json.dumps({ 'base_command': command_type, 'batch_id': batch_id, 'command_string': full_command }) response = http_request('POST', endpoint_url, data=body) return response def run_batch_admin_cmd(batch_id: str, command_type: str, full_command: str, timeout: int = 30) -> Dict: """ Sends RTR command scope with write access :param batch_id: Batch ID to execute the command on. :param command_type: Read-only command type we are going to execute, for example: ls or cd. :param full_command: Full command string for the command. :param timeout: Timeout for how long to wait for the request in seconds. :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/combined/batch-admin-command/v1' params = { 'timeout': timeout } body = json.dumps({ 'base_command': command_type, 'batch_id': batch_id, 'command_string': full_command }) response = http_request('POST', endpoint_url, data=body, params=params) return response def run_batch_get_cmd(host_ids: list, file_path: str, optional_hosts: list = None, timeout: int = None, timeout_duration: str = None) -> Dict: """ Batch executes `get` command across hosts to retrieve files. After this call is made `/real-time-response/combined/batch-get-command/v1` is used to query for the results. :param host_ids: List of host agent ID’s to run RTR command on. :param file_path: Full path to the file that is to be retrieved from each host in the batch. :param optional_hosts: List of a subset of hosts we want to run the command on. If this list is supplied, only these hosts will receive the command. :param timeout: Timeout for how long to wait for the request in seconds :param timeout_duration: Timeout duration for for how long to wait for the request in duration syntax :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/combined/batch-get-command/v1' batch_id = init_rtr_batch_session(host_ids) body = assign_params(batch_id=batch_id, file_path=file_path, optional_hosts=optional_hosts) params = assign_params(timeout=timeout, timeout_duration=timeout_duration) response = http_request('POST', endpoint_url, data=json.dumps(body), params=params) return response def status_get_cmd(request_id: str, timeout: int = None, timeout_duration: str = None) -> Dict: """ Retrieves the status of the specified batch get command. Will return successful files when they are finished processing. :param request_id: ID to the request of `get` command. :param timeout: Timeout for how long to wait for the request in seconds :param timeout_duration: Timeout duration for for how long to wait for the request in duration syntax :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/combined/batch-get-command/v1' params = assign_params(timeout=timeout, timeout_duration=timeout_duration, batch_get_cmd_req_id=request_id) response = http_request('GET', endpoint_url, params=params) return response def run_single_read_cmd(host_id: str, command_type: str, full_command: str) -> Dict: """ Sends RTR command scope with read access :param host_id: Host agent ID to run RTR command on. :param command_type: Active-Responder command type we are going to execute, for example: get or cp. :param full_command: Full command string for the command. :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/entities/command/v1' session_id = init_rtr_single_session(host_id) body = json.dumps({ 'base_command': command_type, 'command_string': full_command, 'session_id': session_id }) response = http_request('POST', endpoint_url, data=body) return response def run_single_write_cmd(host_id: str, command_type: str, full_command: str) -> Dict: """ Sends RTR command scope with write access :param host_id: Host agent ID to run RTR command on. :param command_type: Active-Responder command type we are going to execute, for example: get or cp. :param full_command: Full command string for the command. :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/entities/active-responder-command/v1' session_id = init_rtr_single_session(host_id) body = json.dumps({ 'base_command': command_type, 'command_string': full_command, 'session_id': session_id }) response = http_request('POST', endpoint_url, data=body) return response def run_single_admin_cmd(host_id: str, command_type: str, full_command: str) -> Dict: """ Sends RTR command scope with admin access :param host_id: Host agent ID to run RTR command on. :param command_type: Active-Responder command type we are going to execute, for example: get or cp. :param full_command: Full command string for the command. :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/entities/admin-command/v1' session_id = init_rtr_single_session(host_id) body = json.dumps({ 'base_command': command_type, 'command_string': full_command, 'session_id': session_id }) response = http_request('POST', endpoint_url, data=body) return response def status_read_cmd(request_id: str, sequence_id: Optional[int]) -> Dict: """ Get status of an executed command with read access on a single host. :param request_id: Cloud Request ID of the executed command to query :param sequence_id: Sequence ID that we want to retrieve. Command responses are chunked across sequences """ endpoint_url = '/real-time-response/entities/command/v1' params = { 'cloud_request_id': request_id, 'sequence_id': sequence_id or 0 } response = http_request('GET', endpoint_url, params=params) return response def status_write_cmd(request_id: str, sequence_id: Optional[int]) -> Dict: """ Get status of an executed command with write access on a single host. :param request_id: Cloud Request ID of the executed command to query :param sequence_id: Sequence ID that we want to retrieve. Command responses are chunked across sequences """ endpoint_url = '/real-time-response/entities/active-responder-command/v1' params = { 'cloud_request_id': request_id, 'sequence_id': sequence_id or 0 } response = http_request('GET', endpoint_url, params=params) return response def status_admin_cmd(request_id: str, sequence_id: Optional[int]) -> Dict: """ Get status of an executed command with admin access on a single host. :param request_id: Cloud Request ID of the executed command to query :param sequence_id: Sequence ID that we want to retrieve. Command responses are chunked across sequences """ endpoint_url = '/real-time-response/entities/admin-command/v1' params = { 'cloud_request_id': request_id, 'sequence_id': sequence_id or 0 } response = http_request('GET', endpoint_url, params=params) return response def list_host_files(host_id: str) -> Dict: """ Get a list of files for the specified RTR session on a host. :param host_id: Host agent ID to run RTR command on. :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/entities/file/v1' session_id = init_rtr_single_session(host_id) params = { 'session_id': session_id } response = http_request('GET', endpoint_url, params=params) return response def upload_script(name: str, permission_type: str, content: str, entry_id: str) -> Dict: """ Uploads a script by either given content or file :param name: Script name to upload :param permission_type: Permissions type of script to upload :param content: PowerShell script content :param entry_id: Script file to upload :return: Response JSON which contains errors (if exist) and how many resources were affected """ endpoint_url = '/real-time-response/entities/scripts/v1' body: Dict[str, Tuple[Any, Any]] = { 'name': (None, name), 'permission_type': (None, permission_type) } temp_file = None try: if content: body['content'] = (None, content) else: # entry_id was provided file_ = demisto.getFilePath(entry_id) file_name = file_.get('name') # pylint: disable=E1101 temp_file = open(file_.get('path'), 'rb') # pylint: disable=E1101 body['file'] = (file_name, temp_file) headers = { 'Authorization': HEADERS['Authorization'], 'Accept': 'application/json' } response = http_request('POST', endpoint_url, files=body, headers=headers) return response finally: if temp_file: temp_file.close() def get_script(script_id: list) -> Dict: """ Retrieves a script given its ID :param script_id: ID of script to get :return: Response JSON which contains errors (if exist) and retrieved resource """ endpoint_url = '/real-time-response/entities/scripts/v1' params = { 'ids': script_id } response = http_request('GET', endpoint_url, params=params) return response def delete_script(script_id: str) -> Dict: """ Deletes a script given its ID :param script_id: ID of script to delete :return: Response JSON which contains errors (if exist) and how many resources were affected """ endpoint_url = '/real-time-response/entities/scripts/v1' params = { 'ids': script_id } response = http_request('DELETE', endpoint_url, params=params) return response def list_scripts() -> Dict: """ Retrieves list of scripts :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/entities/scripts/v1' response = http_request('GET', endpoint_url) return response def get_extracted_file(host_id: str, sha256: str, filename: str = None): """ Get RTR extracted file contents for specified session and sha256. :param host_id: The host agent ID to initialize the RTR session on. :param sha256: Extracted SHA256 :param filename: Filename to use for the archive name and the file within the archive. """ endpoint_url = '/real-time-response/entities/extracted-file-contents/v1' session_id = init_rtr_single_session(host_id) params = { 'session_id': session_id, 'sha256': sha256 } if filename: params['filename'] = filename response = http_request('GET', endpoint_url, params=params, no_json=True) return response def upload_file(entry_id: str, description: str) -> Tuple: """ Uploads a file given entry ID :param entry_id: The entry ID of the file to upload :param description: String description of file to upload :return: Response JSON which contains errors (if exist) and how many resources were affected and the file name """ endpoint_url = '/real-time-response/entities/put-files/v1' temp_file = None try: file_ = demisto.getFilePath(entry_id) file_name = file_.get('name') # pylint: disable=E1101 temp_file = open(file_.get('path'), 'rb') # pylint: disable=E1101 body = { 'name': (None, file_name), 'description': (None, description), 'file': (file_name, temp_file) } headers = { 'Authorization': HEADERS['Authorization'], 'Accept': 'application/json' } response = http_request('POST', endpoint_url, files=body, headers=headers) return response, file_name finally: if temp_file: temp_file.close() def delete_file(file_id: str) -> Dict: """ Delete a put-file based on the ID given :param file_id: ID of file to delete :return: Response JSON which contains errors (if exist) and how many resources were affected """ endpoint_url = '/real-time-response/entities/put-files/v1' params = { 'ids': file_id } response = http_request('DELETE', endpoint_url, params=params) return response def get_file(file_id: list) -> Dict: """ Get put-files based on the ID's given :param file_id: ID of file to get :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/entities/put-files/v1' params = { 'ids': file_id } response = http_request('GET', endpoint_url, params=params) return response def list_files() -> Dict: """ Get a list of put-file ID's that are available to the user for the put command. :return: Response JSON which contains errors (if exist) and retrieved resources """ endpoint_url = '/real-time-response/entities/put-files/v1' response = http_request('GET', endpoint_url) return response def get_token(new_token=False): """ Retrieves the token from the server if it's expired and updates the global HEADERS to include it :param new_token: If set to True will generate a new token regardless of time passed :rtype: ``str`` :return: Token """ now = datetime.now() ctx = demisto.getIntegrationContext() if ctx and not new_token: passed_mins = get_passed_mins(now, ctx.get('time')) if passed_mins >= TOKEN_LIFE_TIME: # token expired auth_token = get_token_request() demisto.setIntegrationContext({'auth_token': auth_token, 'time': date_to_timestamp(now) / 1000}) else: # token hasn't expired auth_token = ctx.get('auth_token') else: # there is no token auth_token = get_token_request() demisto.setIntegrationContext({'auth_token': auth_token, 'time': date_to_timestamp(now) / 1000}) return auth_token def get_token_request(): """ Sends token request :rtype ``str`` :return: Access token """ body = { 'client_id': CLIENT_ID, 'client_secret': SECRET } headers = { 'Content-Type': 'application/x-www-form-urlencoded' } token_res = http_request('POST', '/oauth2/token', data=body, headers=headers, safe=True, get_token_flag=False) if not token_res: err_msg = 'Authorization Error: User has no authorization to create a token. Please make sure you entered the' \ ' credentials correctly.' raise Exception(err_msg) return token_res.get('access_token') def get_detections(last_behavior_time=None, behavior_id=None, filter_arg=None): """ Sends detections request. The function will ignore the arguments passed according to priority: filter_arg > behavior_id > last_behavior_time :param last_behavior_time: 3rd priority. The last behavior time of results will be greater than this value :param behavior_id: 2nd priority. The result will only contain the detections with matching behavior id :param filter_arg: 1st priority. The result will be filtered using this argument. :return: Response json of the get detection endpoint (IDs of the detections) """ endpoint_url = '/detects/queries/detects/v1' params = { 'sort': 'first_behavior.asc' } if filter_arg: params['filter'] = filter_arg elif behavior_id: params['filter'] = "behaviors.behavior_id:'{0}'".format(behavior_id) elif last_behavior_time: params['filter'] = "first_behavior:>'{0}'".format(last_behavior_time) response = http_request('GET', endpoint_url, params) return response def get_fetch_detections(last_created_timestamp=None, filter_arg=None, offset: int = 0): """ Sends detection request, based on the created_timestamp field. Used for fetch-incidents Args: last_created_timestamp: last created timestamp of the results will be greater than this value. filter_arg: The result will be filtered using this argument. Returns: Response json of the get detection endpoint (IDs of the detections) """ endpoint_url = '/detects/queries/detects/v1' params = { 'sort': 'first_behavior.asc', 'offset': offset, 'limit': INCIDENTS_PER_FETCH } if filter_arg: params['filter'] = filter_arg elif last_created_timestamp: params['filter'] = "created_timestamp:>'{0}'".format(last_created_timestamp) response = http_request('GET', endpoint_url, params) return response def get_detections_entities(detections_ids): """ Sends detection entities request :param detections_ids: IDs of the requested detections. :return: Response json of the get detection entities endpoint (detection objects) """ ids_json = {'ids': detections_ids} if detections_ids: response = http_request( 'POST', '/detects/entities/summaries/GET/v1', data=json.dumps(ids_json) ) return response return detections_ids def get_incidents_ids(last_created_timestamp=None, filter_arg=None, offset: int = 0): get_incidents_endpoint = '/incidents/queries/incidents/v1' params = { 'sort': 'start.asc', 'offset': offset, 'limit': INCIDENTS_PER_FETCH } if filter_arg: params['filter'] = filter_arg elif last_created_timestamp: params['filter'] = "start:>'{0}'".format(last_created_timestamp) response = http_request('GET', get_incidents_endpoint, params) return response def get_incidents_entities(incidents_ids): ids_json = {'ids': incidents_ids} response = http_request( 'POST', '/incidents/entities/incidents/GET/v1', data=json.dumps(ids_json) ) return response def upload_ioc(ioc_type, value, policy=None, expiration_days=None, share_level=None, description=None, source=None): """ Create a new IOC (or replace an existing one) """ payload = assign_params( type=ioc_type, value=value, policy=policy, share_level=share_level, expiration_days=expiration_days, source=source, description=description, ) return http_request('POST', '/indicators/entities/iocs/v1', json=[payload]) def update_ioc(ioc_type, value, policy=None, expiration_days=None, share_level=None, description=None, source=None): """ Update an existing IOC """ body = assign_params( type=ioc_type, value=value, policy=policy, share_level=share_level, expiration_days=expiration_days, source=source, description=description, ) params = assign_params( type=ioc_type, value=value ) return http_request('PATCH', '/indicators/entities/iocs/v1', json=body, params=params) def search_iocs(types=None, values=None, policies=None, sources=None, expiration_from=None, expiration_to=None, limit=None, share_levels=None, ids=None, sort=None, offset=None): """ :param types: A list of indicator types. Separate multiple types by comma. :param values: Comma-separated list of indicator values :param policies: Comma-separated list of indicator policies :param sources: Comma-separated list of IOC sources :param expiration_from: Start of date range to search (YYYY-MM-DD format). :param expiration_to: End of date range to search (YYYY-MM-DD format). :param share_levels: A list of share levels. Only red is supported. :param limit: The maximum number of records to return. The minimum is 1 and the maximum is 500. Default is 100. :param sort: The order of the results. Format :param offset: The offset to begin the list from """ if not ids: payload = assign_params( types=argToList(types), values=argToList(values), policies=argToList(policies), sources=argToList(sources), share_levels=argToList(share_levels), sort=sort, offset=offset, limit=limit or '50', ) if expiration_from: payload['from.expiration_timestamp'] = expiration_from if expiration_to: payload['to.expiration_timestamp'] = expiration_to ids = http_request('GET', '/indicators/queries/iocs/v1', payload).get('resources') if not ids: return None else: ids = str(ids) payload = { 'ids': ids } return http_request('GET', '/indicators/entities/iocs/v1', params=payload) def enrich_ioc_dict_with_ids(ioc_dict): """ Enriches the provided ioc_dict with IOC ID :param ioc_dict: IOC dict transformed using the SEARCH_IOC_KEY_MAP :return: ioc_dict with its ID key:value updated """ for ioc in ioc_dict: ioc['ID'] = '{type}:{val}'.format(type=ioc.get('Type'), val=ioc.get('Value')) return ioc_dict def delete_ioc(ioc_type, value): """ Delete an IOC """ payload = assign_params( type=ioc_type, value=value ) return http_request('DELETE', '/indicators/entities/iocs/v1', payload) def search_custom_iocs( types: Optional[Union[list, str]] = None, values: Optional[Union[list, str]] = None, sources: Optional[Union[list, str]] = None, expiration: Optional[str] = None, limit: str = '50', sort: Optional[str] = None, offset: Optional[str] = None, ) -> dict: """ :param types: A list of indicator types. Separate multiple types by comma. :param values: Comma-separated list of indicator values :param sources: Comma-separated list of IOC sources :param expiration: The date on which the indicator will become inactive. (YYYY-MM-DD format). :param limit: The maximum number of records to return. The minimum is 1 and the maximum is 500. Default is 100. :param sort: The order of the results. Format :param offset: The offset to begin the list from """ filter_list = [] if types: filter_list.append(f'type:{types}') if values: filter_list.append(f'value:{values}') if sources: filter_list.append(f'source:{sources}') if expiration: filter_list.append(f'expiration:"{expiration}"') params = { 'filter': '+'.join(filter_list), 'sort': sort, 'offset': offset, 'limit': limit, } return http_request('GET', '/iocs/combined/indicator/v1', params=params) def get_custom_ioc(ioc_id: str) -> dict: params = {'ids': ioc_id} return http_request('GET', '/iocs/entities/indicators/v1', params=params) def upload_custom_ioc( ioc_type: str, value: str, action: str, platforms: str, severity: Optional[str] = None, source: Optional[str] = None, description: Optional[str] = None, expiration: Optional[str] = None, applied_globally: Optional[bool] = None, host_groups: Optional[List[str]] = None, ) -> dict: """ Create a new IOC (or replace an existing one) """ payload = { 'indicators': [assign_params( type=ioc_type, value=value, action=action, platforms=platforms, severity=severity, source=source, description=description, expiration=expiration, applied_globally=applied_globally, host_groups=host_groups, )] } return http_request('POST', '/iocs/entities/indicators/v1', json=payload) def update_custom_ioc( ioc_id: str, action: Optional[str] = None, platforms: Optional[str] = None, severity: Optional[str] = None, source: Optional[str] = None, description: Optional[str] = None, expiration: Optional[str] = None, ) -> dict: """ Update an IOC """ payload = { 'indicators': [{ 'id': ioc_id, } | assign_params( action=action, platforms=platforms, severity=severity, source=source, description=description, expiration=expiration, )] } return http_request('PATCH', '/iocs/entities/indicators/v1', json=payload) def delete_custom_ioc(ids: str) -> dict: """ Delete an IOC """ params = {'ids': ids} return http_request('DELETE', '/iocs/entities/indicators/v1', params=params) def get_ioc_device_count(ioc_type, value): """ Gets the devices that encountered the IOC """ payload = assign_params( type=ioc_type, value=value ) response = http_request('GET', '/indicators/aggregates/devices-count/v1', payload, status_code=404) errors = response.get('errors', []) for error in errors: if error.get('code') == 404: return f'No results found for {ioc_type} - {value}' return response def get_process_details(ids): """ Get given processes details """ payload = assign_params(ids=ids) return http_request('GET', '/processes/entities/processes/v1', payload) def get_proccesses_ran_on(ioc_type, value, device_id): """ Get processes ids that ran on the given device_id that encountered the ioc """ payload = assign_params( type=ioc_type, value=value, device_id=device_id ) return http_request('GET', '/indicators/queries/processes/v1', payload) def search_device(): """ Searches for devices using the argument provided by the command execution. Returns empty result of no device was found :return: Search device response json """ args = demisto.args() input_arg_dict = { 'device_id': str(args.get('ids', '')).split(','), 'status': str(args.get('status', '')).split(','), 'hostname': str(args.get('hostname', '')).split(','), 'platform_name': str(args.get('platform_name', '')).split(','), 'site_name': str(args.get('site_name', '')).split(',') } url_filter = '{}'.format(str(args.get('filter', ''))) for k, arg in input_arg_dict.items(): if arg: if type(arg) is list: arg_filter = '' for arg_elem in arg: if arg_elem: first_arg = '{filter},{inp_arg}'.format(filter=arg_filter, inp_arg=k) if arg_filter else k arg_filter = "{first}:'{second}'".format(first=first_arg, second=arg_elem) if arg_filter: url_filter = "{url_filter}{arg_filter}".format(url_filter=url_filter + '+' if url_filter else '', arg_filter=arg_filter) else: # All args should be a list. this is a fallback url_filter = "{url_filter}+{inp_arg}:'{arg_val}'".format(url_filter=url_filter, inp_arg=k, arg_val=arg) raw_res = http_request('GET', '/devices/queries/devices/v1', params={'filter': url_filter}) device_ids = raw_res.get('resources') if not device_ids: return None return http_request('GET', '/devices/entities/devices/v1', params={'ids': device_ids}) def behavior_to_entry_context(behavior): """ Transforms a behavior to entry context representation :param behavior: Behavior dict in the format of crowdstrike's API response :return: Behavior in entry context representation """ raw_entry = get_trasnformed_dict(behavior, DETECTIONS_BEHAVIORS_KEY_MAP) raw_entry.update(extract_transformed_dict_with_split(behavior, DETECTIONS_BEHAVIORS_SPLIT_KEY_MAP)) return raw_entry def get_username_uuid(username: str): """ Obtain CrowdStrike user’s UUId by email. :param username: Username to get UUID of. :return: The user UUID """ response = http_request('GET', '/users/queries/user-uuids-by-email/v1', params={'uid': username}) resources: list = response.get('resources', []) if not resources: raise ValueError(f'User {username} was not found') return resources[0] def resolve_detection(ids, status, assigned_to_uuid, show_in_ui, comment): """ Sends a resolve detection request :param ids: Single or multiple ids in an array string format :param status: New status of the detection :param assigned_to_uuid: uuid to assign the detection to :param show_in_ui: Boolean flag in string format (true/false) :param comment: Optional comment to add to the detection :return: Resolve detection response json """ payload = { 'ids': ids } if status: payload['status'] = status if assigned_to_uuid: payload['assigned_to_uuid'] = assigned_to_uuid if show_in_ui: payload['show_in_ui'] = show_in_ui if comment: payload['comment'] = comment # We do this so show_in_ui value won't contain "" data = json.dumps(payload).replace('"show_in_ui": "false"', '"show_in_ui": false').replace('"show_in_ui": "true"', '"show_in_ui": true') return http_request('PATCH', '/detects/entities/detects/v2', data=data) def contain_host(ids): """ Contains host(s) with matching ids :param ids: IDs of host to contain :return: Contain host response json """ payload = { 'ids': ids } data = json.dumps(payload) params = { 'action_name': 'contain' } return http_request('POST', '/devices/entities/devices-actions/v2', data=data, params=params) def lift_host_containment(ids): """ Lifts off containment from host(s) with matchind ids :param ids: IDs of host to lift off containment from :return: Lift off containment response json """ payload = { 'ids': ids } data = json.dumps(payload) params = { 'action_name': 'lift_containment' } return http_request('POST', '/devices/entities/devices-actions/v2', data=data, params=params) def timestamp_length_equalization(timestamp1, timestamp2): """ Makes sure the timestamps are of the same length. Args: timestamp1: First timestamp to compare. timestamp2: Second timestamp to compare. Returns: the two timestamps in the same length (the longer one) """ diff_len = len(str(timestamp1)) - len(str(timestamp2)) # no difference in length if diff_len == 0: return int(timestamp1), int(timestamp2) # length of timestamp1 > timestamp2 if diff_len > 0: ten_times = pow(10, diff_len) timestamp2 = int(timestamp2) * ten_times # length of timestamp2 > timestamp1 else: ten_times = pow(10, diff_len * -1) timestamp1 = int(timestamp1) * ten_times return int(timestamp1), int(timestamp2) def change_host_group(is_post: bool, host_group_id: Optional[str] = None, name: Optional[str] = None, group_type: Optional[str] = None, description: Optional[str] = None, assignment_rule: Optional[str] = None) -> Dict: method = 'POST' if is_post else 'PATCH' data = {'resources': [{ 'id': host_group_id, "name": name, "description": description, "group_type": group_type, "assignment_rule": assignment_rule }]} response = http_request(method=method, url_suffix='/devices/entities/host-groups/v1', json=data) return response def change_host_group_members(action_name: str, host_group_id: str, host_ids: List[str]) -> Dict: allowed_actions = {'add-hosts', 'remove-hosts'} if action_name not in allowed_actions: raise DemistoException(f'CrowdStrike Falcon error: action name should be in {allowed_actions}') data = {'action_parameters': [{'name': 'filter', 'value': f"(device_id:{str(host_ids)})"}], 'ids': [host_group_id]} response = http_request(method='POST', url_suffix='/devices/entities/host-group-actions/v1', params={'action_name': action_name}, json=data) return response def host_group_members(filter: Optional[str], host_group_id: Optional[str], limit: Optional[str], offset: Optional[str]): params = {'id': host_group_id, 'filter': filter, 'offset': offset, 'limit': limit} response = http_request(method='GET', url_suffix='/devices/combined/host-group-members/v1', params=params) return response def resolve_incident(ids: List[str], status: str): if status not in STATUS_TEXT_TO_NUM: raise DemistoException(f'CrowdStrike Falcon Error: ' f'Status given is {status} and it is not in {STATUS_TEXT_TO_NUM.keys()}') data = { "action_parameters": [ { "name": "update_status", "value": STATUS_TEXT_TO_NUM[status] } ], "ids": ids } http_request(method='POST', url_suffix='/incidents/entities/incident-actions/v1', json=data) def list_host_groups(filter: Optional[str], limit: Optional[str], offset: Optional[str]) -> Dict: params = {'filter': filter, 'offset': offset, 'limit': limit} response = http_request(method='GET', url_suffix='/devices/combined/host-groups/v1', params=params) return response def delete_host_groups(host_group_ids: List[str]) -> Dict: params = {'ids': host_group_ids} response = http_request(method='DELETE', url_suffix='/devices/entities/host-groups/v1', params=params) return response ''' COMMANDS FUNCTIONS ''' def get_fetch_times_and_offset(incident_type): last_run = demisto.getLastRun() last_fetch_time = last_run.get(f'first_behavior_{incident_type}_time') offset = last_run.get(f'{incident_type}_offset', 0) if not last_fetch_time: last_fetch_time, _ = parse_date_range(FETCH_TIME, date_format='%Y-%m-%dT%H:%M:%SZ') prev_fetch = last_fetch_time last_fetch_timestamp = int(parse(last_fetch_time).timestamp() * 1000) return last_fetch_time, offset, prev_fetch, last_fetch_timestamp def fetch_incidents(): incidents = [] # type:List current_fetch_info = demisto.getLastRun() fetch_incidents_or_detections = demisto.params().get('fetch_incidents_or_detections') if 'Detections' in fetch_incidents_or_detections: incident_type = 'detection' last_fetch_time, offset, prev_fetch, last_fetch_timestamp = get_fetch_times_and_offset(incident_type) fetch_query = demisto.params().get('fetch_query') if fetch_query: fetch_query = "created_timestamp:>'{time}'+{query}".format(time=last_fetch_time, query=fetch_query) detections_ids = demisto.get(get_fetch_detections(filter_arg=fetch_query, offset=offset), 'resources') else: detections_ids = demisto.get(get_fetch_detections(last_created_timestamp=last_fetch_time, offset=offset), 'resources') if detections_ids: raw_res = get_detections_entities(detections_ids) if "resources" in raw_res: for detection in demisto.get(raw_res, "resources"): detection['incident_type'] = incident_type incident = detection_to_incident(detection) incident_date = incident['occurred'] incident_date_timestamp = int(parse(incident_date).timestamp() * 1000) # make sure that the two timestamps are in the same length if len(str(incident_date_timestamp)) != len(str(last_fetch_timestamp)): incident_date_timestamp, last_fetch_timestamp = timestamp_length_equalization( incident_date_timestamp, last_fetch_timestamp) # Update last run and add incident if the incident is newer than last fetch if incident_date_timestamp > last_fetch_timestamp: last_fetch_time = incident_date last_fetch_timestamp = incident_date_timestamp incidents.append(incident) if len(incidents) == INCIDENTS_PER_FETCH: current_fetch_info['first_behavior_detection_time'] = prev_fetch current_fetch_info['detection_offset'] = offset + INCIDENTS_PER_FETCH else: current_fetch_info['first_behavior_detection_time'] = last_fetch_time current_fetch_info['detection_offset'] = 0 if 'Incidents' in fetch_incidents_or_detections: incident_type = 'incident' last_fetch_time, offset, prev_fetch, last_fetch_timestamp = get_fetch_times_and_offset(incident_type) last_run = demisto.getLastRun() last_incident_fetched = last_run.get('last_fetched_incident') new_last_incident_fetched = '' fetch_query = demisto.params().get('incidents_fetch_query') if fetch_query: fetch_query = "start:>'{time}'+{query}".format(time=last_fetch_time, query=fetch_query) incidents_ids = demisto.get(get_incidents_ids(filter_arg=fetch_query, offset=offset), 'resources') else: incidents_ids = demisto.get(get_incidents_ids(last_created_timestamp=last_fetch_time, offset=offset), 'resources') if incidents_ids: raw_res = get_incidents_entities(incidents_ids) if "resources" in raw_res: for incident in demisto.get(raw_res, "resources"): incident['incident_type'] = incident_type incident_to_context = incident_to_incident_context(incident) incident_date = incident_to_context['occurred'] incident_date_timestamp = int(parse(incident_date).timestamp() * 1000) # make sure that the two timestamps are in the same length if len(str(incident_date_timestamp)) != len(str(last_fetch_timestamp)): incident_date_timestamp, last_fetch_timestamp = timestamp_length_equalization( incident_date_timestamp, last_fetch_timestamp) # Update last run and add incident if the incident is newer than last fetch if incident_date_timestamp > last_fetch_timestamp: last_fetch_time = incident_date last_fetch_timestamp = incident_date_timestamp new_last_incident_fetched = incident.get('incident_id') if last_incident_fetched != incident.get('incident_id'): incidents.append(incident_to_context) if len(incidents) == INCIDENTS_PER_FETCH: current_fetch_info['first_behavior_incident_time'] = prev_fetch current_fetch_info['incident_offset'] = offset + INCIDENTS_PER_FETCH current_fetch_info['last_fetched_incident'] = new_last_incident_fetched else: current_fetch_info['first_behavior_incident_time'] = last_fetch_time current_fetch_info['incident_offset'] = 0 current_fetch_info['last_fetched_incident'] = new_last_incident_fetched demisto.setLastRun(current_fetch_info) return incidents def upload_ioc_command(ioc_type=None, value=None, policy=None, expiration_days=None, share_level=None, description=None, source=None): """ :param ioc_type: The type of the indicator: :param policy :The policy to enact when the value is detected on a host. :param share_level: The level at which the indicator will be shared. :param expiration_days: This represents the days the indicator should be valid for. :param source: The source where this indicator originated. :param description: A meaningful description of the indicator. :param value: The string representation of the indicator. """ raw_res = upload_ioc(ioc_type, value, policy, expiration_days, share_level, description, source) handle_response_errors(raw_res) iocs = search_iocs(ids=f"{ioc_type}:{value}").get('resources') if not iocs: raise DemistoException("Failed to create IOC. Please try again.") ec = [get_trasnformed_dict(iocs[0], IOC_KEY_MAP)] enrich_ioc_dict_with_ids(ec) return create_entry_object(contents=raw_res, ec={'CrowdStrike.IOC(val.ID === obj.ID)': ec}, hr=tableToMarkdown('Custom IOC was created successfully', ec)) def update_ioc_command(ioc_type=None, value=None, policy=None, expiration_days=None, share_level=None, description=None, source=None): """ :param ioc_type: The type of the indicator: :param policy :The policy to enact when the value is detected on a host. :param share_level: The level at which the indicator will be shared. :param expiration_days: This represents the days the indicator should be valid for. :param source: The source where this indicator originated. :param description: A meaningful description of the indicator. :param value: The string representation of the indicator. """ raw_res = update_ioc(ioc_type, value, policy, expiration_days, share_level, description, source) handle_response_errors(raw_res) iocs = search_iocs(ids=f"{ioc_type}:{value}").get('resources') ec = [get_trasnformed_dict(iocs[0], IOC_KEY_MAP)] enrich_ioc_dict_with_ids(ec) return create_entry_object(contents=raw_res, ec={'CrowdStrike.IOC(val.ID === obj.ID)': ec}, hr=tableToMarkdown('Custom IOC was created successfully', ec)) def search_iocs_command(types=None, values=None, policies=None, sources=None, from_expiration_date=None, to_expiration_date=None, share_levels=None, limit=None, sort=None, offset=None): """ :param types: A list of indicator types. Separate multiple types by comma. :param values: Comma-separated list of indicator values :param policies: Comma-separated list of indicator policies :param sources: Comma-separated list of IOC sources :param from_expiration_date: Start of date range to search (YYYY-MM-DD format). :param to_expiration_date: End of date range to search (YYYY-MM-DD format). :param share_levels: A list of share levels. Only red is supported. :param limit: The maximum number of records to return. The minimum is 1 and the maximum is 500. Default is 100. :param sort: The order of the results. Format :param offset: The offset to begin the list from """ raw_res = search_iocs(types=types, values=values, policies=policies, sources=sources, sort=sort, offset=offset, expiration_from=from_expiration_date, expiration_to=to_expiration_date, share_levels=share_levels, limit=limit) if not raw_res: return create_entry_object(hr='Could not find any Indicators of Compromise.') handle_response_errors(raw_res) iocs = raw_res.get('resources') ec = [get_trasnformed_dict(ioc, IOC_KEY_MAP) for ioc in iocs] enrich_ioc_dict_with_ids(ec) return create_entry_object(contents=raw_res, ec={'CrowdStrike.IOC(val.ID === obj.ID)': ec}, hr=tableToMarkdown('Indicators of Compromise', ec)) def get_ioc_command(ioc_type: str, value: str): """ :param ioc_type: The type of the indicator :param value: The IOC value to retrieve """ raw_res = search_iocs(ids=f"{ioc_type}:{value}") handle_response_errors(raw_res, 'Could not find any Indicators of Compromise.') iocs = raw_res.get('resources') ec = [get_trasnformed_dict(ioc, IOC_KEY_MAP) for ioc in iocs] enrich_ioc_dict_with_ids(ec) return create_entry_object(contents=raw_res, ec={'CrowdStrike.IOC(val.ID === obj.ID)': ec}, hr=tableToMarkdown('Indicator of Compromise', ec)) def delete_ioc_command(ioc_type, value): """ :param ioc_type: The type of the indicator :param value: The IOC value to delete """ raw_res = delete_ioc(ioc_type, value) handle_response_errors(raw_res, "The server has not confirmed deletion, please manually confirm deletion.") ids = f"{ioc_type}:{value}" return create_entry_object(contents=raw_res, hr=f"Custom IOC {ids} was successfully deleted.") def search_custom_iocs_command( types: Optional[Union[list, str]] = None, values: Optional[Union[list, str]] = None, sources: Optional[Union[list, str]] = None, expiration: Optional[str] = None, limit: str = '50', sort: Optional[str] = None, offset: Optional[str] = None, ) -> dict: """ :param types: A list of indicator types. Separate multiple types by comma. :param values: Comma-separated list of indicator values :param sources: Comma-separated list of IOC sources :param expiration: The date on which the indicator will become inactive. (YYYY-MM-DD format). :param limit: The maximum number of records to return. The minimum is 1 and the maximum is 500. Default is 100. :param sort: The order of the results. Format :param offset: The offset to begin the list from """ raw_res = search_custom_iocs( types=argToList(types), values=argToList(values), sources=argToList(sources), sort=sort, offset=offset, expiration=expiration, limit=limit, ) iocs = raw_res.get('resources') if not iocs: return create_entry_object(hr='Could not find any Indicators of Compromise.') handle_response_errors(raw_res) ec = [get_trasnformed_dict(ioc, IOC_KEY_MAP) for ioc in iocs] return create_entry_object( contents=raw_res, ec={'CrowdStrike.IOC(val.ID === obj.ID)': ec}, hr=tableToMarkdown('Indicators of Compromise', ec), ) def get_custom_ioc_command( ioc_type: Optional[str] = None, value: Optional[str] = None, ioc_id: Optional[str] = None, ) -> dict: """ :param ioc_type: IOC type :param value: IOC value :param ioc_id: IOC ID """ if not ioc_id and not (ioc_type and value): raise ValueError('Either ioc_id or ioc_type and value must be provided.') if ioc_id: raw_res = get_custom_ioc(ioc_id) else: raw_res = search_custom_iocs( types=argToList(ioc_type), values=argToList(value), ) iocs = raw_res.get('resources') handle_response_errors(raw_res) if not iocs: return create_entry_object(hr='Could not find any Indicators of Compromise.') ec = [get_trasnformed_dict(ioc, IOC_KEY_MAP) for ioc in iocs] return create_entry_object( contents=raw_res, ec={'CrowdStrike.IOC(val.ID === obj.ID)': ec}, hr=tableToMarkdown('Indicator of Compromise', ec), ) def upload_custom_ioc_command( ioc_type: str, value: str, action: str, platforms: str, severity: Optional[str] = None, source: Optional[str] = None, description: Optional[str] = None, expiration: Optional[str] = None, applied_globally: Optional[bool] = None, host_groups: Optional[List[str]] = None, ) -> dict: """ :param ioc_type: The type of the indicator. :param value: The string representation of the indicator. :param action: Action to take when a host observes the custom IOC. :param platforms: The platforms that the indicator applies to. :param severity: The severity level to apply to this indicator. :param source: The source where this indicator originated. :param description: A meaningful description of the indicator. :param expiration: The date on which the indicator will become inactive. :param applied_globally: Whether the indicator is applied globally. :param host_groups: List of host group IDs that the indicator applies to. """ if action in {'prevent', 'detect'} and not severity: raise ValueError(f'Severity is required for action {action}.') raw_res = upload_custom_ioc( ioc_type, value, action, argToList(platforms), severity, source, description, expiration, argToBoolean(applied_globally) if applied_globally else None, argToList(host_groups), ) handle_response_errors(raw_res) iocs = raw_res.get('resources', []) ec = [get_trasnformed_dict(iocs[0], IOC_KEY_MAP)] return create_entry_object( contents=raw_res, ec={'CrowdStrike.IOC(val.ID === obj.ID)': ec}, hr=tableToMarkdown('Custom IOC was created successfully', ec), ) def update_custom_ioc_command( ioc_id: str, action: Optional[str] = None, platforms: Optional[str] = None, severity: Optional[str] = None, source: Optional[str] = None, description: Optional[str] = None, expiration: Optional[str] = None, ) -> dict: """ :param ioc_id: The ID of the indicator to update. :param action: Action to take when a host observes the custom IOC. :param platforms: The platforms that the indicator applies to. :param severity: The severity level to apply to this indicator. :param source: The source where this indicator originated. :param description: A meaningful description of the indicator. :param expiration: The date on which the indicator will become inactive. """ raw_res = update_custom_ioc( ioc_id, action, argToList(platforms), severity, source, description, expiration, ) handle_response_errors(raw_res) iocs = raw_res.get('resources', []) ec = [get_trasnformed_dict(iocs[0], IOC_KEY_MAP)] return create_entry_object( contents=raw_res, ec={'CrowdStrike.IOC(val.ID === obj.ID)': ec}, hr=tableToMarkdown('Custom IOC was updated successfully', ec), ) def delete_custom_ioc_command(ioc_id: str) -> dict: """ :param ioc_id: The ID of indicator to delete. """ raw_res = delete_custom_ioc(ioc_id) handle_response_errors(raw_res, "The server has not confirmed deletion, please manually confirm deletion.") return create_entry_object(contents=raw_res, hr=f"Custom IOC {ioc_id} was successfully deleted.") def get_ioc_device_count_command(ioc_type: str, value: str): """ :param ioc_type: The type of the indicator :param value: The IOC value """ raw_res = get_ioc_device_count(ioc_type, value) if 'No results found for' in raw_res: return raw_res else: handle_response_errors(raw_res) device_count_res = raw_res.get('resources') ioc_id = f"{ioc_type}:{value}" if not device_count_res: return create_entry_object(raw_res, hr=f"Could not find any devices the IOC **{ioc_id}** was detected in.") context = [get_trasnformed_dict(device_count, IOC_DEVICE_COUNT_MAP) for device_count in device_count_res] hr = f'Indicator of Compromise **{ioc_id}** device count: **{device_count_res[0].get("device_count")}**' return create_entry_object(contents=raw_res, ec={'CrowdStrike.IOC(val.ID === obj.ID)': context}, hr=hr) def get_process_details_command(ids: str): """ :param ids: proccess ids """ ids = argToList(ids) raw_res = get_process_details(ids) handle_response_errors(raw_res) proc = raw_res.get('resources') if not proc: return create_entry_object(raw_res, hr="Could not find any searched processes.") proc_hr_ids = str(ids)[1:-1].replace('\'', '') title = f"Details for process{'es' if len(ids) > 1 else ''}: {proc_hr_ids}." return create_entry_object(contents=raw_res, hr=tableToMarkdown(title, proc), ec={'CrowdStrike.Process(val.process_id === obj.process_id)': proc}) def get_proccesses_ran_on_command(ioc_type, value, device_id): """ :param device_id: Device id the IOC ran on :param ioc_type: The type of the indicator :param value: The IOC value """ raw_res = get_proccesses_ran_on(ioc_type, value, device_id) handle_response_errors(raw_res) proc_ids = raw_res.get('resources') ioc_id = f"{ioc_type}:{value}" if not proc_ids: return create_entry_object(raw_res, hr=f"Could not find any processes associated with the IOC **{ioc_id}**.") context = {'ID': ioc_id, 'Type': ioc_type, 'Value': value, 'Process': {'DeviceID': device_id, 'ID': proc_ids}} hr = tableToMarkdown(f"Processes with custom IOC {ioc_id} on device {device_id}.", proc_ids, headers="Process ID") return create_entry_object(contents=raw_res, hr=hr, ec={'CrowdStrike.IOC(val.ID === obj.ID)': context}) def search_device_command(): """ Searches for a device :return: EntryObject of search device command """ raw_res = search_device() if not raw_res: return create_entry_object(hr='Could not find any devices.') devices = raw_res.get('resources') command_results = [] for single_device in devices: status, is_isolated = generate_status_fields(single_device.get('status')) endpoint = Common.Endpoint( id=single_device.get('device_id'), hostname=single_device.get('hostname'), ip_address=single_device.get('local_ip'), os=single_device.get('platform_name'), os_version=single_device.get('os_version'), status=status, is_isolated=is_isolated, mac_address=single_device.get('mac_address'), vendor=INTEGRATION_NAME) entry = get_trasnformed_dict(single_device, SEARCH_DEVICE_KEY_MAP) headers = ['ID', 'Hostname', 'OS', 'MacAddress', 'LocalIP', 'ExternalIP', 'FirstSeen', 'LastSeen', 'Status'] command_results.append(CommandResults( outputs_prefix='CrowdStrike.Device', outputs_key_field='ID', outputs=entry, readable_output=tableToMarkdown('Devices', entry, headers=headers, headerTransform=pascalToSpace), raw_response=raw_res, indicator=endpoint, )) return command_results def search_device_by_ip(raw_res, ip_address): devices = raw_res.get('resources') filtered_devices = [] for single_device in devices: if single_device.get('local_ip') == ip_address: filtered_devices.append(single_device) if filtered_devices: raw_res['resources'] = filtered_devices else: raw_res = None return raw_res def generate_status_fields(endpoint_status): status = '' is_isolated = '' if endpoint_status.lower() == 'normal': status = 'Online' elif endpoint_status == 'containment_pending': is_isolated = 'Pending isolation' elif endpoint_status == 'contained': is_isolated = 'Yes' elif endpoint_status == 'lift_containment_pending': is_isolated = 'Pending unisolation' else: raise DemistoException(f'Error: Unknown endpoint status was given: {endpoint_status}') return status, is_isolated def generate_endpoint_by_contex_standard(devices): standard_endpoints = [] for single_device in devices: status, is_isolated = generate_status_fields(single_device.get('status')) endpoint = Common.Endpoint( id=single_device.get('device_id'), hostname=single_device.get('hostname'), ip_address=single_device.get('local_ip'), os=single_device.get('platform_name'), os_version=single_device.get('os_version'), status=status, is_isolated=is_isolated, mac_address=single_device.get('mac_address'), vendor=INTEGRATION_NAME) standard_endpoints.append(endpoint) return standard_endpoints def get_endpoint_command(): args = demisto.args() if 'id' in args.keys(): args['ids'] = args.get('id', '') # handles the search by id or by hostname raw_res = search_device() if ip := args.get('ip') and raw_res: # there is no option to filter by ip in an api call, therefore we would filter the devices in the code raw_res = search_device_by_ip(raw_res, ip) if not ip and not args.get('id') and not args.get('hostname'): # in order not to return all the devices return create_entry_object(hr='Please add a filter argument - ip, hostname or id.') if not raw_res: return create_entry_object(hr='Could not find any devices.') devices = raw_res.get('resources') standard_endpoints = generate_endpoint_by_contex_standard(devices) command_results = [] for endpoint in standard_endpoints: endpoint_context = endpoint.to_context().get(Common.Endpoint.CONTEXT_PATH) hr = tableToMarkdown('CrowdStrike Falcon Endpoint', endpoint_context) command_results.append(CommandResults( readable_output=hr, raw_response=raw_res, indicator=endpoint )) return command_results def get_behavior_command(): """ Gets a behavior by ID :return: EntryObject of get behavior command """ behavior_id = demisto.args().get('behavior_id') detections_ids = demisto.get(get_detections(behavior_id=behavior_id), 'resources') raw_res = get_detections_entities(detections_ids) entries = [] if "resources" in raw_res: for resource in demisto.get(raw_res, "resources"): for behavior in demisto.get(resource, 'behaviors'): entries.append(behavior_to_entry_context(behavior)) hr = tableToMarkdown('Behavior ID: {}'.format(behavior_id), entries, headerTransform=pascalToSpace) # no dt since behavior vary by more than their ID ec = {'CrowdStrike.Behavior': entries} return create_entry_object(contents=raw_res, ec=ec, hr=hr) def search_detections_command(): """ Searches for a detection :return: EntryObject of search detections command """ d_args = demisto.args() detections_ids = argToList(d_args.get('ids')) if not detections_ids: filter_arg = d_args.get('filter') if not filter_arg: return_error('Command Error: Please provide at least one argument.') detections_ids = get_detections(filter_arg=filter_arg).get('resources') raw_res = get_detections_entities(detections_ids) entries = [] headers = ['ID', 'Status', 'System', 'ProcessStartTime', 'CustomerID', 'MaxSeverity'] if "resources" in raw_res: for detection in demisto.get(raw_res, "resources"): detection_entry = {} for path, new_key in DETECTIONS_BASE_KEY_MAP.items(): detection_entry[new_key] = demisto.get(detection, path) behaviors = [] for behavior in demisto.get(detection, 'behaviors'): behaviors.append(behavior_to_entry_context(behavior)) detection_entry['Behavior'] = behaviors entries.append(detection_entry) hr = tableToMarkdown('Detections Found:', entries, headers=headers, removeNull=True, headerTransform=pascalToSpace) ec = {'CrowdStrike.Detection(val.ID === obj.ID)': entries} return create_entry_object(contents=raw_res, ec=ec, hr=hr) def resolve_detection_command(): """ Resolves single or multiple detections :return: EntryObject of resolve detection command """ args = demisto.args() ids = argToList(args.get('ids')) username = args.get('username') assigned_to_uuid = args.get('assigned_to_uuid') comment = args.get('comment') if username and assigned_to_uuid: raise ValueError('Only one of the arguments assigned_to_uuid or username should be provided, not both.') if username: assigned_to_uuid = get_username_uuid(username) status = args.get('status') show_in_ui = args.get('show_in_ui') if not (username or assigned_to_uuid or comment or status or show_in_ui): raise DemistoException("Please provide at least one argument to resolve the detection with.") raw_res = resolve_detection(ids, status, assigned_to_uuid, show_in_ui, comment) args.pop('ids') hr = "Detection {0} updated\n".format(str(ids)[1:-1]) hr += 'With the following values:\n' for k, arg in args.items(): hr += '\t{name}:{val}\n'.format(name=k, val=arg) return create_entry_object(contents=raw_res, hr=hr) def contain_host_command(): """ Contains hosts with user arg ids :return: EntryObject of contain host command """ ids = argToList(demisto.args().get('ids')) raw_res = contain_host(ids) hr = "Host {} contained".format(str(ids)[1:-1]) return create_entry_object(contents=raw_res, hr=hr) def lift_host_containment_command(): """ Lifts containment off a host :return: EntryObject of lift host containment """ ids = argToList(demisto.args().get('ids')) raw_res = lift_host_containment(ids) hr = "Containment has been lift off host {}".format(str(ids)[1:-1]) return create_entry_object(contents=raw_res, hr=hr) def run_command(): args = demisto.args() host_ids = argToList(args.get('host_ids')) command_type = args.get('command_type') full_command = args.get('full_command') scope = args.get('scope', 'read') target = args.get('target', 'batch') output = [] if target == 'batch': batch_id = init_rtr_batch_session(host_ids) timer = Timer(300, batch_refresh_session, kwargs={'batch_id': batch_id}) timer.start() try: if scope == 'read': response = run_batch_read_cmd(batch_id, command_type, full_command) elif scope == 'write': response = run_batch_write_cmd(batch_id, command_type, full_command) else: # scope = admin response = run_batch_admin_cmd(batch_id, command_type, full_command) finally: timer.cancel() resources: dict = response.get('combined', {}).get('resources', {}) for _, resource in resources.items(): errors = resource.get('errors', []) if errors: error_message = errors[0].get('message', '') if not error_message: error_message = f'Could not run command\n{errors}' return_error(error_message) output.append({ 'HostID': resource.get('aid'), 'SessionID': resource.get('session_id'), 'Stdout': resource.get('stdout'), 'Stderr': resource.get('stderr'), 'BaseCommand': resource.get('base_command'), 'Command': full_command }) human_readable = tableToMarkdown(f'Command {full_command} results', output, removeNull=True) entry_context_batch = { 'CrowdStrike': { 'Command': output } } return create_entry_object(contents=response, ec=entry_context_batch, hr=human_readable) else: # target = 'single' responses = [] for host_id in host_ids: if scope == 'read': response1 = run_single_read_cmd(host_id, command_type, full_command) elif scope == 'write': response1 = run_single_write_cmd(host_id, command_type, full_command) else: # scope = admin response1 = run_single_admin_cmd(host_id, command_type, full_command) responses.append(response1) for resource in response1.get('resources', []): errors = resource.get('errors', []) if errors: error_message = errors[0].get('message', '') if not error_message: error_message = f'Could not run command\n{errors}' return_error(error_message) output.append({ 'HostID': host_id, 'TaskID': resource.get('cloud_request_id'), 'SessionID': resource.get('session_id'), 'BaseCommand': command_type, 'Command': full_command, 'Complete': False, 'NextSequenceID': 0 }) human_readable = tableToMarkdown(f'Command {full_command} results', output, removeNull=True) entry_context_single = { 'CrowdStrike.Command(val.TaskID === obj.TaskID)': output } return create_entry_object(contents=responses, ec=entry_context_single, hr=human_readable) def upload_script_command(): args = demisto.args() name = args.get('name') permission_type = args.get('permission_type', 'private') content = args.get('content') entry_id = args.get('entry_id') if content and entry_id: raise ValueError('Only one of the arguments entry_id or content should be provided, not both.') elif not content and not entry_id: raise ValueError('One of the arguments entry_id or content must be provided, none given.') response = upload_script(name, permission_type, content, entry_id) return create_entry_object(contents=response, hr='The script was uploaded successfully') def get_script_command(): script_id = argToList(demisto.args().get('script_id')) response = get_script(script_id) resources: list = response.get('resources', []) if resources and isinstance(resources, list): resource = resources[0] script = { 'ID': resource.get('id'), 'CreatedBy': resource.get('created_by'), 'CreatedTime': resource.get('created_timestamp'), 'Description': resource.get('description'), 'ModifiedBy': resource.get('modified_by'), 'ModifiedTime': resource.get('modified_timestamp'), 'Name': resource.get('name'), 'Permission': resource.get('permission_type'), 'SHA256': resource.get('sha256'), 'RunAttemptCount': resource.get('run_attempt_count'), 'RunSuccessCount': resource.get('run_success_count'), 'WriteAccess': resource.get('write_access') } human_readable = tableToMarkdown(f'CrowdStrike Falcon script {script_id}', script) entry_context = { 'CrowdStrike.Script(val.ID === obj.ID)': script } script_content = resource.get('content') if script_content: demisto.results( fileResult( f"{resource.get('name', 'script')}.ps1", script_content ) ) return create_entry_object(contents=response, ec=entry_context, hr=human_readable) else: return 'No script found.' def delete_script_command(): script_id = demisto.args().get('script_id') response = delete_script(script_id) return create_entry_object(contents=response, hr=f'Script {script_id} was deleted successfully') def list_scripts_command(): response = list_scripts() resources: list = response.get('resources', []) scripts = [] for resource in resources: scripts.append({ 'ID': resource.get('id'), 'CreatedBy': resource.get('created_by'), 'CreatedTime': resource.get('created_timestamp'), 'Description': resource.get('description'), 'ModifiedBy': resource.get('modified_by'), 'ModifiedTime': resource.get('modified_timestamp'), 'Name': resource.get('name'), 'Permission': resource.get('permission_type'), 'SHA256': resource.get('sha256'), 'RunAttemptCount': resource.get('run_attempt_count'), 'RunSuccessCount': resource.get('run_success_count'), 'Platform': resource.get('platform'), 'WriteAccess': resource.get('write_access') }) human_readable = tableToMarkdown('CrowdStrike Falcon scripts', scripts) entry_context = { 'CrowdStrike.Script(val.ID === obj.ID)': scripts } return create_entry_object(contents=response, ec=entry_context, hr=human_readable) def upload_file_command(): entry_id = demisto.args().get('entry_id') description = demisto.args().get('description', 'File uploaded from Demisto') response, file_name = upload_file(entry_id, description) return create_entry_object(contents=response, hr='File was uploaded successfully') def delete_file_command(): file_id = demisto.args().get('file_id') response = delete_file(file_id) return create_entry_object(contents=response, hr=f'File {file_id} was deleted successfully') def get_file_command(): file_id = argToList(demisto.args().get('file_id')) response = get_file(file_id) resources: list = response.get('resources', []) if resources and isinstance(resources, list): # will always be a list of one resource resource = resources[0] file_ = { 'ID': resource.get('id'), 'CreatedBy': resource.get('created_by'), 'CreatedTime': resource.get('created_timestamp'), 'Description': resource.get('description'), 'Type': resource.get('file_type'), 'ModifiedBy': resource.get('modified_by'), 'ModifiedTime': resource.get('modified_timestamp'), 'Name': resource.get('name'), 'Permission': resource.get('permission_type'), 'SHA256': resource.get('sha256'), } file_standard_context = { 'Type': resource.get('file_type'), 'Name': resource.get('name'), 'SHA256': resource.get('sha256'), 'Size': resource.get('size'), } human_readable = tableToMarkdown(f'CrowdStrike Falcon file {file_id}', file_) entry_context = { 'CrowdStrike.File(val.ID === obj.ID)': file_, outputPaths['file']: file_standard_context } file_content = resource.get('content') if file_content: demisto.results( fileResult( resource.get('name'), file_content ) ) return create_entry_object(contents=response, ec=entry_context, hr=human_readable) else: return 'No file found.' def list_files_command(): response = list_files() resources: list = response.get('resources', []) files_output = [] file_standard_context = [] for resource in resources: files_output.append({ 'ID': resource.get('id'), 'CreatedBy': resource.get('created_by'), 'CreatedTime': resource.get('created_timestamp'), 'Description': resource.get('description'), 'Type': resource.get('file_type'), 'ModifiedBy': resource.get('modified_by'), 'ModifiedTime': resource.get('modified_timestamp'), 'Name': resource.get('name'), 'Permission': resource.get('permission_type'), 'SHA256': resource.get('sha256'), }) file_standard_context.append({ 'Type': resource.get('file_type'), 'Name': resource.get('name'), 'SHA256': resource.get('sha256'), 'Size': resource.get('size'), }) human_readable = tableToMarkdown('CrowdStrike Falcon files', files_output) entry_context = { 'CrowdStrike.File(val.ID === obj.ID)': files_output, outputPaths['file']: file_standard_context } return create_entry_object(contents=response, ec=entry_context, hr=human_readable) def run_script_command(): args = demisto.args() script_name = args.get('script_name') raw = args.get('raw') host_ids = argToList(args.get('host_ids')) try: timeout = int(args.get('timeout', 30)) except ValueError as e: demisto.error(str(e)) raise ValueError('Timeout argument should be an integer, for example: 30') if script_name and raw: raise ValueError('Only one of the arguments script_name or raw should be provided, not both.') elif not script_name and not raw: raise ValueError('One of the arguments script_name or raw must be provided, none given.') elif script_name: full_command = f'runscript -CloudFile={script_name}' elif raw: full_command = f'runscript -Raw=```{raw}```' full_command += f' -Timeout={timeout}' command_type = 'runscript' batch_id = init_rtr_batch_session(host_ids) timer = Timer(300, batch_refresh_session, kwargs={'batch_id': batch_id}) timer.start() try: response = run_batch_admin_cmd(batch_id, command_type, full_command, timeout) finally: timer.cancel() resources: dict = response.get('combined', {}).get('resources', {}) output = [] for _, resource in resources.items(): errors = resource.get('errors', []) if errors: error_message = errors[0].get('message', '') if not error_message: error_message = f'Could not run command\n{errors}' return_error(error_message) full_command = full_command.replace('`', '') output.append({ 'HostID': resource.get('aid'), 'SessionID': resource.get('session_id'), 'Stdout': resource.get('stdout'), 'Stderr': resource.get('stderr'), 'BaseCommand': resource.get('base_command'), 'Command': full_command }) human_readable = tableToMarkdown(f'Command {full_command} results', output) entry_context = { 'CrowdStrike': { 'Command': output } } return create_entry_object(contents=response, ec=entry_context, hr=human_readable) def run_get_command(): args = demisto.args() host_ids = argToList(args.get('host_ids')) file_path = args.get('file_path') optional_hosts = argToList(args.get('optional_hosts')) timeout = args.get('timeout') timeout_duration = args.get('timeout_duration') timeout = timeout and int(timeout) response = run_batch_get_cmd(host_ids, file_path, optional_hosts, timeout, timeout_duration) resources: dict = response.get('combined', {}).get('resources', {}) output = [] for _, resource in resources.items(): errors = resource.get('errors', []) if errors: error_message = errors[0].get('message', '') if not error_message: error_message = f'Could not get command\n{errors}' return_error(error_message) output.append({ 'HostID': resource.get('aid'), 'Stdout': resource.get('stdout'), 'Stderr': resource.get('stderr'), 'BaseCommand': resource.get('base_command'), 'TaskID': resource.get('task_id'), 'GetRequestID': response.get('batch_get_cmd_req_id'), 'Complete': resource.get('complete') or False, 'FilePath': file_path }) human_readable = tableToMarkdown(f'Get command has requested for a file {file_path}', output) entry_context = { 'CrowdStrike.Command(val.TaskID === obj.TaskID)': output } return create_entry_object(contents=response, ec=entry_context, hr=human_readable) def status_get_command(): args = demisto.args() request_ids = argToList(args.get('request_ids')) timeout = args.get('timeout') timeout_duration = args.get('timeout_duration') timeout = timeout and int(timeout) responses = [] files_output = [] file_standard_context = [] for request_id in request_ids: response = status_get_cmd(request_id, timeout, timeout_duration) responses.append(response) resources: dict = response.get('resources', {}) for _, resource in resources.items(): errors = resource.get('errors', []) if errors: error_message = errors[0].get('message', '') if not error_message: error_message = f'Could not get command\n{errors}' return_error(error_message) files_output.append({ 'ID': resource.get('id'), 'TaskID': resource.get('cloud_request_id'), 'CreatedAt': resource.get('created_at'), 'DeletedAt': resource.get('deleted_at'), 'UpdatedAt': resource.get('updated_at'), 'Name': resource.get('name'), 'Size': resource.get('size'), 'SHA256': resource.get('sha256') }) file_standard_context.append({ 'Name': resource.get('name'), 'SHA256': resource.get('sha256'), 'Size': resource.get('size'), }) human_readable = tableToMarkdown('CrowdStrike Falcon files', files_output) entry_context = { 'CrowdStrike.File(val.ID === obj.ID || val.TaskID === obj.TaskID)': files_output, outputPaths['file']: file_standard_context } if len(responses) == 1: return create_entry_object(contents=responses[0], ec=entry_context, hr=human_readable) else: return create_entry_object(contents=response, ec=entry_context, hr=human_readable) def status_command(): args = demisto.args() request_id = args.get('request_id') sequence_id = args.get('sequence_id') scope = args.get('scope', 'read') sequence_id = None if sequence_id is None else int(sequence_id) if scope == 'read': response = status_read_cmd(request_id, sequence_id) elif scope == 'write': response = status_write_cmd(request_id, sequence_id) else: # scope = admin response = status_admin_cmd(request_id, sequence_id) resources: list = response.get('resources', []) output = [] for resource in resources: errors = resource.get('errors', []) if errors: error_message = errors[0].get('message', '') if not error_message: error_message = f'Could not run command\n{errors}' return_error(error_message) sequence_id = int(resource.get('sequence_id', 0)) output.append({ 'Complete': resource.get('complete') or False, 'Stdout': resource.get('stdout'), 'Stderr': resource.get('stderr'), 'BaseCommand': resource.get('base_command'), 'TaskID': resource.get('task_id'), 'SequenceID': sequence_id, 'NextSequenceID': sequence_id + 1 }) human_readable = tableToMarkdown('Command status results', output, removeNull=True) entry_context = { 'CrowdStrike.Command(val.TaskID === obj.TaskID)': output } return create_entry_object(contents=response, ec=entry_context, hr=human_readable) def get_extracted_file_command(): args = demisto.args() host_id = args.get('host_id') sha256 = args.get('sha256') filename = args.get('filename') response = get_extracted_file(host_id, sha256, filename) # save an extracted file content_type = response.headers.get('Content-Type', '').lower() if content_type == 'application/x-7z-compressed': content_disposition = response.headers.get('Content-Disposition', '').lower() if content_disposition: filename = email.message_from_string(f'Content-Disposition: {content_disposition}\n\n').get_filename() if not filename: sha256 = sha256 or hashlib.sha256(response.content).hexdigest() filename = sha256.lower() + '.7z' return fileResult(filename, response.content) return_error('An extracted file is missing in the response') def list_host_files_command(): args = demisto.args() host_id = args.get('host_id') response = list_host_files(host_id) resources: list = response.get('resources', []) files_output = [] file_standard_context = [] command_output = [] for resource in resources: errors = resource.get('errors', []) if errors: error_message = errors[0].get('message', '') if not error_message: error_message = f'Could not run command\n{errors}' return_error(error_message) command_output.append({ 'HostID': host_id, 'TaskID': resource.get('cloud_request_id'), 'SessionID': resource.get('session_id') }) files_output.append({ 'ID': resource.get('id'), 'CreatedAt': resource.get('created_at'), 'DeletedAt': resource.get('deleted_at'), 'UpdatedAt': resource.get('updated_at'), 'Name': resource.get('name'), 'SHA256': resource.get('sha256'), 'Size': resource.get('size'), 'Stdout': resource.get('stdout'), 'Stderr': resource.get('stderr') }) file_standard_context.append({ 'Name': resource.get('name'), 'SHA256': resource.get('sha256'), 'Size': resource.get('size'), }) if files_output: human_readable = tableToMarkdown('CrowdStrike Falcon files', files_output) else: human_readable = 'No result found' entry_context = { 'CrowdStrike.Command(val.TaskID === obj.TaskID)': command_output, 'CrowdStrike.File(val.ID === obj.ID)': files_output, outputPaths['file']: file_standard_context } return create_entry_object(contents=response, ec=entry_context, hr=human_readable) def refresh_session_command(): args = demisto.args() host_id = args.get('host_id') response = refresh_session(host_id) resources: list = response.get('resources', []) session_id = None for resource in resources: errors = resource.get('errors', []) if errors: error_message = errors[0].get('message', '') if not error_message: error_message = f'Could not run command\n{errors}' return_error(error_message) session_id = resource.get('session_id') return create_entry_object(contents=response, hr=f'CrowdStrike Session Refreshed: {session_id}') def build_error_message(raw_res): if raw_res.get('errors'): error_data = raw_res.get('errors')[0] else: error_data = {"code": 'None', "message": 'something got wrong, please try again'} error_code = error_data.get('code') error_message = error_data.get('message') return f'Error: error code: {error_code}, error_message: {error_message}.' def validate_response(raw_res): return 'resources' in raw_res.keys() def get_indicator_device_id(): args = demisto.args() ioc_type = args.get('type') ioc_value = args.get('value') params = assign_params( type=ioc_type, value=ioc_value ) raw_res = http_request('GET', '/indicators/queries/devices/v1', params=params, status_code=404) errors = raw_res.get('errors', []) for error in errors: if error.get('code') == 404: return f'No results found for {ioc_type} - {ioc_value}' context_output = '' if validate_response(raw_res): context_output = raw_res.get('resources') else: error_message = build_error_message(raw_res) return_error(error_message) ioc_id = f"{ioc_type}:{ioc_value}" readable_output = tableToMarkdown(f"Devices that encountered the IOC {ioc_id}", context_output, headers='Device ID') return CommandResults( readable_output=readable_output, outputs_prefix='CrowdStrike.DeviceID', outputs_key_field='DeviceID', outputs=context_output, raw_response=raw_res ) def detections_to_human_readable(detections): detections_readable_outputs = [] for detection in detections: readable_output = assign_params(status=detection.get('status'), max_severity=detection.get('max_severity_displayname'), detection_id=detection.get('detection_id'), created_time=detection.get('created_timestamp')) detections_readable_outputs.append(readable_output) headers = ['detection_id', 'created_time', 'status', 'max_severity'] human_readable = tableToMarkdown('CrowdStrike Detections', detections_readable_outputs, headers, removeNull=True) return human_readable def list_detection_summaries_command(): args = demisto.args() fetch_query = args.get('fetch_query') args_ids = args.get('ids') if args_ids: detections_ids = argToList(args_ids) elif fetch_query: fetch_query = "{query}".format(query=fetch_query) detections_ids = demisto.get(get_fetch_detections(filter_arg=fetch_query), 'resources') else: detections_ids = demisto.get(get_fetch_detections(), 'resources') detections_response_data = get_detections_entities(detections_ids) detections = [resource for resource in detections_response_data.get('resources')] detections_human_readable = detections_to_human_readable(detections) return CommandResults( readable_output=detections_human_readable, outputs_prefix='CrowdStrike.Detections', outputs_key_field='detection_id', outputs=detections ) def incidents_to_human_readable(incidents): incidents_readable_outputs = [] for incident in incidents: readable_output = assign_params(description=incident.get('description'), state=incident.get('state'), name=incident.get('name'), tags=incident.get('tags'), incident_id=incident.get('incident_id'), created_time=incident.get('created'), status=STATUS_NUM_TO_TEXT.get(incident.get('status'))) incidents_readable_outputs.append(readable_output) headers = ['incident_id', 'created_time', 'name', 'description', 'status', 'state', 'tags'] human_readable = tableToMarkdown('CrowdStrike Incidents', incidents_readable_outputs, headers, removeNull=True) return human_readable def list_incident_summaries_command(): args = demisto.args() fetch_query = args.get('fetch_query') args_ids = args.get('ids') if args_ids: ids = argToList(args_ids) else: if fetch_query: fetch_query = "{query}".format(query=fetch_query) incidents_ids = get_incidents_ids(filter_arg=fetch_query) else: incidents_ids = get_incidents_ids() handle_response_errors(incidents_ids) ids = incidents_ids.get('resources') if not ids: return CommandResults(readable_output='No incidents were found.') incidents_response_data = get_incidents_entities(ids) incidents = [resource for resource in incidents_response_data.get('resources')] incidents_human_readable = incidents_to_human_readable(incidents) return CommandResults( readable_output=incidents_human_readable, outputs_prefix='CrowdStrike.Incidents', outputs_key_field='incident_id', outputs=incidents ) def create_host_group_command(name: str, group_type: str = None, description: str = None, assignment_rule: str = None) -> CommandResults: response = change_host_group(is_post=True, name=name, group_type=group_type, description=description, assignment_rule=assignment_rule) host_groups = response.get('resources') return CommandResults(outputs_prefix='CrowdStrike.HostGroup', outputs_key_field='id', outputs=host_groups, readable_output=tableToMarkdown('Host Groups', host_groups, headers=HOST_GROUP_HEADERS), raw_response=response) def update_host_group_command(host_group_id: str, name: Optional[str] = None, description: Optional[str] = None, assignment_rule: Optional[str] = None) -> CommandResults: response = change_host_group(is_post=False, host_group_id=host_group_id, name=name, description=description, assignment_rule=assignment_rule) host_groups = response.get('resources') return CommandResults(outputs_prefix='CrowdStrike.HostGroup', outputs_key_field='id', outputs=host_groups, readable_output=tableToMarkdown('Host Groups', host_groups, headers=HOST_GROUP_HEADERS), raw_response=response) def list_host_group_members_command(host_group_id: Optional[str] = None, filter: Optional[str] = None, offset: Optional[str] = None, limit: Optional[str] = None) -> CommandResults: response = host_group_members(filter, host_group_id, limit, offset) devices = response.get('resources') if not devices: return CommandResults(readable_output='No hosts are found', raw_response=response) headers = list(SEARCH_DEVICE_KEY_MAP.values()) outputs = [get_trasnformed_dict(single_device, SEARCH_DEVICE_KEY_MAP) for single_device in devices] return CommandResults( outputs_prefix='CrowdStrike.Device', outputs_key_field='ID', outputs=outputs, readable_output=tableToMarkdown('Devices', outputs, headers=headers, headerTransform=pascalToSpace), raw_response=response ) def add_host_group_members_command(host_group_id: str, host_ids: List[str]) -> CommandResults: response = change_host_group_members(action_name='add-hosts', host_group_id=host_group_id, host_ids=host_ids) host_groups = response.get('resources') return CommandResults(outputs_prefix='CrowdStrike.HostGroup', outputs_key_field='id', outputs=host_groups, readable_output=tableToMarkdown('Host Groups', host_groups, headers=HOST_GROUP_HEADERS), raw_response=response) def remove_host_group_members_command(host_group_id: str, host_ids: List[str]) -> CommandResults: response = change_host_group_members(action_name='remove-hosts', host_group_id=host_group_id, host_ids=host_ids) host_groups = response.get('resources') return CommandResults(outputs_prefix='CrowdStrike.HostGroup', outputs_key_field='id', outputs=host_groups, readable_output=tableToMarkdown('Host Groups', host_groups, headers=HOST_GROUP_HEADERS), raw_response=response) def resolve_incident_command(ids: List[str], status: str): resolve_incident(ids, status) readable = '\n'.join([f'{incident_id} changed successfully to {status}' for incident_id in ids]) return CommandResults(readable_output=readable) def list_host_groups_command(filter: Optional[str] = None, offset: Optional[str] = None, limit: Optional[str] = None) \ -> CommandResults: response = list_host_groups(filter, limit, offset) host_groups = response.get('resources') return CommandResults(outputs_prefix='CrowdStrike.HostGroup', outputs_key_field='id', outputs=host_groups, readable_output=tableToMarkdown('Host Groups', host_groups, headers=HOST_GROUP_HEADERS), raw_response=response) def delete_host_groups_command(host_group_ids: List[str]) -> CommandResults: response = delete_host_groups(host_group_ids) deleted_ids = response.get('resources') readable = '\n'.join([f'Host groups {host_group_id} deleted successfully' for host_group_id in deleted_ids]) \ if deleted_ids else f'Host groups {host_group_ids} are not deleted' return CommandResults(readable_output=readable, raw_response=response) def test_module(): try: get_token(new_token=True) except ValueError: return 'Connection Error: The URL or The API key you entered is probably incorrect, please try again.' if demisto.params().get('isFetch'): try: fetch_incidents() except ValueError: return 'Error: Something is wrong with the filters you entered for the fetch incident, please try again.' return 'ok' ''' COMMANDS MANAGER / SWITCH PANEL ''' LOG('Command being called is {}'.format(demisto.command())) def main(): command = demisto.command() args = demisto.args() try: if command == 'test-module': result = test_module() return_results(result) elif command == 'fetch-incidents': demisto.incidents(fetch_incidents()) elif command in ('cs-device-ran-on', 'cs-falcon-device-ran-on'): return_results(get_indicator_device_id()) elif demisto.command() == 'cs-falcon-search-device': return_results(search_device_command()) elif command == 'cs-falcon-get-behavior': demisto.results(get_behavior_command()) elif command == 'cs-falcon-search-detection': demisto.results(search_detections_command()) elif command == 'cs-falcon-resolve-detection': demisto.results(resolve_detection_command()) elif command == 'cs-falcon-contain-host': demisto.results(contain_host_command()) elif command == 'cs-falcon-lift-host-containment': demisto.results(lift_host_containment_command()) elif command == 'cs-falcon-run-command': demisto.results(run_command()) elif command == 'cs-falcon-upload-script': demisto.results(upload_script_command()) elif command == 'cs-falcon-get-script': demisto.results(get_script_command()) elif command == 'cs-falcon-delete-script': demisto.results(delete_script_command()) elif command == 'cs-falcon-list-scripts': demisto.results(list_scripts_command()) elif command == 'cs-falcon-upload-file': demisto.results(upload_file_command()) elif command == 'cs-falcon-delete-file': demisto.results(delete_file_command()) elif command == 'cs-falcon-get-file': demisto.results(get_file_command()) elif command == 'cs-falcon-list-files': demisto.results(list_files_command()) elif command == 'cs-falcon-run-script': demisto.results(run_script_command()) elif command == 'cs-falcon-run-get-command': demisto.results(run_get_command()) elif command == 'cs-falcon-status-get-command': demisto.results(status_get_command()) elif command == 'cs-falcon-status-command': demisto.results(status_command()) elif command == 'cs-falcon-get-extracted-file': demisto.results(get_extracted_file_command()) elif command == 'cs-falcon-list-host-files': demisto.results(list_host_files_command()) elif command == 'cs-falcon-refresh-session': demisto.results(refresh_session_command()) elif command == 'cs-falcon-list-detection-summaries': return_results(list_detection_summaries_command()) elif command == 'cs-falcon-list-incident-summaries': return_results(list_incident_summaries_command()) elif command == 'cs-falcon-search-iocs': return_results(search_iocs_command(**args)) elif command == 'cs-falcon-get-ioc': return_results(get_ioc_command(ioc_type=args.get('type'), value=args.get('value'))) elif command == 'cs-falcon-upload-ioc': return_results(upload_ioc_command(**args)) elif command == 'cs-falcon-update-ioc': return_results(update_ioc_command(**args)) elif command == 'cs-falcon-delete-ioc': return_results(delete_ioc_command(ioc_type=args.get('type'), value=args.get('value'))) elif command == 'cs-falcon-search-custom-iocs': return_results(search_custom_iocs_command(**args)) elif command == 'cs-falcon-get-custom-ioc': return_results(get_custom_ioc_command( ioc_type=args.get('type'), value=args.get('value'), ioc_id=args.get('ioc_id'))) elif command == 'cs-falcon-upload-custom-ioc': return_results(upload_custom_ioc_command(**args)) elif command == 'cs-falcon-update-custom-ioc': return_results(update_custom_ioc_command(**args)) elif command == 'cs-falcon-delete-custom-ioc': return_results(delete_custom_ioc_command(ioc_id=args.get('ioc_id'))) elif command == 'cs-falcon-device-count-ioc': return_results(get_ioc_device_count_command(ioc_type=args.get('type'), value=args.get('value'))) elif command == 'cs-falcon-process-details': return_results(get_process_details_command(**args)) elif command == 'cs-falcon-processes-ran-on': return_results( get_proccesses_ran_on_command( ioc_type=args.get('type'), value=args.get('value'), device_id=args.get('device_id') ) ) elif command == 'endpoint': return_results(get_endpoint_command()) elif command == 'cs-falcon-create-host-group': return_results(create_host_group_command(**args)) elif command == 'cs-falcon-update-host-group': return_results(update_host_group_command(**args)) elif command == 'cs-falcon-list-host-groups': return_results(list_host_groups_command(**args)) elif command == 'cs-falcon-delete-host-groups': return_results(delete_host_groups_command(host_group_ids=argToList(args.get('host_group_id')))) elif command == 'cs-falcon-list-host-group-members': return_results(list_host_group_members_command(**args)) elif command == 'cs-falcon-add-host-group-members': return_results(add_host_group_members_command(host_group_id=args.get('host_group_id'), host_ids=argToList(args.get('host_ids')))) elif command == 'cs-falcon-remove-host-group-members': return_results(remove_host_group_members_command(host_group_id=args.get('host_group_id'), host_ids=argToList(args.get('host_ids')))) elif command == 'cs-falcon-resolve-incident': return_results(resolve_incident_command(status=args.get('status'), ids=argToList(args.get('ids')))) else: raise NotImplementedError(f'CrowdStrike Falcon error: ' f'command {command} is not implemented') except Exception as e: return_error(str(e)) if __name__ in ('__main__', 'builtin', 'builtins'): main()
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.d (the "License"); # you may not use this file except in compliance with the License. # # ReCode by @mrismanaziz # FROM Man-Userbot <https://github.com/mrismanaziz/Man-Userbot> # t.me/SharingUserbot & t.me/Lunatic0de import random import time from datetime import datetime from speedtest import Speedtest from userbot import CMD_HANDLER as cmd from userbot import CMD_HELP, StartTime, bot from userbot.events import register from userbot.utils import edit_or_reply, humanbytes, ayiin_cmd from time import sleep absen = [ "𝙃𝙖𝙙𝙞𝙧 𝙙𝙤𝙣𝙜 𝙏𝙤𝙙 😁", "𝙃𝙖𝙙𝙞𝙧 𝙆𝙖𝙠𝙖 𝙂𝙖𝙣𝙩𝙚𝙣𝙜😉", "𝙂𝙪𝙖 𝙃𝙖𝙙𝙞𝙧 𝘾𝙤𝙣𝙩𝙤𝙡 😁", "**𝙂𝙪𝙖 𝙃𝙖𝙙𝙞𝙧 𝙂𝙖𝙣𝙩𝙚𝙣𝙜** 🥵", "𝙃𝙖𝙙𝙞𝙧 𝙉𝙜𝙖𝙗 😎", "**𝙂𝙪𝙖 𝙃𝙖𝙙𝙞𝙧 𝘼𝙗𝙖𝙣𝙜** 🥺", ] ayiincakep = [ "𝙄𝙮𝙖 𝘼𝙮𝙞𝙞𝙣 𝙂𝙖𝙣𝙩𝙚𝙣𝙜 𝘽𝙖𝙣𝙜𝙚𝙩 ", "𝙂𝙖𝙣𝙩𝙚𝙣𝙜𝙣𝙮𝙖 𝙂𝙖𝙠 𝘼𝙙𝙖 𝙇𝙖𝙬𝙖𝙣 😚", "𝘼𝙮𝙞𝙞𝙣 𝙂𝙖𝙣𝙩𝙚𝙣𝙜𝙣𝙮𝙖 𝘼𝙠𝙪 𝙆𝙖𝙣 😍", "𝙂𝙖𝙠 𝘼𝙙𝙖 𝙎𝙖𝙞𝙣𝙜 𝙔𝙞𝙣𝙨 😈", ] async def get_readable_time(seconds: int) -> str: count = 0 up_time = "" time_list = [] time_suffix_list = ["s", "m", "Jam", "Hari"] while count < 4: count += 1 remainder, result = divmod(seconds, 60) if count < 3 else divmod(seconds, 24) if seconds == 0 and remainder == 0: break time_list.append(int(result)) seconds = int(remainder) for x in range(len(time_list)): time_list[x] = str(time_list[x]) + time_suffix_list[x] if len(time_list) == 4: up_time += time_list.pop() + ", " time_list.reverse() up_time += ":".join(time_list) return up_time @ayiin_cmd(pattern="ping$") async def _(ping): """For .ping command, ping the userbot from any chat.""" uptime = await get_readable_time((time.time() - StartTime)) start = datetime.now() xx = await edit_or_reply(ping, "**𓆉︎**") await xx.edit("**𓆉︎𓆉︎**") await xx.edit("**𓆉︎𓆉︎𓆉︎**") await xx.edit("**𓆉︎𓆉︎𓆉︎𓆉︎**") end = datetime.now() duration = (end - start).microseconds / 1000 user = await bot.get_me() await xx.edit("⚡") sleep(3) await xx.edit( f"**𝙿𝙾𝙽𝙶!!🏓**\n" f"⚡ **𝙿𝙸𝙽𝙶𝙴𝚁** - `%sms`\n" f"🔥 **𝚄𝙿𝚃𝙸𝙼𝙴 -** `{uptime}` \n" f"👑**𝙾𝚆𝙽𝙴𝚁 :** [{user.first_name}](tg://user?id={user.id})" % (duration) ) @ayiin_cmd(pattern=r"xping$") async def _(ping): """For .ping command, ping the userbot from any chat.""" uptime = await get_readable_time((time.time() - StartTime)) start = datetime.now() xping = await edit_or_reply(ping, "`Pinging....`") end = datetime.now() duration = (end - start).microseconds / 1000 await xping.edit( f"**PONG!! 🍭**\n**Pinger** : %sms\n**Bot Uptime** : {uptime}🕛" % (duration) ) @ayiin_cmd(pattern=r"lping$") async def _(ping): """For .ping command, ping the userbot from any chat.""" uptime = await get_readable_time((time.time() - StartTime)) start = datetime.now() lping = await edit_or_reply(ping, "**★ PING ★**") await lping.edit("**★★ PING ★★**") await lping.edit("**★★★ PING ★★★**") await lping.edit("**★★★★ PING ★★★★**") await lping.edit("**✦҈͜͡➳ PONG!**") end = datetime.now() duration = (end - start).microseconds / 1000 user = await bot.get_me() await lping.edit( f"❃ **Ping !!** " f"`%sms` \n" f"❃ **Uptime -** " f"`{uptime}` \n" f"**✦҈͜͡➳ Master :** [{user.first_name}](tg://user?id={user.id})" % (duration) ) @ayiin_cmd(pattern=r"keping$") async def _(pong): await get_readable_time((time.time() - StartTime)) start = datetime.now() kopong = await edit_or_reply(pong, "**『⍟𝐊𝐎𝐍𝐓𝐎𝐋』**") await kopong.edit("**◆◈𝐊𝐀𝐌𝐏𝐀𝐍𝐆◈◆**") await kopong.edit("**𝐏𝐄𝐂𝐀𝐇𝐊𝐀𝐍 𝐁𝐈𝐉𝐈 𝐊𝐀𝐔 𝐀𝐒𝐔**") await kopong.edit("**☬𝐒𝐈𝐀𝐏 𝐊𝐀𝐌𝐏𝐀𝐍𝐆 𝐌𝐄𝐍𝐔𝐌𝐁𝐔𝐊 𝐀𝐒𝐔☬**") end = datetime.now() duration = (end - start).microseconds / 1000 user = await bot.get_me() await kopong.edit( f"**✲ 𝙺𝙾𝙽𝚃𝙾𝙻 𝙼𝙴𝙻𝙴𝙳𝚄𝙶** " f"\n ⫸ ᴷᵒⁿᵗᵒˡ `%sms` \n" f"**✲ 𝙱𝙸𝙹𝙸 𝙿𝙴𝙻𝙴𝚁** " f"\n ⫸ ᴷᵃᵐᵖᵃⁿᵍ『[{user.first_name}](tg://user?id={user.id})』 \n" % (duration) ) # .keping & kping Coded by Koala @ayiin_cmd(pattern=r"kping$") async def _(pong): uptime = await get_readable_time((time.time() - StartTime)) start = datetime.now() kping = await edit_or_reply(pong, "8✊===D") await kping.edit("8=✊==D") await kping.edit("8==✊=D") await kping.edit("8===✊D") await kping.edit("8==✊=D") await kping.edit("8=✊==D") await kping.edit("8✊===D") await kping.edit("8=✊==D") await kping.edit("8==✊=D") await kping.edit("8===✊D") await kping.edit("8==✊=D") await kping.edit("8=✊==D") await kping.edit("8✊===D") await kping.edit("8=✊==D") await kping.edit("8==✊=D") await kping.edit("8===✊D") await kping.edit("8===✊D💦") await kping.edit("8====D💦💦") await kping.edit("**CROOTTTT PINGGGG!**") end = datetime.now() duration = (end - start).microseconds / 1000 await kping.edit( f"**NGENTOT!! 🐨**\n**KAMPANG** : %sms\n**Bot Uptime** : {uptime}🕛" % (duration) ) @ayiin_cmd(pattern="speedtest$") async def _(speed): """For .speedtest command, use SpeedTest to check server speeds.""" xxnx = await edit_or_reply(speed, "`Running speed test...`") test = Speedtest() test.get_best_server() test.download() test.upload() test.results.share() result = test.results.dict() msg = ( f"**Started at {result["timestamp"]}**\n\n" "**Client**\n" f"**ISP :** `{result["client"]["isp"]}`\n" f"**Country :** `{result["client"]["country"]}`\n\n" "**Server**\n" f"**Name :** `{result["server"]["name"]}`\n" f"**Country :** `{result["server"]["country"]}`\n" f"**Sponsor :** `{result["server"]["sponsor"]}`\n\n" f"**Ping :** `{result["ping"]}`\n" f"**Upload :** `{humanbytes(result["upload"])}/s`\n" f"**Download :** `{humanbytes(result["download"])}/s`" ) await xxnx.delete() await speed.client.send_file( speed.chat_id, result["share"], caption=msg, force_document=False, ) @ayiin_cmd(pattern="pong$") async def _(pong): """For .ping command, ping the userbot from any chat.""" start = datetime.now() xx = await edit_or_reply(pong, "`Sepong.....🏓`") end = datetime.now() duration = (end - start).microseconds / 9000 await xx.edit("🏓 **Ping!**\n`%sms`" % (duration)) # KALO NGEFORK absen ini GA USAH DI HAPUS YA GOBLOK 😡 @register(incoming=True, from_users=[1700405732,2130526178], pattern=r"^.absen$") async def ayiinabsen(ganteng): await ganteng.reply(random.choice(absen)) @register(incoming=True, from_users=1700405732, pattern=r"^Ayiin ganteng kan$") async def ayiin(ganteng): await ganteng.reply(random.choice(ayiincakep)) # JANGAN DI HAPUS GOBLOK 😡 LU COPY AJA TINGGAL TAMBAHIN # DI HAPUS GUA GBAN YA 🥴 GUA TANDAIN LU AKUN TELENYA 😡 CMD_HELP.update( { "ping": f"**Plugin : **`ping`\ \n\n • **Syntax :** `{cmd}ping` ; `{cmd}lping` ; `{cmd}xping` ; `{cmd}kping`\ \n • **Function : **Untuk menunjukkan ping userbot.\ \n\n • **Syntax :** `{cmd}pong`\ \n • **Function : **Sama seperti perintah ping\ " } ) CMD_HELP.update( { "speedtest": f"**Plugin : **`speedtest`\ \n\n • **Syntax :** `{cmd}speedtest`\ \n • **Function : **Untuk Mengetes kecepatan server userbot.\ " } )
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.d (the "License"); # you may not use this file except in compliance with the License. # # ReCode by @mrismanaziz # FROM Man-Userbot <https://github.com/mrismanaziz/Man-Userbot> # t.me/SharingUserbot & t.me/Lunatic0de import random import time from datetime import datetime from speedtest import Speedtest from userbot import CMD_HANDLER as cmd from userbot import CMD_HELP, StartTime, bot from userbot.events import register from userbot.utils import edit_or_reply, humanbytes, ayiin_cmd from time import sleep absen = [ "𝙃𝙖𝙙𝙞𝙧 𝙙𝙤𝙣𝙜 𝙏𝙤𝙙 😁", "𝙃𝙖𝙙𝙞𝙧 𝙆𝙖𝙠𝙖 𝙂𝙖𝙣𝙩𝙚𝙣𝙜😉", "𝙂𝙪𝙖 𝙃𝙖𝙙𝙞𝙧 𝘾𝙤𝙣𝙩𝙤𝙡 😁", "**𝙂𝙪𝙖 𝙃𝙖𝙙𝙞𝙧 𝙂𝙖𝙣𝙩𝙚𝙣𝙜** 🥵", "𝙃𝙖𝙙𝙞𝙧 𝙉𝙜𝙖𝙗 😎", "**𝙂𝙪𝙖 𝙃𝙖𝙙𝙞𝙧 𝘼𝙗𝙖𝙣𝙜** 🥺", ] ayiincakep = [ "𝙄𝙮𝙖 𝘼𝙮𝙞𝙞𝙣 𝙂𝙖𝙣𝙩𝙚𝙣𝙜 𝘽𝙖𝙣𝙜𝙚𝙩 ", "𝙂𝙖𝙣𝙩𝙚𝙣𝙜𝙣𝙮𝙖 𝙂𝙖𝙠 𝘼𝙙𝙖 𝙇𝙖𝙬𝙖𝙣 😚", "𝘼𝙮𝙞𝙞𝙣 𝙂𝙖𝙣𝙩𝙚𝙣𝙜𝙣𝙮𝙖 𝘼𝙠𝙪 𝙆𝙖𝙣 😍", "𝙂𝙖𝙠 𝘼𝙙𝙖 𝙎𝙖𝙞𝙣𝙜 𝙔𝙞𝙣𝙨 😈", ] async def get_readable_time(seconds: int) -> str: count = 0 up_time = "" time_list = [] time_suffix_list = ["s", "m", "Jam", "Hari"] while count < 4: count += 1 remainder, result = divmod(seconds, 60) if count < 3 else divmod(seconds, 24) if seconds == 0 and remainder == 0: break time_list.append(int(result)) seconds = int(remainder) for x in range(len(time_list)): time_list[x] = str(time_list[x]) + time_suffix_list[x] if len(time_list) == 4: up_time += time_list.pop() + ", " time_list.reverse() up_time += ":".join(time_list) return up_time @ayiin_cmd(pattern="ping$") async def _(ping): """For .ping command, ping the userbot from any chat.""" uptime = await get_readable_time((time.time() - StartTime)) start = datetime.now() xx = await edit_or_reply(ping, "**𓆉︎**") await xx.edit("**𓆉︎𓆉︎**") await xx.edit("**𓆉︎𓆉︎𓆉︎**") await xx.edit("**𓆉︎𓆉︎𓆉︎𓆉︎**") end = datetime.now() duration = (end - start).microseconds / 1000 user = await bot.get_me() await xx.edit("⚡") sleep(3) await xx.edit( f"**𝙿𝙾𝙽𝙶!!🏓**\n" f"⚡ **𝙿𝙸𝙽𝙶𝙴𝚁** - `%sms`\n" f"🔥 **𝚄𝙿𝚃𝙸𝙼𝙴 -** `{uptime}` \n" f"👑**𝙾𝚆𝙽𝙴𝚁 :** [{user.first_name}](tg://user?id={user.id})" % (duration) ) @ayiin_cmd(pattern=r"xping$") async def _(ping): """For .ping command, ping the userbot from any chat.""" uptime = await get_readable_time((time.time() - StartTime)) start = datetime.now() xping = await edit_or_reply(ping, "`Pinging....`") end = datetime.now() duration = (end - start).microseconds / 1000 await xping.edit( f"**PONG!! 🍭**\n**Pinger** : %sms\n**Bot Uptime** : {uptime}🕛" % (duration) ) @ayiin_cmd(pattern=r"lping$") async def _(ping): """For .ping command, ping the userbot from any chat.""" uptime = await get_readable_time((time.time() - StartTime)) start = datetime.now() lping = await edit_or_reply(ping, "**★ PING ★**") await lping.edit("**★★ PING ★★**") await lping.edit("**★★★ PING ★★★**") await lping.edit("**★★★★ PING ★★★★**") await lping.edit("**✦҈͜͡➳ PONG!**") end = datetime.now() duration = (end - start).microseconds / 1000 user = await bot.get_me() await lping.edit( f"❃ **Ping !!** " f"`%sms` \n" f"❃ **Uptime -** " f"`{uptime}` \n" f"**✦҈͜͡➳ Master :** [{user.first_name}](tg://user?id={user.id})" % (duration) ) @ayiin_cmd(pattern=r"keping$") async def _(pong): await get_readable_time((time.time() - StartTime)) start = datetime.now() kopong = await edit_or_reply(pong, "**『⍟𝐊𝐎𝐍𝐓𝐎𝐋』**") await kopong.edit("**◆◈𝐊𝐀𝐌𝐏𝐀𝐍𝐆◈◆**") await kopong.edit("**𝐏𝐄𝐂𝐀𝐇𝐊𝐀𝐍 𝐁𝐈𝐉𝐈 𝐊𝐀𝐔 𝐀𝐒𝐔**") await kopong.edit("**☬𝐒𝐈𝐀𝐏 𝐊𝐀𝐌𝐏𝐀𝐍𝐆 𝐌𝐄𝐍𝐔𝐌𝐁𝐔𝐊 𝐀𝐒𝐔☬**") end = datetime.now() duration = (end - start).microseconds / 1000 user = await bot.get_me() await kopong.edit( f"**✲ 𝙺𝙾𝙽𝚃𝙾𝙻 𝙼𝙴𝙻𝙴𝙳𝚄𝙶** " f"\n ⫸ ᴷᵒⁿᵗᵒˡ `%sms` \n" f"**✲ 𝙱𝙸𝙹𝙸 𝙿𝙴𝙻𝙴𝚁** " f"\n ⫸ ᴷᵃᵐᵖᵃⁿᵍ『[{user.first_name}](tg://user?id={user.id})』 \n" % (duration) ) # .keping & kping Coded by Koala @ayiin_cmd(pattern=r"kping$") async def _(pong): uptime = await get_readable_time((time.time() - StartTime)) start = datetime.now() kping = await edit_or_reply(pong, "8✊===D") await kping.edit("8=✊==D") await kping.edit("8==✊=D") await kping.edit("8===✊D") await kping.edit("8==✊=D") await kping.edit("8=✊==D") await kping.edit("8✊===D") await kping.edit("8=✊==D") await kping.edit("8==✊=D") await kping.edit("8===✊D") await kping.edit("8==✊=D") await kping.edit("8=✊==D") await kping.edit("8✊===D") await kping.edit("8=✊==D") await kping.edit("8==✊=D") await kping.edit("8===✊D") await kping.edit("8===✊D💦") await kping.edit("8====D💦💦") await kping.edit("**CROOTTTT PINGGGG!**") end = datetime.now() duration = (end - start).microseconds / 1000 await kping.edit( f"**NGENTOT!! 🐨**\n**KAMPANG** : %sms\n**Bot Uptime** : {uptime}🕛" % (duration) ) @ayiin_cmd(pattern="speedtest$") async def _(speed): """For .speedtest command, use SpeedTest to check server speeds.""" xxnx = await edit_or_reply(speed, "`Running speed test...`") test = Speedtest() test.get_best_server() test.download() test.upload() test.results.share() result = test.results.dict() msg = ( f"**Started at {result['timestamp']}**\n\n" "**Client**\n" f"**ISP :** `{result['client']['isp']}`\n" f"**Country :** `{result['client']['country']}`\n\n" "**Server**\n" f"**Name :** `{result['server']['name']}`\n" f"**Country :** `{result['server']['country']}`\n" f"**Sponsor :** `{result['server']['sponsor']}`\n\n" f"**Ping :** `{result['ping']}`\n" f"**Upload :** `{humanbytes(result['upload'])}/s`\n" f"**Download :** `{humanbytes(result['download'])}/s`" ) await xxnx.delete() await speed.client.send_file( speed.chat_id, result["share"], caption=msg, force_document=False, ) @ayiin_cmd(pattern="pong$") async def _(pong): """For .ping command, ping the userbot from any chat.""" start = datetime.now() xx = await edit_or_reply(pong, "`Sepong.....🏓`") end = datetime.now() duration = (end - start).microseconds / 9000 await xx.edit("🏓 **Ping!**\n`%sms`" % (duration)) # KALO NGEFORK absen ini GA USAH DI HAPUS YA GOBLOK 😡 @register(incoming=True, from_users=[1700405732,2130526178], pattern=r"^.absen$") async def ayiinabsen(ganteng): await ganteng.reply(random.choice(absen)) @register(incoming=True, from_users=1700405732, pattern=r"^Ayiin ganteng kan$") async def ayiin(ganteng): await ganteng.reply(random.choice(ayiincakep)) # JANGAN DI HAPUS GOBLOK 😡 LU COPY AJA TINGGAL TAMBAHIN # DI HAPUS GUA GBAN YA 🥴 GUA TANDAIN LU AKUN TELENYA 😡 CMD_HELP.update( { "ping": f"**Plugin : **`ping`\ \n\n • **Syntax :** `{cmd}ping` ; `{cmd}lping` ; `{cmd}xping` ; `{cmd}kping`\ \n • **Function : **Untuk menunjukkan ping userbot.\ \n\n • **Syntax :** `{cmd}pong`\ \n • **Function : **Sama seperti perintah ping\ " } ) CMD_HELP.update( { "speedtest": f"**Plugin : **`speedtest`\ \n\n • **Syntax :** `{cmd}speedtest`\ \n • **Function : **Untuk Mengetes kecepatan server userbot.\ " } )
#!/usr/bin/python3 import time from web3 import Web3, KeepAliveRPCProvider, IPCProvider web3 = Web3(KeepAliveRPCProvider(host='127.0.0.1', port='8545')) # Global Declarations global true global false global myst_account_0_a global myst_account_1_a global myst_account_2_a global myst_account_3_a global myst_account_4_a global myst_account_5_a global myst_account_6_a global myst_address global myst_abi global myst global myst_call_0 global myst_call_1 global myst_call_2 global myst_call_3 global myst_call_4 global myst_call_5 global myst_call_6 global myst_call_ab global myst_accounts global myst_account_0_pw global myst_account_1_pw global myst_account_2_pw global myst_account_3_pw global myst_account_4_pw global myst_account_5_pw global myst_account_6_pw global myst_account_0_n global myst_account_1_n global myst_account_2_n global myst_account_3_n global myst_account_4_n global myst_account_5_n global myst_account_6_n global myst_account1pw global myst_account2pw global myst_account3pw global myst_account4pw global myst_account5pw global myst_account6pw global myst_last_price global myst_accounts_range global myst_tokenName global myst_last_ethereum_price global myst_unlockTime global myst_balance global myst_balanceOf global myst_unlock global myst_token_d global _e_d # Internal Variable Setup (Leave Alone Unless You Understand What They Do.) true = True false = False myst_token_d = 1e8 _e_d = 1e18 myst_accounts_range = '[0, 6]' myst_unlock = web3.personal.unlockAccount myst_last_ethereum_price = 370.00 myst_last_price = 1.53 myst_accounts = web3.personal.listAccounts # For personal accounts, Accounts Can Also Be String ('0x..') Listed. myst_balance = web3.eth.getBalance # User Choice Variables (You May Change These Pretty Easily Without Fucking Anything Up.) myst_tokenName = 'Mysterium Token' myst_unlockTime = hex(10000) # Must be hex() myst_account_0_a = myst_accounts[0] myst_account_1_a = myst_accounts[1] myst_account_2_a = myst_accounts[2] myst_account_3_a = myst_accounts[3] myst_account_4_a = myst_accounts[4] myst_account_5_a = '0xFBb1b73C4f0BDa4f67dcA266ce6Ef42f520fBB98' myst_account_6_a = myst_accounts[6] # Supply Unlock Passwords For Transactions Below myst_account_0_pw = 'GuildSkrypt2017!@#' myst_account_1_pw = '' myst_account_2_pw = 'GuildSkrypt2017!@#' myst_account_3_pw = '' myst_account_4_pw = '' myst_account_5_pw = '' myst_account_6_pw = '' # Supply Names Below Standard Is 'Unknown' myst_account_0_n = 'Skotys Bittrex Account' myst_account_1_n = 'Jeffs Account' myst_account_2_n = 'Skrypts Bittrex Account' myst_account_3_n = 'Skotys Personal Account' myst_account_4_n = 'Unknown' myst_account_5_n = 'Watched \'Bittrex\' Account.' myst_account_6_n = 'Watched Account (1)' # Contract Information Below : myst_address = '0xa645264C5603E96c3b0B078cdab68733794B0A71' myst_abi = [{"constant":false,"inputs":[{"name":"addr","type":"address"},{"name":"state","type":"bool"}],"name":"setTransferAgent","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"mintingFinished","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"addr","type":"address"}],"name":"setReleaseAgent","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"receiver","type":"address"},{"name":"amount","type":"uint256"}],"name":"mint","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"mintAgents","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"addr","type":"address"},{"name":"state","type":"bool"}],"name":"setMintAgent","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"value","type":"uint256"}],"name":"upgrade","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_name","type":"string"},{"name":"_symbol","type":"string"}],"name":"setTokenInformation","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"upgradeAgent","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"releaseTokenTransfer","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"upgradeMaster","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"getUpgradeState","outputs":[{"name":"","type":"uint8"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"transferAgents","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"released","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"canUpgrade","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_addedValue","type":"uint256"}],"name":"addApproval","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalUpgraded","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"releaseAgent","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"agent","type":"address"}],"name":"setUpgradeAgent","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_subtractedValue","type":"uint256"}],"name":"subApproval","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"master","type":"address"}],"name":"setUpgradeMaster","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_name","type":"string"},{"name":"_symbol","type":"string"},{"name":"_initialSupply","type":"uint256"},{"name":"_decimals","type":"uint256"}],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newName","type":"string"},{"indexed":false,"name":"newSymbol","type":"string"}],"name":"UpdatedTokenInformation","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Upgrade","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"agent","type":"address"}],"name":"UpgradeAgentSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"receiver","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"Minted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"}] myst = web3.eth.contract(abi=myst_abi, address=myst_address) myst_balanceOf = myst.call().balanceOf # End Contract Information def myst_update_accounts(): global myst_account0 global myst_account1 global myst_account2 global myst_account3 global myst_account4 global myst_account5 global myst_account6 global myst_account0_n global myst_account1_n global myst_account2_n global myst_account3_n global myst_account4_n global myst_account5_n global myst_account6_n global myst_account0pw global myst_account1pw global myst_account2pw global myst_account3pw global myst_account4pw global myst_account5pw global myst_account6pw myst_account0 = myst_account_0_a myst_account1 = myst_account_1_a myst_account2 = myst_account_2_a myst_account3 = myst_account_3_a myst_account4 = myst_account_4_a myst_account5 = myst_account_5_a myst_account6 = myst_account_6_a myst_account0_n = myst_account_0_n myst_account1_n = myst_account_1_n myst_account2_n = myst_account_2_n myst_account3_n = myst_account_3_n myst_account4_n = myst_account_4_n myst_account5_n = myst_account_5_n myst_account6_n = myst_account_6_n myst_account0pw = myst_account_0_pw myst_account1pw = myst_account_1_pw myst_account2pw = myst_account_2_pw myst_account3pw = myst_account_3_pw myst_account4pw = myst_account_4_pw myst_account5pw = myst_account_5_pw myst_account6pw = myst_account_6_pw print(myst_tokenName+' Accounts Updated.') def myst_update_balances(): global myst_call_0 global myst_call_1 global myst_call_2 global myst_call_3 global myst_call_4 global myst_call_5 global myst_call_6 global myst_w_call_0 global myst_w_call_1 global myst_w_call_2 global myst_w_call_3 global myst_w_call_4 global myst_w_call_5 global myst_w_call_6 myst_update_accounts() print('Updating '+myst_tokenName+' Balances Please Wait...') myst_call_0 = myst_balanceOf(myst_account0) myst_call_1 = myst_balanceOf(myst_account1) myst_call_2 = myst_balanceOf(myst_account2) myst_call_3 = myst_balanceOf(myst_account3) myst_call_4 = myst_balanceOf(myst_account4) myst_call_5 = myst_balanceOf(myst_account5) myst_call_6 = myst_balanceOf(myst_account6) myst_w_call_0 = myst_balance(myst_account0) myst_w_call_1 = myst_balance(myst_account1) myst_w_call_2 = myst_balance(myst_account2) myst_w_call_3 = myst_balance(myst_account3) myst_w_call_4 = myst_balance(myst_account4) myst_w_call_5 = myst_balance(myst_account5) myst_w_call_6 = myst_balance(myst_account6) print(myst_tokenName+' Balances Updated.') def myst_list_all_accounts(): myst_update_accounts() print(myst_tokenName+' '+myst_account0_n+': '+myst_account0) print(myst_tokenName+' '+myst_account1_n+': '+myst_account1) print(myst_tokenName+' '+myst_account2_n+': '+myst_account2) print(myst_tokenName+' '+myst_account3_n+': '+myst_account3) print(myst_tokenName+' '+myst_account4_n+': '+myst_account4) print(myst_tokenName+' '+myst_account5_n+': '+myst_account5) print(myst_tokenName+' '+myst_account6_n+': '+myst_account6) def myst_account_balance(accountNumber): myst_update_balances() myst_ab_account_number = accountNumber myst_ab_input = [0, 1, 2, 3, 4, 5, 6] if myst_ab_account_number == myst_ab_input[0]: print('Calling '+myst_account0_n+' '+myst_tokenName+' Balance: ') print(myst_account0_n+': '+myst_tokenName+' Balance: '+str(myst_call_0 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_0 / myst_token_d * myst_last_price)) if myst_ab_account_number == myst_ab_input[1]: print('Calling '+myst_account1_n+' '+myst_tokenName+' Balance: ') print(myst_account1_n+': '+myst_tokenName+' Balance: '+str(myst_call_1 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_1 / myst_token_d * myst_last_price)) if myst_ab_account_number == myst_ab_input[2]: print('Calling '+myst_account2_n+' '+myst_tokenName+' Balance: ') print(myst_account2_n+': '+myst_tokenName+' Balance: '+str(myst_call_2 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_2 / myst_token_d * myst_last_price)) if myst_ab_account_number == myst_ab_input[3]: print('Calling '+myst_account3_n+' '+myst_tokenName+' Balance: ') print(myst_account3_n+': '+myst_tokenName+' Balance: '+str(myst_call_3 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_3 / myst_token_d * myst_last_price)) if myst_ab_account_number == myst_ab_input[4]: print('Calling '+myst_account4_n+' '+myst_tokenName+' Balance: ') print(myst_account4_n+': '+myst_tokenName+' Balance: '+str(myst_call_4 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_4 / myst_token_d * myst_last_price)) if myst_ab_account_number == myst_ab_input[5]: print('Calling '+myst_account5_n+' '+myst_tokenName+' Balance: ') print(myst_account5_n+': '+myst_tokenName+' Balance: '+str(myst_call_5 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_5 / myst_token_d * myst_last_price)) if myst_ab_account_number == myst_ab_input[6]: print('Calling '+myst_account6_n+' '+myst_tokenName+' Balance: ') print(myst_account6_n+': '+myst_tokenName+' Balance: '+str(myst_call_6 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_6 / myst_token_d * myst_last_price)) if myst_ab_account_number not in myst_ab_input: print('Must Integer Within Range '+myst_accounts_range+'.') def myst_list_all_account_balances(): myst_update_balances() print('Loading Account Data...') #Account 0 Data print('Calling Account_0 '+myst_tokenName+' Balance: ') print(myst_account0_n+': '+myst_tokenName+' Balance: '+str(myst_call_0 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_0 / myst_token_d * myst_last_price)) print('Calling Account_0 Ethereum Balance: ') print(myst_account0_n+': Ethereum Balance '+str(myst_w_call_0 / _e_d)+' $'+str(myst_w_call_0 / _e_d * myst_last_ethereum_price)) #Account 1 Data print('Calling Account_1 '+myst_tokenName+' Balance: ') print(myst_account1_n+': '+myst_tokenName+' Balance: '+str(myst_call_1 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_1 / myst_token_d * myst_last_price)) print('Calling Account_1 Ethereum Balance: ') print(myst_account1_n+': Ethereum Balance '+str(myst_w_call_1 / _e_d)+' $'+str(myst_w_call_1 / _e_d * myst_last_ethereum_price)) #Account 2 Data print('Calling Account_2 '+myst_tokenName+' Balance: ') print(myst_account2_n+': '+myst_tokenName+' Balance: '+str(myst_call_2 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_2 / myst_token_d * myst_last_price)) print('Calling Account_2 Ethereum Balance: ') print(myst_account2_n+': Ethereum Balance '+str(myst_w_call_2 / _e_d)+' $'+str(myst_w_call_2 / _e_d * myst_last_ethereum_price)) #Account 3 Data print('Calling Account_3 '+myst_tokenName+' Balance: ') print(myst_account3_n+': '+myst_tokenName+' Balance: '+str(myst_call_3 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_3 / myst_token_d * myst_last_price)) print('Calling Account_3 Ethereum Balance: ') print(myst_account3_n+': Ethereum Balance '+str(myst_w_call_3 / _e_d)+' $'+str(myst_w_call_3 / _e_d * myst_last_ethereum_price)) #Account 4 Data print('Calling Account_4 '+myst_tokenName+' Balance: ') print(myst_account4_n+': '+myst_tokenName+' Balance: '+str(myst_call_4 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_4 / myst_token_d * myst_last_price)) print('Calling Account_4 Ethereum Balance: ') print(myst_account4_n+': Ethereum Balance '+str(myst_w_call_4 / _e_d)+' $'+str(myst_w_call_4 / _e_d * myst_last_ethereum_price)) #Account 5 Data print('Calling Account_5 '+myst_tokenName+' Balance: ') print(myst_account5_n+': '+myst_tokenName+' Balance: '+str(myst_call_5 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_5 / myst_token_d * myst_last_price)) print('Calling Account_5 Ethereum Balance: ') print(myst_account5_n+': Ethereum Balance '+str(myst_w_call_5 / _e_d)+' $'+str(myst_w_call_5 /_e_d * myst_last_ethereum_price)) #Account 0 Data print('Calling Account_6 '+myst_tokenName+' Balance: ') print(myst_account6_n+': '+myst_tokenName+' Balance: '+str(myst_call_6 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_6 / myst_token_d * myst_last_price)) print('Calling Account_6 Ethereum Balance: ') print(myst_account6_n+': Ethereum Balance '+str(myst_w_call_6 / _e_d)+' $'+str(myst_w_call_6 / _e_d * myst_last_ethereum_price)) def myst_unlock_all_accounts(): myst_unlock_account_0() myst_unlock_account_1() myst_unlock_account_2() myst_unlock_account_3() myst_unlock_account_4() myst_unlock_account_5() myst_unlock_account_6() def myst_unlock_account_0(): global myst_account0pw global myst_account0 global myst_account0_n myst_update_accounts() myst_u_a_0 = myst_w_unlock(myst_account0, myst_account0pw, myst_unlockTime) if myst_u_a_0 == False: if myst_account0pw == '': myst_account0pw_r = 'UnAssigned (Blank String (\'\')' print('Unlock Failure With Account '+myst_account0_n+' Passphrase Denied: '+myst_account0pw_r) elif myst_account0pw == 'UnAssigned (Blank String (\'\')': print('Unlock Failure With Account '+myst_account0_n+' Passphrase Denied: '+myst_account0pw) if myst_u_a_0 == True: print(myst_account0_n+' Unlocked') def myst_unlock_account_1(): global myst_account1pw global myst_account1 global myst_account1_n myst_update_accounts() myst_u_a_1 = myst_unlock(myst_account1, myst_account1pw, myst_unlockTime) if myst_u_a_1 == False: if myst_account1pw == '': myst_account1pw_r = 'UnAssigned (Blank String (\'\')' print('Unlock Failure With Account '+myst_account1_n+' Passphrase Denied: '+myst_account1pw_r) elif myst_account1pw == 'UnAssigned (Blank String (\'\')': print('Unlock Failure With Account '+myst_account1_n+' Passphrase Denied: '+myst_account1pw) if myst_u_a_1 == True: print(myst_account1_n+' Unlocked') def myst_unlock_account_2(): global myst_account2pw global myst_account2 global myst_account2_n myst_update_accounts() myst_u_a_2 = myst_unlock(myst_account2, myst_account2pw, myst_unlockTime) if myst_u_a_2 == False: if myst_account2pw == '': myst_account2pw_r = 'UnAssigned (Blank String (\'\')' print('Unlock Failure With Account '+myst_account2_n+' Passphrase Denied: '+myst_account2pw_r) elif myst_account2pw != '': print('Unlock Failure With Account '+myst_account2_n+' Passphrase Denied: '+myst_account2pw) if myst_u_a_2 == True: print(myst_account2_n+' Unlocked') def myst_unlock_account_3(): global myst_account3pw global myst_account3 global myst_account3_n myst_update_accounts() myst_u_a_3 = myst_unlock(myst_account3, myst_account3pw, myst_unlockTime) if myst_u_a_3 == False: if myst_account3pw == '': myst_account3pw_r = 'UnAssigned (Blank String (\'\')' print('Unlock Failure With Account '+myst_account3_n+' Passphrase Denied: '+myst_account3pw_r) elif myst_account3pw != '': print('Unlock Failure With Account '+myst_account3_n+' Passphrase Denied: '+myst_account3pw) if myst_u_a_3 == True: print(myst_account3_n+' Unlocked') def myst_unlock_account_4(): global myst_account4pw global myst_account4 global myst_account4_n myst_update_accounts() myst_u_a_4 = myst_unlock(myst_account4, myst_account4pw, myst_unlockTime) if myst_u_a_4 == False: if myst_account4pw == '': myst_account4pw_r = 'UnAssigned (Blank String (\'\')' print('Unlock Failure With Account '+myst_account4_n+' Passphrase Denied: '+myst_account4pw_r) elif myst_account4pw != '': print('Unlock Failure With Account '+myst_account4_n+' Passphrase Denied: '+myst_account4pw) if myst_u_a_4 == True: print(myst_account4_n+' Unlocked') def myst_unlock_account_5(): global myst_account5pw global myst_account5 global myst_account5_n myst_update_accounts() myst_u_a_5 = myst_unlock(myst_account5, myst_account5pw, myst_unlockTime) if myst_u_a_5 == False: if myst_account5pw == '': myst_account5pw_r = 'UnAssigned (Blank String (\'\')' print('Unlock Failure With Account '+myst_account5_n+' Passphrase Denied: '+myst_account5pw_r) elif myst_account5pw != '': print('Unlock Failure With Account '+myst_account5_n+' Passphrase Denied: '+myst_account5pw) if myst_u_a_5 == True: print(myst_account5_n+' Unlocked') def myst_unlock_account_6(): global myst_account6pw global myst_account6 global myst_account6_n myst_update_accounts() myst_u_a_6 = myst_unlock(myst_account6, myst_account6pw, myst_unlockTime) if myst_u_a_6 == False: if myst_account6pw == '': myst_account6pw_r = 'UnAssigned (Blank String (\'\')' print('Unlock Failure With Account '+myst_account6_n+' Passphrase Denied: '+myst_account6pw_r) elif myst_account6pw != '': print('Unlock Failure With Account '+myst_account6_n+' Passphrase Denied: '+myst_account6pw) if myst_u_a_6 == True: print(myst_account6_n+' Unlocked') def myst_unlock_account(myst_ua_accountNumber): myst_update_accounts() myst_ua_account_number = myst_ua_accountNumber myst_ua_input = [0, 1, 2, 3, 4, 5, 6] if myst_ua_account_number == myst_ua_input[0]: myst_unlock_account_0() if myst_ua_account_number == myst_ua_input[1]: myst_unlock_account_1() if myst_ua_account_number == myst_ua_input[2]: myst_unlock_account_2() if myst_ua_account_number == myst_ua_input[3]: myst_unlock_account_3() if myst_ua_account_number == myst_ua_input[4]: myst_unlock_account_4() if myst_ua_account_number == myst_ua_input[5]: myst_unlock_account_5() if myst_ua_account_number == myst_ua_input[6]: myst_unlock_account_6() if myst_ua_account_number not in myst_ua_input: print('Must Integer Within Range '+myst_accounts_range+'.') def myst_approve_between_accounts(fromAccount, toAccount, msgValue): myst_update_accounts() myst_a_0 = myst.transact({'from': web3.personal.listAccounts[fromAccount]}).approve(web3.personal.listAccounts[toAccount], msgValue) print(myst_a_0) def myst_approve(fromAccountNumber, toAddress, msgValue): myst_update_accounts() myst_unlock_account(fromAccountNumber) myst_a_1 = myst.transact({'from': web3.personal.listAccounts[fromAccount]}).approve(toAddress, msgValue) print(myst_a_1) def myst_transfer_between_accounts(fromAccount, toAccount, msgValue): myst_update_accounts() myst_unlock_account(fromAccount) myst_t_0 = myst.transact({'from': web3.personal.listAccounts[fromAccount]}).transfer(web3.personal.listAccounts[toAccount], msgValue) print(myst_t_0) def myst_transfer(fromAccountNumber, toAddress, msgValue): myst_update_accounts() myst_unlock_account(fromAccountNumber) myst_t_1 = myst.transact({'from': web3.personal.listAccounts[fromAccount]}).transfer(toAddress, msgValue) print(myst_t_1) def myst_transferFrom_between_accounts(callAccount, fromAccount, toAccount, msgValue): myst_update_accounts() myst_unlock_account(callAccount) myst_tf_0 = myst.transact({'from': web3.personal.listAccounts[callAccount]}).transferFrom(web3.personal.listAccounts[fromAccount], web3.personal.listAccounts[toAccount], msgValue) print(myst_tf_0) def myst_transferFrom(callAccount, fromAccount, toAccount, msgValue): myst_update_accounts() myst_unlock_account(callAccount) myst_tf_1 = myst.transact({'from': web3.personal.listAccounts[callAccount]}).transferFrom(web3.personal.listAccounts[fromAccount], toAddress, msgValue) print(myst_tf_1) def myst_help(): print('Following Functions For '+myst_tokenName+' Are As Follows:') print(''' @ Tag Listing Below: ~ (Function Name) -- (Next line same subject) / * (variable assigned main function) ** (variable assigned contract call/transaction) // (if condition is met) => (function calls in order) / * myst_unlock => web3.personal.unlockAccount / * myst_accounts => web3.personal.listAccounts / * myst_balance = web3.eth.getBalance ** myst => web3.eth.contract(abi=myst_abi, address=myst_address) ** / * myst_balanceOf => myst.call().balanceOf ~ Function Listing Below: ~ myst_update_accounts() ~ myst_update_balances() \n\r -- => myst_update_accounts() ~ myst_list_all_accounts() \n\r -- => myst_update_accounts() ~ myst_account_balance(accountNumber) \n\r -- => myst_update_balances() ~ myst_list_all_account_balances() \n\r -- => myst_update_balances() ~ myst_unlock_all_accounts() \n\r -- => myst_unlock_account_0() \n\r -- => myst_unlock_account_1() \n\r -- => myst_unlock_account_2() \n\r -- => myst_unlock_account_3() \n\r -- => myst_unlock_account_4() \n\r -- => myst_unlock_account_5() \n\r -- => myst_unlock_account_6() ~ myst_unlock_account_0() \n\r -- => myst_update_accounts() \n\r -- / *myst_w_unlock(myst_account0, myst_account0pw, myst_unlockTime) ~ myst_unlock_account_1() \n\r -- => myst_update_accounts() \n\r -- / *myst_w_unlock(myst_account1, myst_account0pw, myst_unlockTime) ~ myst_unlock_account_2() \n\r -- => myst_update_accounts() \n\r --/ *myst_w_unlock(myst_account2, myst_account0pw, myst_unlockTime) ~ myst_unlock_account_3() \n\r -- => myst_update_accounts() \n\r -- / *myst_w_unlock(myst_account3, myst_account0pw, myst_unlockTime) ~ myst_unlock_account_4() \n\r -- => myst_update_accounts() \n\r -- / *myst_w_unlock(myst_account4, myst_account0pw, myst_unlockTime) ~ myst_unlock_account_5() \n\r -- => myst_update_accounts() \n\r -- / *myst_w_unlock(myst_account5, myst_account0pw, myst_unlockTime) ~ myst_unlock_account_6() \n\r -- => myst_update_accounts() \n\r -- / *myst_w_unlock(myst_account6, myst_account0pw, myst_unlockTime) ~ myst_unlock_account(myst_ua_accountNumber) \n\r -- => myst_update_accounts() \n\r -- // myst_unlock_account_0() \n\r -- // myst_unlock_account_1() \n\r -- // myst_unlock_account_2() \n\r -- // myst_unlock_account_3() \n\r -- // myst_unlock_account_4() \n\r -- // myst_unlock_account_5() \n\r -- // myst_unlock_account_6() ~ myst_approve_between_accounts(fromAccount, toAccount, msgValue) \n\r -- => myst_update_accounts() \n\r -- => myst_unlock_account(fromAccount) \n\r -- / ** myst.transact({'from': web3.personal.listAccounts[fromAccount]}).approve(toAddress, msgValue) ~ myst_approve(fromAccountNumber, toAddress, msgValue) \n\r -- => myst_update_accounts() \n\r -- => myst_unlock_account(fromAccountNumber) \n\r -- / ** myst.transact({'from': web3.personal.listAccounts[fromAccount]}).approve(toAddress, msgValue) ~ myst_transfer_between_accounts(fromAccount, toAccount, msgValue) \n\r -- => myst_update_accounts() \n\r -- => myst_unlock_account(fromAccount) \n\r -- / ** myst.transact({'from': web3.personal.listAccounts[fromAccount]}).transfer(web3.personal.listAccounts[toAccount], msgValue) ~ myst_transfer(fromAccountNumber, toAddress, msgValue) \n\r -- => myst_update_accounts() \n\r -- => myst_unlock_account(fromAccountNumber) \n\r -- / ** myst.transact({'from': web3.personal.listAccounts[callAccount]}).transferFrom(web3.personal.listAccounts[fromAccount], \n\r -- web3.personal.listAccounts[toAccount], msgValue) ~ myst_transferFrom_between_accounts(callAccount, fromAccount, toAccount, msgValue) \n\r -- => myst_update_accounts() \n\r -- => myst_unlock_account(callAccount) \n\r / ** myst.transact({'from': web3.personal.listAccounts[callAccount]}).transferFrom(web3.personal.listAccounts[fromAccount], \n\r -- web3.personal.listAccounts[toAccount], msgValue) ~ myst_transferFrom(callAccount, fromAccount, toAccount, msgValue) \n\r -- => myst_update_accounts() \n\r -- => myst_unlock_account(callAccount) \n\r -- / ** myst.transact({'from': web3.personal.listAccounts[callAccount]}).transferFrom(web3.personal.listAccounts[fromAccount], toAddress, msgValue) ~ myst_help() <-- You Are Here. ''')
#!/usr/bin/python3 import time from web3 import Web3, KeepAliveRPCProvider, IPCProvider web3 = Web3(KeepAliveRPCProvider(host='127.0.0.1', port='8545')) # Global Declarations global true global false global myst_account_0_a global myst_account_1_a global myst_account_2_a global myst_account_3_a global myst_account_4_a global myst_account_5_a global myst_account_6_a global myst_address global myst_abi global myst global myst_call_0 global myst_call_1 global myst_call_2 global myst_call_3 global myst_call_4 global myst_call_5 global myst_call_6 global myst_call_ab global myst_accounts global myst_account_0_pw global myst_account_1_pw global myst_account_2_pw global myst_account_3_pw global myst_account_4_pw global myst_account_5_pw global myst_account_6_pw global myst_account_0_n global myst_account_1_n global myst_account_2_n global myst_account_3_n global myst_account_4_n global myst_account_5_n global myst_account_6_n global myst_account1pw global myst_account2pw global myst_account3pw global myst_account4pw global myst_account5pw global myst_account6pw global myst_last_price global myst_accounts_range global myst_tokenName global myst_last_ethereum_price global myst_unlockTime global myst_balance global myst_balanceOf global myst_unlock global myst_token_d global _e_d # Internal Variable Setup (Leave Alone Unless You Understand What They Do.) true = True false = False myst_token_d = 1e8 _e_d = 1e18 myst_accounts_range = '[0, 6]' myst_unlock = web3.personal.unlockAccount myst_last_ethereum_price = 370.00 myst_last_price = 1.53 myst_accounts = web3.personal.listAccounts # For personal accounts, Accounts Can Also Be String ('0x..') Listed. myst_balance = web3.eth.getBalance # User Choice Variables (You May Change These Pretty Easily Without Fucking Anything Up.) myst_tokenName = 'Mysterium Token' myst_unlockTime = hex(10000) # Must be hex() myst_account_0_a = myst_accounts[0] myst_account_1_a = myst_accounts[1] myst_account_2_a = myst_accounts[2] myst_account_3_a = myst_accounts[3] myst_account_4_a = myst_accounts[4] myst_account_5_a = '0xFBb1b73C4f0BDa4f67dcA266ce6Ef42f520fBB98' myst_account_6_a = myst_accounts[6] # Supply Unlock Passwords For Transactions Below myst_account_0_pw = 'GuildSkrypt2017!@#' myst_account_1_pw = '' myst_account_2_pw = 'GuildSkrypt2017!@#' myst_account_3_pw = '' myst_account_4_pw = '' myst_account_5_pw = '' myst_account_6_pw = '' # Supply Names Below Standard Is 'Unknown' myst_account_0_n = 'Skotys Bittrex Account' myst_account_1_n = 'Jeffs Account' myst_account_2_n = 'Skrypts Bittrex Account' myst_account_3_n = 'Skotys Personal Account' myst_account_4_n = 'Unknown' myst_account_5_n = 'Watched \'Bittrex\' Account.' myst_account_6_n = 'Watched Account (1)' # Contract Information Below : myst_address = '0xa645264C5603E96c3b0B078cdab68733794B0A71' myst_abi = [{"constant":false,"inputs":[{"name":"addr","type":"address"},{"name":"state","type":"bool"}],"name":"setTransferAgent","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"mintingFinished","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"addr","type":"address"}],"name":"setReleaseAgent","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"receiver","type":"address"},{"name":"amount","type":"uint256"}],"name":"mint","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"mintAgents","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"addr","type":"address"},{"name":"state","type":"bool"}],"name":"setMintAgent","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"value","type":"uint256"}],"name":"upgrade","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_name","type":"string"},{"name":"_symbol","type":"string"}],"name":"setTokenInformation","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"upgradeAgent","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"releaseTokenTransfer","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"upgradeMaster","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"getUpgradeState","outputs":[{"name":"","type":"uint8"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"transferAgents","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"released","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"canUpgrade","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_addedValue","type":"uint256"}],"name":"addApproval","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalUpgraded","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"releaseAgent","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"agent","type":"address"}],"name":"setUpgradeAgent","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_subtractedValue","type":"uint256"}],"name":"subApproval","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"master","type":"address"}],"name":"setUpgradeMaster","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_name","type":"string"},{"name":"_symbol","type":"string"},{"name":"_initialSupply","type":"uint256"},{"name":"_decimals","type":"uint256"}],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newName","type":"string"},{"indexed":false,"name":"newSymbol","type":"string"}],"name":"UpdatedTokenInformation","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Upgrade","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"agent","type":"address"}],"name":"UpgradeAgentSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"receiver","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"Minted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"}] myst = web3.eth.contract(abi=myst_abi, address=myst_address) myst_balanceOf = myst.call().balanceOf # End Contract Information def myst_update_accounts(): global myst_account0 global myst_account1 global myst_account2 global myst_account3 global myst_account4 global myst_account5 global myst_account6 global myst_account0_n global myst_account1_n global myst_account2_n global myst_account3_n global myst_account4_n global myst_account5_n global myst_account6_n global myst_account0pw global myst_account1pw global myst_account2pw global myst_account3pw global myst_account4pw global myst_account5pw global myst_account6pw myst_account0 = myst_account_0_a myst_account1 = myst_account_1_a myst_account2 = myst_account_2_a myst_account3 = myst_account_3_a myst_account4 = myst_account_4_a myst_account5 = myst_account_5_a myst_account6 = myst_account_6_a myst_account0_n = myst_account_0_n myst_account1_n = myst_account_1_n myst_account2_n = myst_account_2_n myst_account3_n = myst_account_3_n myst_account4_n = myst_account_4_n myst_account5_n = myst_account_5_n myst_account6_n = myst_account_6_n myst_account0pw = myst_account_0_pw myst_account1pw = myst_account_1_pw myst_account2pw = myst_account_2_pw myst_account3pw = myst_account_3_pw myst_account4pw = myst_account_4_pw myst_account5pw = myst_account_5_pw myst_account6pw = myst_account_6_pw print(myst_tokenName+' Accounts Updated.') def myst_update_balances(): global myst_call_0 global myst_call_1 global myst_call_2 global myst_call_3 global myst_call_4 global myst_call_5 global myst_call_6 global myst_w_call_0 global myst_w_call_1 global myst_w_call_2 global myst_w_call_3 global myst_w_call_4 global myst_w_call_5 global myst_w_call_6 myst_update_accounts() print('Updating '+myst_tokenName+' Balances Please Wait...') myst_call_0 = myst_balanceOf(myst_account0) myst_call_1 = myst_balanceOf(myst_account1) myst_call_2 = myst_balanceOf(myst_account2) myst_call_3 = myst_balanceOf(myst_account3) myst_call_4 = myst_balanceOf(myst_account4) myst_call_5 = myst_balanceOf(myst_account5) myst_call_6 = myst_balanceOf(myst_account6) myst_w_call_0 = myst_balance(myst_account0) myst_w_call_1 = myst_balance(myst_account1) myst_w_call_2 = myst_balance(myst_account2) myst_w_call_3 = myst_balance(myst_account3) myst_w_call_4 = myst_balance(myst_account4) myst_w_call_5 = myst_balance(myst_account5) myst_w_call_6 = myst_balance(myst_account6) print(myst_tokenName+' Balances Updated.') def myst_list_all_accounts(): myst_update_accounts() print(myst_tokenName+' '+myst_account0_n+': '+myst_account0) print(myst_tokenName+' '+myst_account1_n+': '+myst_account1) print(myst_tokenName+' '+myst_account2_n+': '+myst_account2) print(myst_tokenName+' '+myst_account3_n+': '+myst_account3) print(myst_tokenName+' '+myst_account4_n+': '+myst_account4) print(myst_tokenName+' '+myst_account5_n+': '+myst_account5) print(myst_tokenName+' '+myst_account6_n+': '+myst_account6) def myst_account_balance(accountNumber): myst_update_balances() myst_ab_account_number = accountNumber myst_ab_input = [0, 1, 2, 3, 4, 5, 6] if myst_ab_account_number == myst_ab_input[0]: print('Calling '+myst_account0_n+' '+myst_tokenName+' Balance: ') print(myst_account0_n+': '+myst_tokenName+' Balance: '+str(myst_call_0 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_0 / myst_token_d * myst_last_price)) if myst_ab_account_number == myst_ab_input[1]: print('Calling '+myst_account1_n+' '+myst_tokenName+' Balance: ') print(myst_account1_n+': '+myst_tokenName+' Balance: '+str(myst_call_1 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_1 / myst_token_d * myst_last_price)) if myst_ab_account_number == myst_ab_input[2]: print('Calling '+myst_account2_n+' '+myst_tokenName+' Balance: ') print(myst_account2_n+': '+myst_tokenName+' Balance: '+str(myst_call_2 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_2 / myst_token_d * myst_last_price)) if myst_ab_account_number == myst_ab_input[3]: print('Calling '+myst_account3_n+' '+myst_tokenName+' Balance: ') print(myst_account3_n+': '+myst_tokenName+' Balance: '+str(myst_call_3 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_3 / myst_token_d * myst_last_price)) if myst_ab_account_number == myst_ab_input[4]: print('Calling '+myst_account4_n+' '+myst_tokenName+' Balance: ') print(myst_account4_n+': '+myst_tokenName+' Balance: '+str(myst_call_4 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_4 / myst_token_d * myst_last_price)) if myst_ab_account_number == myst_ab_input[5]: print('Calling '+myst_account5_n+' '+myst_tokenName+' Balance: ') print(myst_account5_n+': '+myst_tokenName+' Balance: '+str(myst_call_5 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_5 / myst_token_d * myst_last_price)) if myst_ab_account_number == myst_ab_input[6]: print('Calling '+myst_account6_n+' '+myst_tokenName+' Balance: ') print(myst_account6_n+': '+myst_tokenName+' Balance: '+str(myst_call_6 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_6 / myst_token_d * myst_last_price)) if myst_ab_account_number not in myst_ab_input: print('Must Integer Within Range '+myst_accounts_range+'.') def myst_list_all_account_balances(): myst_update_balances() print('Loading Account Data...') #Account 0 Data print('Calling Account_0 '+myst_tokenName+' Balance: ') print(myst_account0_n+': '+myst_tokenName+' Balance: '+str(myst_call_0 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_0 / myst_token_d * myst_last_price)) print('Calling Account_0 Ethereum Balance: ') print(myst_account0_n+': Ethereum Balance '+str(myst_w_call_0 / _e_d)+' $'+str(myst_w_call_0 / _e_d * myst_last_ethereum_price)) #Account 1 Data print('Calling Account_1 '+myst_tokenName+' Balance: ') print(myst_account1_n+': '+myst_tokenName+' Balance: '+str(myst_call_1 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_1 / myst_token_d * myst_last_price)) print('Calling Account_1 Ethereum Balance: ') print(myst_account1_n+': Ethereum Balance '+str(myst_w_call_1 / _e_d)+' $'+str(myst_w_call_1 / _e_d * myst_last_ethereum_price)) #Account 2 Data print('Calling Account_2 '+myst_tokenName+' Balance: ') print(myst_account2_n+': '+myst_tokenName+' Balance: '+str(myst_call_2 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_2 / myst_token_d * myst_last_price)) print('Calling Account_2 Ethereum Balance: ') print(myst_account2_n+': Ethereum Balance '+str(myst_w_call_2 / _e_d)+' $'+str(myst_w_call_2 / _e_d * myst_last_ethereum_price)) #Account 3 Data print('Calling Account_3 '+myst_tokenName+' Balance: ') print(myst_account3_n+': '+myst_tokenName+' Balance: '+str(myst_call_3 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_3 / myst_token_d * myst_last_price)) print('Calling Account_3 Ethereum Balance: ') print(myst_account3_n+': Ethereum Balance '+str(myst_w_call_3 / _e_d)+' $'+str(myst_w_call_3 / _e_d * myst_last_ethereum_price)) #Account 4 Data print('Calling Account_4 '+myst_tokenName+' Balance: ') print(myst_account4_n+': '+myst_tokenName+' Balance: '+str(myst_call_4 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_4 / myst_token_d * myst_last_price)) print('Calling Account_4 Ethereum Balance: ') print(myst_account4_n+': Ethereum Balance '+str(myst_w_call_4 / _e_d)+' $'+str(myst_w_call_4 / _e_d * myst_last_ethereum_price)) #Account 5 Data print('Calling Account_5 '+myst_tokenName+' Balance: ') print(myst_account5_n+': '+myst_tokenName+' Balance: '+str(myst_call_5 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_5 / myst_token_d * myst_last_price)) print('Calling Account_5 Ethereum Balance: ') print(myst_account5_n+': Ethereum Balance '+str(myst_w_call_5 / _e_d)+' $'+str(myst_w_call_5 /_e_d * myst_last_ethereum_price)) #Account 0 Data print('Calling Account_6 '+myst_tokenName+' Balance: ') print(myst_account6_n+': '+myst_tokenName+' Balance: '+str(myst_call_6 / myst_token_d)+' Usd/'+myst_tokenName+' Balance: $'+str(myst_call_6 / myst_token_d * myst_last_price)) print('Calling Account_6 Ethereum Balance: ') print(myst_account6_n+': Ethereum Balance '+str(myst_w_call_6 / _e_d)+' $'+str(myst_w_call_6 / _e_d * myst_last_ethereum_price)) def myst_unlock_all_accounts(): myst_unlock_account_0() myst_unlock_account_1() myst_unlock_account_2() myst_unlock_account_3() myst_unlock_account_4() myst_unlock_account_5() myst_unlock_account_6() def myst_unlock_account_0(): global myst_account0pw global myst_account0 global myst_account0_n myst_update_accounts() myst_u_a_0 = myst_w_unlock(myst_account0, myst_account0pw, myst_unlockTime) if myst_u_a_0 == False: if myst_account0pw == '': myst_account0pw_r = 'UnAssigned (Blank String (\'\')' print('Unlock Failure With Account '+myst_account0_n+' Passphrase Denied: '+myst_account0pw_r) elif myst_account0pw == 'UnAssigned (Blank String (\'\')': print('Unlock Failure With Account '+myst_account0_n+' Passphrase Denied: '+myst_account0pw) if myst_u_a_0 == True: print(myst_account0_n+' Unlocked') def myst_unlock_account_1(): global myst_account1pw global myst_account1 global myst_account1_n myst_update_accounts() myst_u_a_1 = myst_unlock(myst_account1, myst_account1pw, myst_unlockTime) if myst_u_a_1 == False: if myst_account1pw == '': myst_account1pw_r = 'UnAssigned (Blank String (\'\')' print('Unlock Failure With Account '+myst_account1_n+' Passphrase Denied: '+myst_account1pw_r) elif myst_account1pw == 'UnAssigned (Blank String (\'\')': print('Unlock Failure With Account '+myst_account1_n+' Passphrase Denied: '+myst_account1pw) if myst_u_a_1 == True: print(myst_account1_n+' Unlocked') def myst_unlock_account_2(): global myst_account2pw global myst_account2 global myst_account2_n myst_update_accounts() myst_u_a_2 = myst_unlock(myst_account2, myst_account2pw, myst_unlockTime) if myst_u_a_2 == False: if myst_account2pw == '': myst_account2pw_r = 'UnAssigned (Blank String (\'\')' print('Unlock Failure With Account '+myst_account2_n+' Passphrase Denied: '+myst_account2pw_r) elif myst_account2pw != '': print('Unlock Failure With Account '+myst_account2_n+' Passphrase Denied: '+myst_account2pw) if myst_u_a_2 == True: print(myst_account2_n+' Unlocked') def myst_unlock_account_3(): global myst_account3pw global myst_account3 global myst_account3_n myst_update_accounts() myst_u_a_3 = myst_unlock(myst_account3, myst_account3pw, myst_unlockTime) if myst_u_a_3 == False: if myst_account3pw == '': myst_account3pw_r = 'UnAssigned (Blank String (\'\')' print('Unlock Failure With Account '+myst_account3_n+' Passphrase Denied: '+myst_account3pw_r) elif myst_account3pw != '': print('Unlock Failure With Account '+myst_account3_n+' Passphrase Denied: '+myst_account3pw) if myst_u_a_3 == True: print(myst_account3_n+' Unlocked') def myst_unlock_account_4(): global myst_account4pw global myst_account4 global myst_account4_n myst_update_accounts() myst_u_a_4 = myst_unlock(myst_account4, myst_account4pw, myst_unlockTime) if myst_u_a_4 == False: if myst_account4pw == '': myst_account4pw_r = 'UnAssigned (Blank String (\'\')' print('Unlock Failure With Account '+myst_account4_n+' Passphrase Denied: '+myst_account4pw_r) elif myst_account4pw != '': print('Unlock Failure With Account '+myst_account4_n+' Passphrase Denied: '+myst_account4pw) if myst_u_a_4 == True: print(myst_account4_n+' Unlocked') def myst_unlock_account_5(): global myst_account5pw global myst_account5 global myst_account5_n myst_update_accounts() myst_u_a_5 = myst_unlock(myst_account5, myst_account5pw, myst_unlockTime) if myst_u_a_5 == False: if myst_account5pw == '': myst_account5pw_r = 'UnAssigned (Blank String (\'\')' print('Unlock Failure With Account '+myst_account5_n+' Passphrase Denied: '+myst_account5pw_r) elif myst_account5pw != '': print('Unlock Failure With Account '+myst_account5_n+' Passphrase Denied: '+myst_account5pw) if myst_u_a_5 == True: print(myst_account5_n+' Unlocked') def myst_unlock_account_6(): global myst_account6pw global myst_account6 global myst_account6_n myst_update_accounts() myst_u_a_6 = myst_unlock(myst_account6, myst_account6pw, myst_unlockTime) if myst_u_a_6 == False: if myst_account6pw == '': myst_account6pw_r = 'UnAssigned (Blank String (\'\')' print('Unlock Failure With Account '+myst_account6_n+' Passphrase Denied: '+myst_account6pw_r) elif myst_account6pw != '': print('Unlock Failure With Account '+myst_account6_n+' Passphrase Denied: '+myst_account6pw) if myst_u_a_6 == True: print(myst_account6_n+' Unlocked') def myst_unlock_account(myst_ua_accountNumber): myst_update_accounts() myst_ua_account_number = myst_ua_accountNumber myst_ua_input = [0, 1, 2, 3, 4, 5, 6] if myst_ua_account_number == myst_ua_input[0]: myst_unlock_account_0() if myst_ua_account_number == myst_ua_input[1]: myst_unlock_account_1() if myst_ua_account_number == myst_ua_input[2]: myst_unlock_account_2() if myst_ua_account_number == myst_ua_input[3]: myst_unlock_account_3() if myst_ua_account_number == myst_ua_input[4]: myst_unlock_account_4() if myst_ua_account_number == myst_ua_input[5]: myst_unlock_account_5() if myst_ua_account_number == myst_ua_input[6]: myst_unlock_account_6() if myst_ua_account_number not in myst_ua_input: print('Must Integer Within Range '+myst_accounts_range+'.') def myst_approve_between_accounts(fromAccount, toAccount, msgValue): myst_update_accounts() myst_a_0 = myst.transact({'from': web3.personal.listAccounts[fromAccount]}).approve(web3.personal.listAccounts[toAccount], msgValue) print(myst_a_0) def myst_approve(fromAccountNumber, toAddress, msgValue): myst_update_accounts() myst_unlock_account(fromAccountNumber) myst_a_1 = myst.transact({'from': web3.personal.listAccounts[fromAccount]}).approve(toAddress, msgValue) print(myst_a_1) def myst_transfer_between_accounts(fromAccount, toAccount, msgValue): myst_update_accounts() myst_unlock_account(fromAccount) myst_t_0 = myst.transact({'from': web3.personal.listAccounts[fromAccount]}).transfer(web3.personal.listAccounts[toAccount], msgValue) print(myst_t_0) def myst_transfer(fromAccountNumber, toAddress, msgValue): myst_update_accounts() myst_unlock_account(fromAccountNumber) myst_t_1 = myst.transact({'from': web3.personal.listAccounts[fromAccount]}).transfer(toAddress, msgValue) print(myst_t_1) def myst_transferFrom_between_accounts(callAccount, fromAccount, toAccount, msgValue): myst_update_accounts() myst_unlock_account(callAccount) myst_tf_0 = myst.transact({'from': web3.personal.listAccounts[callAccount]}).transferFrom(web3.personal.listAccounts[fromAccount], web3.personal.listAccounts[toAccount], msgValue) print(myst_tf_0) def myst_transferFrom(callAccount, fromAccount, toAccount, msgValue): myst_update_accounts() myst_unlock_account(callAccount) myst_tf_1 = myst.transact({'from': web3.personal.listAccounts[callAccount]}).transferFrom(web3.personal.listAccounts[fromAccount], toAddress, msgValue) print(myst_tf_1) def myst_help(): print('Following Functions For '+myst_tokenName+' Are As Follows:') print(''' @ Tag Listing Below: ~ (Function Name) -- (Next line same subject) / * (variable assigned main function) ** (variable assigned contract call/transaction) // (if condition is met) => (function calls in order) / * myst_unlock => web3.personal.unlockAccount / * myst_accounts => web3.personal.listAccounts / * myst_balance = web3.eth.getBalance ** myst => web3.eth.contract(abi=myst_abi, address=myst_address) ** / * myst_balanceOf => myst.call().balanceOf ~ Function Listing Below: ~ myst_update_accounts() ~ myst_update_balances() \n\r -- => myst_update_accounts() ~ myst_list_all_accounts() \n\r -- => myst_update_accounts() ~ myst_account_balance(accountNumber) \n\r -- => myst_update_balances() ~ myst_list_all_account_balances() \n\r -- => myst_update_balances() ~ myst_unlock_all_accounts() \n\r -- => myst_unlock_account_0() \n\r -- => myst_unlock_account_1() \n\r -- => myst_unlock_account_2() \n\r -- => myst_unlock_account_3() \n\r -- => myst_unlock_account_4() \n\r -- => myst_unlock_account_5() \n\r -- => myst_unlock_account_6() ~ myst_unlock_account_0() \n\r -- => myst_update_accounts() \n\r -- / *myst_w_unlock(myst_account0, myst_account0pw, myst_unlockTime) ~ myst_unlock_account_1() \n\r -- => myst_update_accounts() \n\r -- / *myst_w_unlock(myst_account1, myst_account0pw, myst_unlockTime) ~ myst_unlock_account_2() \n\r -- => myst_update_accounts() \n\r --/ *myst_w_unlock(myst_account2, myst_account0pw, myst_unlockTime) ~ myst_unlock_account_3() \n\r -- => myst_update_accounts() \n\r -- / *myst_w_unlock(myst_account3, myst_account0pw, myst_unlockTime) ~ myst_unlock_account_4() \n\r -- => myst_update_accounts() \n\r -- / *myst_w_unlock(myst_account4, myst_account0pw, myst_unlockTime) ~ myst_unlock_account_5() \n\r -- => myst_update_accounts() \n\r -- / *myst_w_unlock(myst_account5, myst_account0pw, myst_unlockTime) ~ myst_unlock_account_6() \n\r -- => myst_update_accounts() \n\r -- / *myst_w_unlock(myst_account6, myst_account0pw, myst_unlockTime) ~ myst_unlock_account(myst_ua_accountNumber) \n\r -- => myst_update_accounts() \n\r -- // myst_unlock_account_0() \n\r -- // myst_unlock_account_1() \n\r -- // myst_unlock_account_2() \n\r -- // myst_unlock_account_3() \n\r -- // myst_unlock_account_4() \n\r -- // myst_unlock_account_5() \n\r -- // myst_unlock_account_6() ~ myst_approve_between_accounts(fromAccount, toAccount, msgValue) \n\r -- => myst_update_accounts() \n\r -- => myst_unlock_account(fromAccount) \n\r -- / ** myst.transact({'from': web3.personal.listAccounts[fromAccount]}).approve(toAddress, msgValue) ~ myst_approve(fromAccountNumber, toAddress, msgValue) \n\r -- => myst_update_accounts() \n\r -- => myst_unlock_account(fromAccountNumber) \n\r -- / ** myst.transact({'from': web3.personal.listAccounts[fromAccount]}).approve(toAddress, msgValue) ~ myst_transfer_between_accounts(fromAccount, toAccount, msgValue) \n\r -- => myst_update_accounts() \n\r -- => myst_unlock_account(fromAccount) \n\r -- / ** myst.transact({'from': web3.personal.listAccounts[fromAccount]}).transfer(web3.personal.listAccounts[toAccount], msgValue) ~ myst_transfer(fromAccountNumber, toAddress, msgValue) \n\r -- => myst_update_accounts() \n\r -- => myst_unlock_account(fromAccountNumber) \n\r -- / ** myst.transact({'from': web3.personal.listAccounts[callAccount]}).transferFrom(web3.personal.listAccounts[fromAccount], \n\r -- web3.personal.listAccounts[toAccount], msgValue) ~ myst_transferFrom_between_accounts(callAccount, fromAccount, toAccount, msgValue) \n\r -- => myst_update_accounts() \n\r -- => myst_unlock_account(callAccount) \n\r / ** myst.transact({'from': web3.personal.listAccounts[callAccount]}).transferFrom(web3.personal.listAccounts[fromAccount], \n\r -- web3.personal.listAccounts[toAccount], msgValue) ~ myst_transferFrom(callAccount, fromAccount, toAccount, msgValue) \n\r -- => myst_update_accounts() \n\r -- => myst_unlock_account(callAccount) \n\r -- / ** myst.transact({'from': web3.personal.listAccounts[callAccount]}).transferFrom(web3.personal.listAccounts[fromAccount], toAddress, msgValue) ~ myst_help() <-- You Are Here. ''')
import copy import json import math import os import random import re import socket import string import time import traceback import sys from functools import cmp_to_key from http.client import IncompleteRead from multiprocessing import Process, Manager, Semaphore from threading import Thread import crc32 import logger import testconstants from cb_tools.cbstats import Cbstats from remote.remote_util import RemoteMachineShellConnection from collection.collections_rest_client import CollectionsRest from collection.collections_stats import CollectionsStats from couchbase_helper.document import DesignDocument from couchbase_helper.documentgenerator import BatchedDocumentGenerator from couchbase_helper.stats_tools import StatsCommon from deepdiff import DeepDiff from mc_bin_client import MemcachedError from membase.api.exception import BucketCreationException from membase.api.exception import N1QLQueryException, DropIndexException, CreateIndexException, \ DesignDocCreationException, QueryViewException, ReadDocumentException, RebalanceFailedException, \ GetBucketInfoFailed, CompactViewFailed, SetViewInfoNotFound, FailoverFailedException, \ ServerUnavailableException, BucketFlushFailed, CBRecoveryFailedException, BucketCompactionException, \ AutoFailoverException,NodesFailureException, ServerAlreadyJoinedException from membase.api.rest_client import RestConnection, Bucket, RestHelper from membase.helper.bucket_helper import BucketOperationHelper from memcacheConstants import ERR_NOT_FOUND, NotFoundError from memcached.helper.data_helper import MemcachedClientHelper from memcached.helper.kvstore import KVStore from remote.remote_util import RemoteMachineShellConnection, RemoteUtilHelper from tasks.future import Future from testconstants import MIN_KV_QUOTA, INDEX_QUOTA, FTS_QUOTA, COUCHBASE_FROM_4DOT6, \ THROUGHPUT_CONCURRENCY, ALLOW_HTP, CBAS_QUOTA, CLUSTER_QUOTA_RATIO from TestInput import TestInputServer, TestInputSingleton try: CHECK_FLAG = False if (TestInputSingleton.input.param("testrunner_client", None) == testconstants.PYTHON_SDK) or \ ((testconstants.TESTRUNNER_CLIENT in list(os.environ.keys())) and os.environ[testconstants.TESTRUNNER_CLIENT] == testconstants.PYTHON_SDK): try: from sdk_client import SDKSmartClient as VBucketAwareMemcached from sdk_client import SDKBasedKVStoreAwareSmartClient as KVStoreAwareSmartClient except: from sdk_client3 import SDKSmartClient as VBucketAwareMemcached from sdk_client3 import SDKBasedKVStoreAwareSmartClient as KVStoreAwareSmartClient if (TestInputSingleton.input.param("enable_sdk_logging", False)): import logging import couchbase logging.basicConfig(stream=sys.stderr, level=logging.INFO) couchbase.enable_logging() else: CHECK_FLAG = True from memcached.helper.data_helper import VBucketAwareMemcached, KVStoreAwareSmartClient except Exception as e: CHECK_FLAG = False try: from sdk_client import SDKSmartClient as VBucketAwareMemcached from sdk_client import SDKBasedKVStoreAwareSmartClient as KVStoreAwareSmartClient except: from sdk_client3 import SDKSmartClient as VBucketAwareMemcached from sdk_client3 import SDKBasedKVStoreAwareSmartClient as KVStoreAwareSmartClient # TODO: Setup stacktracer # TODO: Needs "easy_install pygments" # import stacktracer # stacktracer.trace_start("trace.html",interval=30,auto=True) # Set auto flag to always update file! CONCURRENCY_LOCK = Semaphore(THROUGHPUT_CONCURRENCY) PENDING = 'PENDING' EXECUTING = 'EXECUTING' CHECKING = 'CHECKING' FINISHED = 'FINISHED' class Task(Future): def __init__(self, name): Future.__init__(self) self.log = logger.Logger.get_logger() self.state = PENDING self.name = name self.cancelled = False self.retries = 0 self.res = None def step(self, task_manager): if not self.done(): if self.state == PENDING: self.state = EXECUTING task_manager.schedule(self) elif self.state == EXECUTING: self.execute(task_manager) elif self.state == CHECKING: self.check(task_manager) elif self.state != FINISHED: raise Exception("Bad State in {0}: {1}".format(self.name, self.state)) def execute(self, task_manager): raise NotImplementedError def check(self, task_manager): raise NotImplementedError def set_unexpected_exception(self, e, suffix=""): self.log.error("Unexpected exception [{0}] caught".format(e) + suffix) self.log.error(''.join(traceback.format_stack())) self.set_exception(e) class NodeInitializeTask(Task): def __init__(self, server, disabled_consistent_view=None, rebalanceIndexWaitingDisabled=None, rebalanceIndexPausingDisabled=None, maxParallelIndexers=None, maxParallelReplicaIndexers=None, port=None, quota_percent=None, index_quota_percent=None, services=None, gsi_type='forestdb'): Task.__init__(self, "node_init_task") self.server = server self.port = port or server.port self.quota = 0 self.index_quota = 0 self.index_quota_percent = index_quota_percent self.quota_percent = quota_percent self.disable_consistent_view = disabled_consistent_view self.rebalanceIndexWaitingDisabled = rebalanceIndexWaitingDisabled self.rebalanceIndexPausingDisabled = rebalanceIndexPausingDisabled self.maxParallelIndexers = maxParallelIndexers self.maxParallelReplicaIndexers = maxParallelReplicaIndexers self.services = services self.gsi_type = gsi_type def execute(self, task_manager): try: rest = RestConnection(self.server) except Exception as error: self.state = FINISHED print("debuging hanging issue task 127" + str(error)) self.set_exception(error) return self.log.info("server: %s, nodes/self ", self.server) info = Future.wait_until(lambda: rest.get_nodes_self(), lambda x: x.memoryTotal > 0 or x.storageTotalRam > 0, timeout_secs=60, interval_time=0.1, exponential_backoff=False) self.log.info(" %s", info.__dict__) username = self.server.rest_username password = self.server.rest_password if int(info.port) in range(9091, 9991): self.state = FINISHED self.set_result(True) return self.quota = int(info.mcdMemoryReserved * CLUSTER_QUOTA_RATIO) if self.index_quota_percent: self.index_quota = int((info.mcdMemoryReserved * CLUSTER_QUOTA_RATIO) * \ self.index_quota_percent // 100) rest.set_service_memoryQuota(service='indexMemoryQuota', username=username, \ password=password, memoryQuota=self.index_quota) if self.quota_percent: self.quota = int(info.mcdMemoryReserved * self.quota_percent / 100) """ Adjust KV RAM to correct value when there is INDEX and FTS services added to node from Watson """ index_quota = INDEX_QUOTA cluster_setting = rest.cluster_status() fts_quota = FTS_QUOTA if cluster_setting: if cluster_setting["ftsMemoryQuota"] and \ int(cluster_setting["ftsMemoryQuota"]) >= 256: fts_quota = int(cluster_setting["ftsMemoryQuota"]) kv_quota = int(info.mcdMemoryReserved * CLUSTER_QUOTA_RATIO) if self.index_quota_percent: index_quota = self.index_quota if not self.quota_percent: set_services = copy.deepcopy(self.services) if set_services is None: set_services = ["kv"] # info = rest.get_nodes_self() # cb_version = info.version[:5] # if cb_version in COUCHBASE_FROM_VERSION_4: if "index" in set_services: self.log.info("quota for index service will be %s MB" % (index_quota)) kv_quota -= index_quota self.log.info("set index quota to node %s " % self.server.ip) rest.set_service_memoryQuota(service='indexMemoryQuota', memoryQuota=index_quota) if "fts" in set_services: self.log.info("quota for fts service will be %s MB" % (fts_quota)) kv_quota -= fts_quota self.log.info("set both index and fts quota at node %s " % self.server.ip) rest.set_service_memoryQuota(service='ftsMemoryQuota', memoryQuota=fts_quota) if "cbas" in set_services: self.log.info("quota for cbas service will be %s MB" % (CBAS_QUOTA)) kv_quota -= CBAS_QUOTA rest.set_service_memoryQuota(service="cbasMemoryQuota", memoryQuota=CBAS_QUOTA) if kv_quota < MIN_KV_QUOTA: raise Exception("KV RAM needs to be more than %s MB" " at node %s" % (MIN_KV_QUOTA, self.server.ip)) if kv_quota < int(self.quota): self.quota = kv_quota rest.init_cluster_memoryQuota(username, password, self.quota) if self.services: status = rest.init_node_services(username=username, password=password, \ port=self.port, hostname=self.server.ip, \ services=self.services) if not status: self.state = FINISHED self.set_exception(Exception('unable to set services for server %s' \ % (self.server.ip))) return if self.disable_consistent_view is not None: rest.set_reb_cons_view(self.disable_consistent_view) if self.rebalanceIndexWaitingDisabled is not None: rest.set_reb_index_waiting(self.rebalanceIndexWaitingDisabled) if self.rebalanceIndexPausingDisabled is not None: rest.set_rebalance_index_pausing(self.rebalanceIndexPausingDisabled) if self.maxParallelIndexers is not None: rest.set_max_parallel_indexers(self.maxParallelIndexers) if self.maxParallelReplicaIndexers is not None: rest.set_max_parallel_replica_indexers(self.maxParallelReplicaIndexers) if self.server.internal_ip: rest.set_alternate_address(self.server.ip) rest.init_cluster(username, password, self.port) remote_shell = RemoteMachineShellConnection(self.server) remote_shell.enable_diag_eval_on_non_local_hosts() remote_shell.disconnect() if rest.is_cluster_compat_mode_greater_than(4.0): if self.gsi_type == "plasma": if (not rest.is_cluster_compat_mode_greater_than(5.0)) or (not rest.is_enterprise_edition()): rest.set_indexer_storage_mode(username, password, "forestdb") else: rest.set_indexer_storage_mode(username, password, self.gsi_type) else: rest.set_indexer_storage_mode(username, password, self.gsi_type) self.server.port = self.port try: rest = RestConnection(self.server) except Exception as error: self.state = FINISHED print("debuging hanging issue task 230" + str(error)) self.set_exception(error) return info = rest.get_nodes_self() if info is None: self.state = FINISHED self.set_exception( Exception('unable to get information on a server %s, it is available?' % (self.server.ip))) return self.state = CHECKING task_manager.schedule(self) def check(self, task_manager): self.state = FINISHED self.set_result(self.quota) class BucketCreateTask(Task): def __init__(self, bucket_params): Task.__init__(self, "bucket_create_task") self.server = bucket_params['server'] self.bucket = bucket_params['bucket_name'] self.alt_addr = TestInputSingleton.input.param("alt_addr", False) self.replicas = bucket_params['replicas'] self.port = bucket_params['port'] self.size = bucket_params['size'] self.password = bucket_params['password'] self.bucket_type = bucket_params['bucket_type'] self.enable_replica_index = bucket_params['enable_replica_index'] self.eviction_policy = bucket_params['eviction_policy'] self.lww = bucket_params['lww'] self.storageBackend = bucket_params['bucket_storage'] if 'maxTTL' in bucket_params: self.maxttl = bucket_params['maxTTL'] else: self.maxttl = 0 if 'compressionMode' in bucket_params: self.compressionMode = bucket_params['compressionMode'] else: self.compressionMode = 'passive' self.flush_enabled = bucket_params['flush_enabled'] if bucket_params['bucket_priority'] is None or bucket_params['bucket_priority'].lower() is 'low': self.bucket_priority = 3 else: self.bucket_priority = 8 def execute(self, task_manager): try: rest = RestConnection(self.server) except Exception as error: self.state = FINISHED print("debuging hanging issue task 279" + str(error)) self.set_exception(error) return info = rest.get_nodes_self() if self.size is None or int(self.size) <= 0: self.size = info.memoryQuota * 2 // 3 if int(info.port) in range(9091, 9991): try: self.port = info.port rest.create_bucket(bucket=self.bucket) self.state = CHECKING task_manager.schedule(self) except Exception as e: self.state = FINISHED self.set_exception(e) return version = rest.get_nodes_self().version try: if float(version[:2]) >= 3.0 and self.bucket_priority is not None: rest.create_bucket(bucket=self.bucket, ramQuotaMB=self.size, replicaNumber=self.replicas, proxyPort=self.port, bucketType=self.bucket_type, replica_index=self.enable_replica_index, flushEnabled=self.flush_enabled, evictionPolicy=self.eviction_policy, threadsNumber=self.bucket_priority, lww=self.lww, maxTTL=self.maxttl, compressionMode=self.compressionMode, storageBackend=self.storageBackend) else: rest.create_bucket(bucket=self.bucket, ramQuotaMB=self.size, replicaNumber=self.replicas, proxyPort=self.port, bucketType=self.bucket_type, replica_index=self.enable_replica_index, flushEnabled=self.flush_enabled, evictionPolicy=self.eviction_policy, lww=self.lww, maxTTL=self.maxttl, compressionMode=self.compressionMode) self.state = CHECKING task_manager.schedule(self) except BucketCreationException as e: self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): try: if self.bucket_type == 'memcached' or int(self.port) in range(9091, 9991): self.set_result(True) self.state = FINISHED return if BucketOperationHelper.wait_for_memcached(self.server, self.bucket): self.log.info("bucket '{0}' was created with per node RAM quota: {1}".format(self.bucket, self.size)) self.set_result(True) self.state = FINISHED return else: self.log.warning("vbucket map not ready after try {0}".format(self.retries)) if self.retries >= 5: self.set_result(False) self.state = FINISHED return except Exception as e: self.log.error("Unexpected error: %s" % str(e)) self.log.warning("vbucket map not ready after try {0}".format(self.retries)) if self.retries >= 5: self.state = FINISHED self.set_exception(e) self.retries = self.retries + 1 task_manager.schedule(self) class BucketDeleteTask(Task): def __init__(self, server, bucket="default"): Task.__init__(self, "bucket_delete_task") self.server = server self.bucket = bucket def execute(self, task_manager): try: rest = RestConnection(self.server) if rest.delete_bucket(self.bucket): self.state = CHECKING task_manager.schedule(self) else: self.log.info(StatsCommon.get_stats([self.server], self.bucket, "timings")) self.state = FINISHED self.set_result(False) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.log.info(StatsCommon.get_stats([self.server], self.bucket, "timings")) self.set_unexpected_exception(e) def check(self, task_manager): try: rest = RestConnection(self.server) if BucketOperationHelper.wait_for_bucket_deletion(self.bucket, rest, 200): self.set_result(True) else: self.set_result(False) self.state = FINISHED # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.log.info(StatsCommon.get_stats([self.server], self.bucket, "timings")) self.set_unexpected_exception(e) class CollectionCreateTask(Task): def __init__(self, server, bucket, scope, collection, params=None): Task.__init__(self, "collection_create_task") self.server = server self.bucket_name = bucket self.scope_name = scope self.collection_name = collection self.collection_params = params def execute(self, task_manager): try: rest = RestConnection(self.server) except ServerUnavailableException as error: self.state = FINISHED self.set_exception(error) return try: rest.create_collection(bucket=self.bucket_name, scope=self.scope_name, collection=self.collection_name, params=self.collection_params) self.state = CHECKING task_manager.schedule(self) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) class ConcurrentIndexCreateTask(Task): def __init__(self, server, bucket, scope, collection, query_definitions=None, IndexTrackingObject=None, n1ql_helper=None, num_indexes=1, defer_build="", itr=0, expected_failure=[], query_def_group="plasma_test"): Task.__init__(self, "collection_create_task") self.server = server self.bucket_name = bucket self.scope_name = scope self.collection_name = collection self.query_definitions = query_definitions self.test_fail = False self.index_tracking_obj = IndexTrackingObject self.n1ql_helper=n1ql_helper self.num_indexes = num_indexes self.defer_build = defer_build self.itr = itr self.expected_failure = expected_failure self.query_def_group = query_def_group def execute(self, task_manager): try: RestConnection(self.server) except ServerUnavailableException as error: self.state = FINISHED self.set_exception(error) return try: itr = self.itr while itr < (self.num_indexes + self.itr) and not self.index_tracking_obj.get_stop_create_index(): for query_def in self.query_definitions: if itr >= (self.num_indexes + self.itr): break if self.query_def_group in query_def.groups: query_def_copy = copy.deepcopy(query_def) index_name = query_def_copy.get_index_name() index_name = index_name + str(itr) query_def_copy.update_index_name(index_name) if self.defer_build == "": defer_build = random.choice([True, False]) else: defer_build = self.defer_build index_meta = {"name": query_def_copy.get_index_name(), "query_def": query_def_copy, "defer_build": defer_build} if "primary" in query_def.groups: query = query_def_copy.generate_primary_index_create_query(defer_build=defer_build) else: query = query_def_copy.generate_index_create_query(use_gsi_for_secondary=True, gsi_type="plasma", defer_build=defer_build) try: # create index self.n1ql_helper.run_cbq_query(query=query, server=self.server) self.index_tracking_obj.all_indexes_metadata(index_meta=index_meta, operation="create", defer_build=defer_build) except Exception as err: if not any(error in str(err) for error in self.expected_failure) \ and "Build Already In Progress" not in str(err) \ and "Timeout 1ms exceeded" not in str(err): error_map = {"query": query, "error": str(err)} self.index_tracking_obj.update_errors(error_map) elif not any(error in str(err) for error in self.expected_failure): self.index_tracking_obj.all_indexes_metadata(index_meta=index_meta, operation="create", defer_build=defer_build) itr += 1 self.state = CHECKING task_manager.schedule(self) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) task_manager.schedule(self) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) class CollectionDeleteTask(Task): def __init__(self, server, bucket, scope, collection): Task.__init__(self, "collection_delete_task") self.server = server self.bucket_name = bucket self.scope_name = scope self.collection_name = collection def execute(self, task_manager): try: RestConnection(self.server) except ServerUnavailableException as error: self.state = FINISHED self.set_exception(error) return try: CollectionsRest(self.server).delete_collection(bucket=self.bucket_name, scope=self.scope_name, collection=self.collection_name) self.state = CHECKING task_manager.schedule(self) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) class ScopeCollectionCreateTask(Task): def __init__(self, server, bucket, scope, collection, params=None): Task.__init__(self, "collection_create_task") self.server = server self.bucket_name = bucket self.scope_name = scope self.collection_name = collection self.collection_params = params def execute(self, task_manager): try: RestConnection(self.server) except ServerUnavailableException as error: self.state = FINISHED self.set_exception(error) return try: CollectionsRest(self.server).create_scope_collection(bucket=self.bucket_name, scope=self.scope_name, collection=self.collection_name, params=self.collection_params) self.state = CHECKING task_manager.schedule(self) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) class ScopeCollectionDeleteTask(Task): def __init__(self, server, bucket, scope, collection): Task.__init__(self, "collection_delete_task") self.server = server self.bucket_name = bucket self.scope_name = scope self.collection_name = collection def execute(self, task_manager): try: RestConnection(self.server) except ServerUnavailableException as error: self.state = FINISHED self.set_exception(error) return try: CollectionsRest(self.server).delete_scope_collection(bucket=self.bucket_name, scope=self.scope_name, collection=self.collection_name) self.state = CHECKING task_manager.schedule(self) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) class ScopeCreateTask(Task): def __init__(self, server, bucket, scope, params=None): Task.__init__(self, "scope_create_task") self.server = server self.bucket_name = bucket self.scope_name = scope self.scope_params = params def execute(self, task_manager): try: RestConnection(self.server) except ServerUnavailableException as error: self.state = FINISHED self.set_exception(error) return try: CollectionsRest(self.server).create_scope(bucket=self.bucket_name, scope=self.scope_name, params=self.scope_params) self.state = CHECKING task_manager.schedule(self) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) class ScopeDeleteTask(Task): def __init__(self, server, bucket, scope): Task.__init__(self, "scope_delete_task") self.server = server self.bucket_name = bucket self.scope_name = scope def execute(self, task_manager): try: RestConnection(self.server) except ServerUnavailableException as error: self.state = FINISHED self.set_exception(error) return try: CollectionsRest(self.server).delete_scope(bucket=self.bucket_name, scope=self.scope_name) self.state = CHECKING task_manager.schedule(self) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) class RebalanceTask(Task): def __init__(self, servers, to_add=[], to_remove=[], do_stop=False, progress=30, use_hostnames=False, services=None, sleep_before_rebalance=None): Task.__init__(self, "rebalance_task") self.servers = servers self.to_add = to_add self.to_remove = to_remove self.start_time = None if services is not None and not services: services = ["kv"] self.services = services self.monitor_vbuckets_shuffling = False self.sleep_before_rebalance = sleep_before_rebalance try: self.rest = RestConnection(self.servers[0]) except ServerUnavailableException as e: self.log.error(e) self.state = FINISHED self.set_exception(e) self.retry_get_progress = 0 self.use_hostnames = use_hostnames self.previous_progress = 0 self.old_vbuckets = {} def execute(self, task_manager): try: if len(self.to_add) and len(self.to_add) == len(self.to_remove): node_version_check = self.rest.check_node_versions() non_swap_servers = (node for node in self.servers if node not in self.to_add and node not in self.to_remove) self.old_vbuckets = RestHelper(self.rest)._get_vbuckets(non_swap_servers, None) if self.old_vbuckets: self.monitor_vbuckets_shuffling = True if self.monitor_vbuckets_shuffling and node_version_check and self.services: for service_group in self.services: if "kv" not in service_group: self.monitor_vbuckets_shuffling = False if self.monitor_vbuckets_shuffling and node_version_check: services_map = self.rest.get_nodes_services() for remove_node in self.to_remove: key = "{0}:{1}".format(remove_node.ip, remove_node.port) services = services_map[key] if "kv" not in services: self.monitor_vbuckets_shuffling = False if self.monitor_vbuckets_shuffling: self.log.info("This is swap rebalance and we will monitor vbuckets shuffling") self.add_nodes(task_manager) if self.sleep_before_rebalance: self.log.info("Sleep {0}secs before rebalance_start" .format(self.sleep_before_rebalance)) time.sleep(self.sleep_before_rebalance) self.start_rebalance(task_manager) self.state = CHECKING task_manager.schedule(self) except Exception as e: self.state = FINISHED traceback.print_exc() self.set_exception(e) def add_nodes(self, task_manager): master = self.servers[0] services_for_node = None node_index = 0 for node in self.to_add: self.log.info("adding node {0}:{1} to cluster".format(node.ip, node.port)) if self.services is not None: services_for_node = [self.services[node_index]] node_index += 1 if self.use_hostnames: remote_ip = node.hostname else: remote_ip = node.cluster_ip try: self.rest.add_node(master.rest_username, master.rest_password, remote_ip, node.port, services=services_for_node) except ServerAlreadyJoinedException: pass def start_rebalance(self, task_manager): nodes = self.rest.node_statuses() # Determine whether its a cluster_run/not cluster_run = True firstIp = self.servers[0].ip if len(self.servers) == 1 and self.servers[0].port == '8091': cluster_run = False else: for node in self.servers: if node.ip != firstIp: cluster_run = False break ejectedNodes = [] for server in self.to_remove: for node in nodes: if cluster_run: if int(server.port) == int(node.port): ejectedNodes.append(node.id) else: if self.use_hostnames: if server.hostname == node.ip and int(server.port) == int(node.port): ejectedNodes.append(node.id) elif server.ip == node.ip and int(server.port) == int(node.port): ejectedNodes.append(node.id) if self.rest.is_cluster_mixed(): # workaround MB-8094 self.log.warning("cluster is mixed. sleep for 15 seconds before rebalance") time.sleep(15) self.rest.rebalance(otpNodes=[node.id for node in nodes], ejectedNodes=ejectedNodes) self.start_time = time.time() def check(self, task_manager): status = None progress = -100 try: if self.monitor_vbuckets_shuffling: self.log.info("This is swap rebalance and we will monitor vbuckets shuffling") non_swap_servers = set(self.servers) - set(self.to_remove) - set(self.to_add) new_vbuckets = RestHelper(self.rest)._get_vbuckets(non_swap_servers, None) for vb_type in ["active_vb", "replica_vb"]: for srv in non_swap_servers: if not (len(self.old_vbuckets[srv][vb_type]) + 1 >= len(new_vbuckets[srv][vb_type]) and \ len(self.old_vbuckets[srv][vb_type]) - 1 <= len(new_vbuckets[srv][vb_type])): msg = "Vbuckets were suffled! Expected %s for %s" % (vb_type, srv.ip) + \ " are %s. And now are %s" % ( len(self.old_vbuckets[srv][vb_type]), len(new_vbuckets[srv][vb_type])) self.log.error(msg) self.log.error("Old vbuckets: %s, new vbuckets %s" % (self.old_vbuckets, new_vbuckets)) raise Exception(msg) time.sleep(10) (status, progress) = self.rest._rebalance_status_and_progress() self.log.info("Rebalance - status: {}, progress: {:.02f}%".format(status, progress)) # if ServerUnavailableException if progress == -100: self.retry_get_progress += 1 if self.previous_progress != progress: self.previous_progress = progress self.retry_get_progress = 0 else: self.retry_get_progress += 1 except RebalanceFailedException as ex: self.state = FINISHED self.set_exception(ex) self.retry_get_progress += 1 # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e, " in {0} sec".format(time.time() - self.start_time)) retry_get_process_num = 300 if self.rest.is_cluster_mixed(timeout=300): # See MB-40670 """ for mix cluster, rebalance takes longer """ self.log.info("rebalance in mix cluster") retry_get_process_num = 40 # we need to wait for status to be 'none' (i.e. rebalance actually finished and # not just 'running' and at 100%) before we declare ourselves done if progress != -1 and status != 'none': if self.retry_get_progress < retry_get_process_num: task_manager.schedule(self, 10) else: self.state = FINISHED # self.set_result(False) self.rest.print_UI_logs() self.set_exception(RebalanceFailedException( \ "seems like rebalance hangs. please check logs!")) else: success_cleaned = [] for removed in self.to_remove: try: rest = RestConnection(removed) except ServerUnavailableException as e: self.log.error(e) continue start = time.time() while time.time() - start < 30: try: if 'pools' in rest.get_pools_info() and \ (len(rest.get_pools_info()["pools"]) == 0): success_cleaned.append(removed) break else: time.sleep(0.1) except (ServerUnavailableException, IncompleteRead) as e: self.log.error(e) result = True for node in set(self.to_remove) - set(success_cleaned): self.log.error("node {0}:{1} was not cleaned after removing from cluster" \ .format(node.ip, node.port)) result = False self.log.info("rebalancing was completed with progress: {0}% in {1} sec". format(progress, time.time() - self.start_time)) for added in self.to_add: if added.internal_ip: self.log.info("Adding alternate address {} after rebalance in using internal ip {}".format(added.ip, added.internal_ip)) rest = RestConnection(added) rest.set_alternate_address(added.ip) self.state = FINISHED self.set_result(result) class StatsWaitTask(Task): EQUAL = '==' NOT_EQUAL = '!=' LESS_THAN = '<' LESS_THAN_EQ = '<=' GREATER_THAN = '>' GREATER_THAN_EQ = '>=' def __init__(self, servers, bucket, param, stat, comparison, value, scope=None, collection=None): Task.__init__(self, "stats_wait_task") self.servers = servers self.bucket = bucket if isinstance(bucket, Bucket): self.bucket = bucket.name self.param = param self.stat = stat self.comparison = comparison self.value = value self.conns = {} self.scope = scope self.collection = collection def execute(self, task_manager): self.state = CHECKING task_manager.schedule(self) def check(self, task_manager): stat_result = 0 for server in self.servers: try: shell = RemoteMachineShellConnection(server) cbstat = Cbstats(shell) stats = cbstat.all_stats(self.bucket, stat_name=self.param) if self.stat not in stats: self.state = FINISHED self.set_exception(Exception("Stat {0} not found".format(self.stat))) shell.disconnect() return if stats[self.stat].isdigit(): stat_result += int(stats[self.stat]) else: stat_result = stats[self.stat] shell.disconnect() except EOFError as ex: self.state = FINISHED self.set_exception(ex) shell.disconnect() return if not self._compare(self.comparison, str(stat_result), self.value): self.log.warning("Not Ready: %s %s %s %s expected on %s, %s bucket" % (self.stat, stat_result, self.comparison, self.value, self._stringify_servers(), self.bucket)) task_manager.schedule(self, 5) return self.log.info("Saw %s %s %s %s expected on %s,%s bucket" % (self.stat, stat_result, self.comparison, self.value, self._stringify_servers(), self.bucket)) for server, conn in list(self.conns.items()): conn.close() self.state = FINISHED self.set_result(True) def _stringify_servers(self): return ''.join([repr(server.ip + ":" + str(server.port)) for server in self.servers]) def _get_connection(self, server, admin_user='cbadminbucket', admin_pass='password'): if server not in self.conns: for i in range(3): try: self.conns[server] = MemcachedClientHelper.direct_client(server, self.bucket, admin_user=admin_user, admin_pass=admin_pass) return self.conns[server] except (EOFError, socket.error): self.log.error("failed to create direct client, retry in 1 sec") time.sleep(1) self.conns[server] = MemcachedClientHelper.direct_client(server, self.bucket, admin_user=admin_user, admin_pass=admin_pass) return self.conns[server] def _compare(self, cmp_type, a, b): if isinstance(b, int) and a.isdigit(): a = int(a) elif isinstance(b, int) and not a.isdigit(): return False if (cmp_type == StatsWaitTask.EQUAL and a == b) or \ (cmp_type == StatsWaitTask.NOT_EQUAL and a != b) or \ (cmp_type == StatsWaitTask.LESS_THAN_EQ and a <= b) or \ (cmp_type == StatsWaitTask.GREATER_THAN_EQ and a >= b) or \ (cmp_type == StatsWaitTask.LESS_THAN and a < b) or \ (cmp_type == StatsWaitTask.GREATER_THAN and a > b): return True return False class XdcrStatsWaitTask(StatsWaitTask): def __init__(self, servers, bucket, param, stat, comparison, value, scope=None, collection=None): StatsWaitTask.__init__(self, servers, bucket, param, stat, comparison, value, scope, collection) def check(self, task_manager): stat_result = 0 for server in self.servers: try: rest = RestConnection(server) stat = 'replications/' + rest.get_replication_for_buckets(self.bucket, self.bucket)[ 'id'] + '/' + self.stat # just get the required value, don't fetch the big big structure of stats stats_value = rest.fetch_bucket_xdcr_stats(self.bucket)['op']['samples'][stat][-1] stat_result += int(stats_value) except (EOFError, Exception) as ex: self.state = FINISHED self.set_exception(ex) return if not self._compare(self.comparison, str(stat_result), self.value): self.log.warning("Not Ready: %s %s %s %s expected on %s, %s bucket" % (self.stat, stat_result, self.comparison, self.value, self._stringify_servers(), self.bucket)) task_manager.schedule(self, 5) return self.log.info("Saw %s %s %s %s expected on %s,%s bucket" % (self.stat, stat_result, self.comparison, self.value, self._stringify_servers(), self.bucket)) for server, conn in list(self.conns.items()): conn.close() self.state = FINISHED self.set_result(True) class GenericLoadingTask(Thread, Task): def __init__(self, server, bucket, kv_store, batch_size=1, pause_secs=1, timeout_secs=60, compression=True, scope=None, collection=None): Thread.__init__(self) Task.__init__(self, "load_gen_task") self.kv_store = kv_store self.batch_size = batch_size self.pause = pause_secs self.timeout = timeout_secs self.server = server self.bucket = bucket self.collection = collection self.scope = scope if CHECK_FLAG: self.client = VBucketAwareMemcached(RestConnection(server), bucket) else: self.client = VBucketAwareMemcached(RestConnection(server), bucket, compression=compression) self.process_concurrency = THROUGHPUT_CONCURRENCY # task queue's for synchronization process_manager = Manager() self.wait_queue = process_manager.Queue() self.shared_kvstore_queue = process_manager.Queue() def execute(self, task_manager): self.start() self.state = EXECUTING def check(self, task_manager): pass def run(self): while self.has_next() and not self.done(): next(self) self.state = FINISHED self.set_result(True) def has_next(self): raise NotImplementedError def __next__(self): raise NotImplementedError def _unlocked_create(self, partition, key, value, is_base64_value=False): try: value_json = json.loads(value) if isinstance(value_json, dict): value_json['mutated'] = 0 value = json.dumps(value_json) except ValueError: index = random.choice(list(range(len(value)))) if not is_base64_value: value = value[0:index] + random.choice(string.ascii_uppercase) + value[index + 1:] except TypeError: value = json.dumps(value) try: self.client.set(key, self.exp, self.flag, value, scope=self.scope, collection=self.collection) if self.only_store_hash: value = str(crc32.crc32_hash(value)) partition.set(key, value, self.exp, self.flag) except Exception as error: self.state = FINISHED self.set_exception(error) def _unlocked_read(self, partition, key): try: o, c, d = self.client.get(key, scope=self.scope, collection=self.collection) except MemcachedError as error: if error.status == ERR_NOT_FOUND and partition.get_valid(key) is None: pass else: self.state = FINISHED self.set_exception(error) def _unlocked_replica_read(self, partition, key): try: o, c, d = self.client.getr(key, scope=self.scope, collection=self.collection) except Exception as error: self.state = FINISHED self.set_exception(error) def _unlocked_update(self, partition, key): value = None try: o, c, value = self.client.get(key, scope=self.scope, collection=self.collection) if value is None: return value_json = json.loads(value) value_json['mutated'] += 1 value = json.dumps(value_json) except MemcachedError as error: if error.status == ERR_NOT_FOUND and partition.get_valid(key) is None: # there is no such item, we do not know what value to set return else: self.state = FINISHED self.log.error("%s, key: %s update operation." % (error, key)) self.set_exception(error) return except (ValueError, json.JSONDecodeError) as e: if value is None: return index = random.choice(list(range(len(value)))) value = value[0:index] + random.choice(string.ascii_uppercase).encode() + value[index + 1:] except BaseException as error: self.state = FINISHED self.set_exception(error) try: self.client.set(key, self.exp, self.flag, value, scope=self.scope, collection=self.collection) if self.only_store_hash: if value != None: value = str(crc32.crc32_hash(value)) partition.set(key, value, self.exp, self.flag) except BaseException as error: self.state = FINISHED self.set_exception(error) def _unlocked_delete(self, partition, key): try: self.client.delete(key, scope=self.scope, collection=self.collection) partition.delete(key) except MemcachedError as error: if error.status == ERR_NOT_FOUND and partition.get_valid(key) is None: pass else: self.state = FINISHED self.log.error("%s, key: %s delete operation." % (error, key)) self.set_exception(error) except BaseException as error: self.state = FINISHED self.set_exception(error) def _unlocked_append(self, partition, key, value): try: o, c, old_value = self.client.get(key, scope=self.scope, collection=self.collection) if value is None: return value_json = json.loads(value) old_value_json = json.loads(old_value) old_value_json.update(value_json) old_value = json.dumps(old_value_json) value = json.dumps(value_json) except MemcachedError as error: if error.status == ERR_NOT_FOUND and partition.get_valid(key) is None: # there is no such item, we do not know what value to set return else: self.state = FINISHED self.set_exception(error) return except ValueError: o, c, old_value = self.client.get(key, scope=self.scope, collection=self.collection) index = random.choice(list(range(len(value)))) value = value[0:index] + random.choice(string.ascii_uppercase) + value[index + 1:] old_value += value except BaseException as error: self.state = FINISHED self.set_exception(error) try: self.client.append(key, value, scope=self.scope, collection=self.collection) if self.only_store_hash: old_value = str(crc32.crc32_hash(old_value)) partition.set(key, old_value) except BaseException as error: self.state = FINISHED self.set_exception(error) # start of batch methods def _create_batch_client(self, key_val, shared_client=None): """ standalone method for creating key/values in batch (sans kvstore) arguments: key_val -- array of key/value dicts to load size = self.batch_size shared_client -- optional client to use for data loading """ try: self._process_values_for_create(key_val) client = shared_client or self.client client.setMulti(self.exp, self.flag, key_val, self.pause, self.timeout, parallel=False, scope=self.scope, collection=self.collection) except ( MemcachedError, ServerUnavailableException, socket.error, EOFError, AttributeError, RuntimeError) as error: self.state = FINISHED self.set_exception(error) def _create_batch(self, partition_keys_dic, key_val): self._create_batch_client(key_val) self._populate_kvstore(partition_keys_dic, key_val) def _update_batch(self, partition_keys_dic, key_val): try: self._process_values_for_update(partition_keys_dic, key_val) self.client.setMulti(self.exp, self.flag, key_val, self.pause, self.timeout, parallel=False, scope=self.scope, collection=self.collection) self._populate_kvstore(partition_keys_dic, key_val) except ( MemcachedError, ServerUnavailableException, socket.error, EOFError, AttributeError, RuntimeError) as error: self.state = FINISHED self.set_exception(error) def _delete_batch(self, partition_keys_dic, key_val): for partition, keys in list(partition_keys_dic.items()): for key in keys: try: self.client.delete(key, scope=self.scope, collection=self.collection) partition.delete(key) except MemcachedError as error: if error.status == ERR_NOT_FOUND and partition.get_valid(key) is None: pass else: self.state = FINISHED self.set_exception(error) return except (ServerUnavailableException, socket.error, EOFError, AttributeError) as error: self.state = FINISHED self.set_exception(error) def _read_batch(self, partition_keys_dic, key_val): try: self.client.getMulti(list(key_val.keys()), self.pause, self.timeout, scope=self.scope, collection=self.collection) # print "the key is {} from collection {}".format(c, collection) except MemcachedError as error: self.state = FINISHED self.set_exception(error) def _process_values_for_create(self, key_val): for key, value in list(key_val.items()): try: value_json = json.loads(value) value_json['mutated'] = 0 value = json.dumps(value_json) except ValueError: index = random.choice(list(range(len(value)))) value = value[0:index] + random.choice(string.ascii_uppercase) + value[index + 1:] except TypeError: value = json.dumps(value) finally: key_val[key] = value def _process_values_for_update(self, partition_keys_dic, key_val): for partition, keys in list(partition_keys_dic.items()): for key in keys: value = partition.get_valid(key) if value is None: del key_val[key] continue try: value = key_val[ key] # new updated value, however it is not their in orginal code "LoadDocumentsTask" value_json = json.loads(value) value_json['mutated'] += 1 value = json.dumps(value_json) except ValueError: index = random.choice(list(range(len(value)))) value = value[0:index] + random.choice(string.ascii_uppercase) + value[index + 1:] finally: key_val[key] = value def _populate_kvstore(self, partition_keys_dic, key_val): for partition, keys in list(partition_keys_dic.items()): self._populate_kvstore_partition(partition, keys, key_val) def _release_locks_on_kvstore(self): for part in self._partitions_keyvals_dic.keys: self.kv_store.release_lock(part) def _populate_kvstore_partition(self, partition, keys, key_val): for key in keys: if self.only_store_hash: key_val[key] = str(crc32.crc32_hash(key_val[key])) partition.set(key, key_val[key], self.exp, self.flag) class LoadDocumentsTask(GenericLoadingTask): def __init__(self, server, bucket, generator, kv_store, op_type, exp, flag=0, only_store_hash=True, proxy_client=None, batch_size=1, pause_secs=1, timeout_secs=30, compression=True, scope=None, collection=None): GenericLoadingTask.__init__(self, server, bucket, kv_store, batch_size=batch_size, pause_secs=pause_secs, timeout_secs=timeout_secs, compression=compression, scope=scope, collection=collection) self.generator = generator self.op_type = op_type self.exp = exp self.flag = flag self.only_store_hash = only_store_hash self.scope = scope self.collection = collection if proxy_client: self.log.info("Changing client to proxy %s:%s..." % (proxy_client.host, proxy_client.port)) self.client = proxy_client def has_next(self): return self.generator.has_next() def next(self, override_generator=None): if self.batch_size == 1: key, value = next(self.generator) partition = self.kv_store.acquire_partition(key, self.bucket, self.scope, self.collection) if self.op_type == 'create': is_base64_value = (self.generator.__class__.__name__ == 'Base64Generator') self._unlocked_create(partition, key, value, is_base64_value=is_base64_value) elif self.op_type == 'read': self._unlocked_read(partition, key) elif self.op_type == 'read_replica': self._unlocked_replica_read(partition, key) elif self.op_type == 'update': self._unlocked_update(partition, key) elif self.op_type == 'delete': self._unlocked_delete(partition, key) elif self.op_type == 'append': self._unlocked_append(partition, key, value) else: self.state = FINISHED self.set_exception(Exception("Bad operation type: %s" % self.op_type)) self.kv_store.release_partition(key, self.bucket, self.scope, self.collection) else: doc_gen = override_generator or self.generator key_value = doc_gen.next_batch() partition_keys_dic = self.kv_store.acquire_partitions(list(key_value.keys()), self.bucket, self.scope, self.collection) if self.op_type == 'create': self._create_batch(partition_keys_dic, key_value) elif self.op_type == 'update': self._update_batch(partition_keys_dic, key_value) elif self.op_type == 'delete': self._delete_batch(partition_keys_dic, key_value) elif self.op_type == 'read': self._read_batch(partition_keys_dic, key_value) else: self.state = FINISHED self.set_exception(Exception("Bad operation type: %s" % self.op_type)) self.kv_store.release_partitions(list(partition_keys_dic.keys())) class LoadDocumentsGeneratorsTask(LoadDocumentsTask): def __init__(self, server, bucket, generators, kv_store, op_type, exp, flag=0, only_store_hash=True, batch_size=1, pause_secs=1, timeout_secs=60, compression=True, scope=None, collection=None): LoadDocumentsTask.__init__(self, server, bucket, generators[0], kv_store, op_type, exp, flag=flag, only_store_hash=only_store_hash, batch_size=batch_size, pause_secs=pause_secs, timeout_secs=timeout_secs, compression=compression, scope=scope, collection=collection) if batch_size == 1: self.generators = generators else: self.generators = [] for i in generators: if i.isGenerator(): self.generators.append(BatchedDocumentGenerator(i, batch_size)) else: self.generators.append(i) # only run high throughput for batch-create workloads # also check number of input generators isn't greater than # process_concurrency as too many generators become inefficient self.is_high_throughput_mode = False if ALLOW_HTP and not TestInputSingleton.input.param("disable_HTP", False): self.is_high_throughput_mode = self.op_type == "create" and \ self.batch_size > 1 and \ len(self.generators) < self.process_concurrency self.input_generators = generators self.bucket = bucket self.op_types = None self.buckets = None if isinstance(op_type, list): self.op_types = op_type if isinstance(bucket, list): self.buckets = bucket self.compression = compression self.scope = scope self.collection = collection def run(self): if self.op_types: if len(self.op_types) != len(self.generators): self.state = FINISHED self.set_exception(Exception("not all generators have op_type!")) if self.buckets: if len(self.op_types) != len(self.buckets): self.state = FINISHED self.set_exception(Exception("not all generators have bucket specified!")) # check if running in high throughput mode or normal if self.is_high_throughput_mode: self.run_high_throughput_mode() else: self.run_normal_throughput_mode() self.state = FINISHED self.set_result(True) def run_normal_throughput_mode(self): iterator = 0 for generator in self.generators: self.generator = generator if self.op_types: self.op_type = self.op_types[iterator] if self.buckets: self.bucket = self.buckets[iterator] while self.has_next() and not self.done(): self.next() iterator += 1 def run_high_throughput_mode(self): # high throughput mode requires partitioning the doc generators self.generators = [] for gen in self.input_generators: gen_start = int(gen.start) gen_end = max(int(gen.end), 1) gen_range = max(int(gen.end / self.process_concurrency), 1) for pos in range(gen_start, gen_end, gen_range): try: partition_gen = copy.deepcopy(gen) partition_gen.start = pos partition_gen.itr = pos partition_gen.end = pos + gen_range if partition_gen.end > gen.end: partition_gen.end = gen.end batch_gen = BatchedDocumentGenerator( partition_gen, self.batch_size) self.generators.append(batch_gen) except Exception as e: traceback.print_exc() iterator = 0 all_processes = [] for generator in self.generators: # only start processing when there resources available CONCURRENCY_LOCK.acquire() # add child process to wait queue self.wait_queue.put(iterator + 1) generator_process = Process( target=self.run_generator, args=(generator, iterator)) generator_process.start() iterator += 1 all_processes.append(generator_process) # wait for all child processes to finish self.wait_queue.join() # merge kvstore partitions while self.shared_kvstore_queue.empty() is False: # get partitions created by child process rv = self.shared_kvstore_queue.get() if rv["err"] is not None: self.state = FINISHED self.set_exception(rv["err"]) return # merge child partitions with parent generator_partitions = rv["partitions"] self.kv_store.merge_partitions(generator_partitions) # terminate child process iterator -= 1 all_processes[iterator].terminate() def run_generator(self, generator, iterator): tmp_kv_store = KVStore() rv = {"err": None, "partitions": None} try: if CHECK_FLAG: client = VBucketAwareMemcached( RestConnection(self.server), self.bucket) else: client = VBucketAwareMemcached( RestConnection(self.server), self.bucket, compression=self.compression) try: if self.op_types: self.op_type = self.op_types[iterator] if self.buckets: self.bucket = self.buckets[iterator] while generator.has_next() and not self.done(): # generate key_value = generator.next_batch() # create self._create_batch_client(key_value, client) # cache self.cache_items(tmp_kv_store, key_value) except Exception as e: traceback.print_exc() except Exception as ex: rv["err"] = ex else: rv["partitions"] = tmp_kv_store.get_partitions() finally: # share the kvstore from this generator self.shared_kvstore_queue.put(rv) self.wait_queue.task_done() # release concurrency lock CONCURRENCY_LOCK.release() def cache_items(self, store, key_value): """ unpacks keys,values and adds them to provided store """ for key, value in key_value.items(): if self.only_store_hash: value = str(crc32.crc32_hash(value)) partition = store.partition(key, self.scope, self.collection, self.bucket) partition["partition"].set( key, value, self.exp, self.flag) class ESLoadGeneratorTask(Task): """ Class to load/update/delete documents into/from Elastic Search """ def __init__(self, es_instance, index_name, generator, op_type="create", scope=None, collection=None): Task.__init__(self, "ES_loader_task") self.es_instance = es_instance self.index_name = index_name self.generator = generator self.iterator = 0 self.scope = scope self.collection = collection self.log.info("Starting to load data into Elastic Search ...") def check(self, task_manager): self.state = FINISHED self.set_result(True) def execute(self, task_manager): for key, doc in self.generator: doc = json.loads(doc) self.es_instance.load_data(self.index_name, json.dumps(doc, encoding='utf-8'), doc['type'], key, self.scope, self.collection) self.iterator += 1 if math.fmod(self.iterator, 500) == 0.0: self.log.info("{0} documents loaded into ES". format(self.iterator)) self.state = FINISHED self.set_result(True) class ESBulkLoadGeneratorTask(Task): """ Class to load/update/delete documents into/from Elastic Search """ def __init__(self, es_instance, index_name, generator, op_type="create", batch=1000, scope=None, collection=None): Task.__init__(self, "ES_loader_task") self.es_instance = es_instance self.index_name = index_name self.generator = generator self.iterator = 0 self.op_type = op_type self.batch_size = batch self.scope = scope self.collection = collection self.log.info("Starting operation '%s' on Elastic Search ..." % op_type) def check(self, task_manager): self.state = FINISHED self.set_result(True) def execute(self, task_manager): es_filename = "/tmp/es_bulk.txt" es_bulk_docs = [] loaded = 0 batched = 0 for key, doc in self.generator: doc = json.loads(doc) es_doc = { self.op_type: { "_index": self.index_name, "_type": doc['type'], "_id": key, } } es_bulk_docs.append(json.dumps(es_doc)) if self.op_type == "create": es_bulk_docs.append(json.dumps(doc)) elif self.op_type == "update": doc['mutated'] += 1 es_bulk_docs.append(json.dumps({"doc": doc})) batched += 1 if batched == self.batch_size or not self.generator.has_next(): es_file = open(es_filename, "wb") for line in es_bulk_docs: es_file.write("{}\n".format(line).encode()) es_file.close() self.es_instance.load_bulk_data(es_filename) loaded += batched self.log.info("{0} documents bulk loaded into ES".format(loaded)) self.es_instance.update_index(self.index_name) batched = 0 indexed = self.es_instance.get_index_count(self.index_name) self.log.info("ES index count for '{0}': {1}". format(self.index_name, indexed)) self.state = FINISHED self.set_result(True) class ESRunQueryCompare(Task): def __init__(self, fts_index, es_instance, query_index, es_index_name=None, n1ql_executor=None, use_collections=False): Task.__init__(self, "Query_runner_task") self.fts_index = fts_index self.fts_query = fts_index.fts_queries[query_index] self.es = es_instance if self.es: self.es_query = es_instance.es_queries[query_index] self.max_verify = None self.show_results = False self.query_index = query_index self.passed = True self.es_index_name = es_index_name or "es_index" self.n1ql_executor = n1ql_executor self.score = TestInputSingleton.input.param("score",'') self.use_collections = use_collections def check(self, task_manager): self.state = FINISHED self.set_result(self.result) def execute(self, task_manager): self.es_compare = True should_verify_n1ql = True try: self.log.info("---------------------------------------" "-------------- Query # %s -------------" "---------------------------------------" % str(self.query_index + 1)) try: fts_hits, fts_doc_ids, fts_time, fts_status = \ self.run_fts_query(self.fts_query, self.score) self.log.info("Status: %s" % fts_status) if fts_status == 'fail': error = fts_doc_ids if "err: TooManyClauses over field" in str(error): self.log.info("FTS chose not to run this big query" "...skipping ES validation") self.passed = True self.es_compare = False should_verify_n1ql = False elif fts_hits < 0: self.passed = False elif 'errors' in list(fts_status.keys()) and fts_status['errors']: if fts_status['successful'] == 0 and \ (list(set(fts_status['errors'].values())) == ['context deadline exceeded'] or "TooManyClauses" in str(list(set(fts_status['errors'].values())))): # too many clauses in the query for fts to process self.log.info("FTS chose not to run this big query" "...skipping ES validation") self.passed = True self.es_compare = False should_verify_n1ql = False elif 0 < fts_status['successful'] < \ self.fts_index.num_pindexes: # partial results self.log.info("FTS returned partial results..." "skipping ES validation") self.passed = True self.es_compare = False self.log.info("FTS hits for query: %s is %s (took %sms)" % \ (json.dumps(self.fts_query, ensure_ascii=False), fts_hits, float(fts_time) / 1000000)) except ServerUnavailableException: self.log.error("ERROR: FTS Query timed out (client timeout=70s)!") self.passed = False es_hits = 0 if self.es and self.es_query: es_hits, es_doc_ids, es_time = self.run_es_query(self.es_query) self.log.info("ES hits for query: %s on %s is %s (took %sms)" % \ (json.dumps(self.es_query, ensure_ascii=False), self.es_index_name, es_hits, es_time)) if self.passed and self.es_compare: if int(es_hits) != int(fts_hits): msg = "FAIL: FTS hits: %s, while ES hits: %s" \ % (fts_hits, es_hits) self.log.error(msg) es_but_not_fts = list(set(es_doc_ids) - set(fts_doc_ids)) fts_but_not_es = list(set(fts_doc_ids) - set(es_doc_ids)) if not (es_but_not_fts or fts_but_not_es): self.log.info("SUCCESS: Docs returned by FTS = docs" " returned by ES, doc_ids verified") else: if fts_but_not_es: msg = "FAIL: Following %s doc(s) were not returned" \ " by ES,but FTS, printing 50: %s" \ % (len(fts_but_not_es), fts_but_not_es[:50]) else: msg = "FAIL: Following %s docs were not returned" \ " by FTS, but ES, printing 50: %s" \ % (len(es_but_not_fts), es_but_not_fts[:50]) self.log.error(msg) self.passed = False if fts_hits <= 0 and es_hits == 0: should_verify_n1ql = False if self.n1ql_executor and should_verify_n1ql: if self.fts_index.dataset == 'all': query_type = 'emp' if int(TestInputSingleton.input.param("doc_maps", 1)) > 1: query_type = 'wiki' wiki_fields = ["revision.text", "title"] if any(field in str(json.dumps(self.fts_query)) for field in wiki_fields): query_type = 'wiki' else: query_type = self.fts_index.dataset geo_strings = ['"field": "geo"'] if any(geo_str in str(json.dumps(self.fts_query)) for geo_str in geo_strings): query_type = 'earthquake' if self.use_collections: kv_container = "default:default.scope1.collection1" else: kv_container = "default" n1ql_queries = [f"select meta().id from {kv_container} where type='" + str( query_type) + "' and search(default, " + str( json.dumps(self.fts_query, ensure_ascii=False)) + ")", f"select meta().id from {kv_container} where type='" + str( query_type) + "' and search(default, " + str( json.dumps(self.fts_query, ensure_ascii=False)) + ",{\"index\": \"" + self.fts_index.name + "\"})", f"select meta().id,* from {kv_container} where type='" + str( query_type) + "' and search(default, " + str( json.dumps(self.fts_query, ensure_ascii=False)) + ",{\"index\": \"" + self.fts_index.name + "\"})"] for n1ql_query in n1ql_queries: if ("disjuncts" not in n1ql_query and "-" not in n1ql_query) or "\"index\"" in n1ql_query: self.log.info("Running N1QL query: " + str(n1ql_query)) n1ql_result = self.n1ql_executor.run_n1ql_query(query=n1ql_query) if n1ql_result['status'] == 'success': n1ql_hits = n1ql_result['metrics']['resultCount'] n1ql_doc_ids = [] for res in n1ql_result['results']: n1ql_doc_ids.append(res['id']) n1ql_time = n1ql_result['metrics']['elapsedTime'] self.log.info("N1QL hits for query: %s is %s (took %s)" % \ (json.dumps(n1ql_query, ensure_ascii=False), n1ql_hits, n1ql_time)) if self.passed: if int(n1ql_hits) != int(fts_hits): msg = "FAIL: FTS hits: %s, while N1QL hits: %s" \ % (fts_hits, n1ql_hits) self.log.error(msg) n1ql_but_not_fts = list(set(n1ql_doc_ids) - set(fts_doc_ids)) fts_but_not_n1ql = list(set(fts_doc_ids) - set(n1ql_doc_ids)) if not (n1ql_but_not_fts or fts_but_not_n1ql): self.log.info("SUCCESS: Docs returned by FTS = docs" " returned by N1QL, doc_ids verified") else: if fts_but_not_n1ql: msg = "FAIL: Following %s doc(s) were not returned" \ " by N1QL,but FTS, printing 50: %s" \ % (len(fts_but_not_n1ql), fts_but_not_n1ql[:50]) else: msg = "FAIL: Following %s docs were not returned" \ " by FTS, but N1QL, printing 50: %s" \ % (len(n1ql_but_not_fts), n1ql_but_not_fts[:50]) self.log.error(msg) self.passed = False else: self.passed = False self.log.info("N1QL query execution is failed.") self.log.error(n1ql_result["errors"][0]['msg']) self.state = CHECKING task_manager.schedule(self) if not should_verify_n1ql and self.n1ql_executor: self.log.info("Skipping N1QL result validation since FTS results are - " + str( fts_hits) + " and es results are - " + str(es_hits) + ".") except Exception as e: self.log.error(e) self.set_exception(e) self.state = FINISHED def run_fts_query(self, query, score=''): return self.fts_index.execute_query(query, score=score) def run_es_query(self, query): return self.es.search(index_name=self.es_index_name, query=query) # This will be obsolete with the implementation of batch operations in LoadDocumentsTaks class BatchedLoadDocumentsTask(GenericLoadingTask): def __init__(self, server, bucket, generator, kv_store, op_type, exp, flag=0, only_store_hash=True, batch_size=100, pause_secs=1, timeout_secs=60, compression=True, scope=None, collection=None): GenericLoadingTask.__init__(self, server, bucket, kv_store, compression=compression, scope=scope, collection=collection) self.batch_generator = BatchedDocumentGenerator(generator, batch_size) self.op_type = op_type self.exp = exp self.flag = flag self.only_store_hash = only_store_hash self.batch_size = batch_size self.pause = pause_secs self.timeout = timeout_secs self.bucket = bucket self.server = server self.scope=scope self.collection = collection def has_next(self): has = self.batch_generator.has_next() if math.fmod(self.batch_generator._doc_gen.itr, 50000) == 0.0 or not has: self.log.info("Batch {0} documents queued #: {1} with exp:{2} @ {3}, bucket {4}". \ format(self.op_type, (self.batch_generator._doc_gen.itr - self.batch_generator._doc_gen.start), self.exp, self.server.ip, self.bucket)) return has def __next__(self): key_value = self.batch_generator.next_batch() partition_keys_dic = self.kv_store.acquire_partitions(list(key_value.keys()), self.bucket, self.scope, self.collection) if self.op_type == 'create': self._create_batch(partition_keys_dic, key_value) elif self.op_type == 'update': self._update_batch(partition_keys_dic, key_value) elif self.op_type == 'delete': self._delete_batch(partition_keys_dic, key_value) elif self.op_type == 'read': self._read_batch(partition_keys_dic, key_value) else: self.state = FINISHED self.set_exception(Exception("Bad operation type: %s" % self.op_type)) self.kv_store.release_partitions(list(partition_keys_dic.keys()), self.scope, self.collection) def _create_batch(self, partition_keys_dic, key_val): try: self._process_values_for_create(key_val) self.client.setMulti(self.exp, self.flag, key_val, self.pause, self.timeout, parallel=False, scope=self.scope, collection=self.collection) self._populate_kvstore(partition_keys_dic, key_val) except ( MemcachedError, ServerUnavailableException, socket.error, EOFError, AttributeError, RuntimeError) as error: self.state = FINISHED self.set_exception(error) def _update_batch(self, partition_keys_dic, key_val): try: self._process_values_for_update(partition_keys_dic, key_val) self.client.setMulti(self.exp, self.flag, key_val, self.pause, self.timeout, parallel=False, scope=self.scope, collection=self.collection) self._populate_kvstore(partition_keys_dic, key_val) except ( MemcachedError, ServerUnavailableException, socket.error, EOFError, AttributeError, RuntimeError) as error: self.state = FINISHED self.set_exception(error) def _delete_batch(self, partition_keys_dic, key_val): for partition, keys in list(partition_keys_dic.items()): for key in keys: try: self.client.delete(key, scope=self.scope, collection=self.collection) partition.delete(key) except MemcachedError as error: if error.status == ERR_NOT_FOUND and partition.get_valid(key) is None: pass else: self.state = FINISHED self.set_exception(error) return except (ServerUnavailableException, socket.error, EOFError, AttributeError) as error: self.state = FINISHED self.set_exception(error) def _read_batch(self, partition_keys_dic, key_val): try: self.client.getMulti(list(key_val.keys()), self.pause, self.timeout, scope=self.scope, collection=self.collection) except MemcachedError as error: self.state = FINISHED self.set_exception(error) def _process_values_for_create(self, key_val): for key, value in list(key_val.items()): try: value_json = json.loads(value) value_json['mutated'] = 0 value = json.dumps(value_json) except ValueError: index = random.choice(list(range(len(value)))) value = value[0:index] + random.choice(string.ascii_uppercase) + value[index + 1:] finally: key_val[key] = value def _process_values_for_update(self, partition_keys_dic, key_val): for partition, keys in list(partition_keys_dic.items()): for key in keys: value = partition.get_valid(key) if value is None: del key_val[key] continue try: value = key_val[ key] # new updated value, however it is not their in orginal code "LoadDocumentsTask" value_json = json.loads(value) value_json['mutated'] += 1 value = json.dumps(value_json) except ValueError: index = random.choice(list(range(len(value)))) value = value[0:index] + random.choice(string.ascii_uppercase) + value[index + 1:] finally: key_val[key] = value def _populate_kvstore(self, partition_keys_dic, key_val): for partition, keys in list(partition_keys_dic.items()): self._populate_kvstore_partition(partition, keys, key_val) def _release_locks_on_kvstore(self): for part in self._partitions_keyvals_dic.keys: self.kv_store.release_lock(part) def _populate_kvstore_partition(self, partition, keys, key_val): for key in keys: if self.only_store_hash: key_val[key] = str(crc32.crc32_hash(key_val[key])) partition.set(key, key_val[key], self.exp, self.flag) class WorkloadTask(GenericLoadingTask): def __init__(self, server, bucket, kv_store, num_ops, create, read, update, delete, exp, compression=True, scope=None, collection=None): GenericLoadingTask.__init__(self, server, bucket, kv_store, compression=compression, scope=scope, collection=collection) self.itr = 0 self.num_ops = num_ops self.create = create self.read = create + read self.update = create + read + update self.delete = create + read + update + delete self.exp = exp self.scope = scope self.collection = collection self.bucket = bucket def has_next(self): if self.num_ops == 0 or self.itr < self.num_ops: return True return False def __next__(self): self.itr += 1 rand = random.randint(1, self.delete) if 0 < rand <= self.create: self._create_random_key() elif self.create < rand <= self.read: self._get_random_key() elif self.read < rand <= self.update: self._update_random_key() elif self.update < rand <= self.delete: self._delete_random_key() def _get_random_key(self): partition, part_num = self.kv_store.acquire_random_partition() if partition is None: return key = partition.get_random_valid_key() if key is None: self.kv_store.release_partitions(part_num) return self._unlocked_read(partition, key) self.kv_store.release_partitions(part_num) def _create_random_key(self): partition, part_num = self.kv_store.acquire_random_partition(False) if partition is None: return key = partition.get_random_deleted_key() if key is None: self.kv_store.release_partitions(part_num) return value = partition.get_deleted(key) if value is None: self.kv_store.release_partitions(part_num) return self._unlocked_create(partition, key, value) self.kv_store.release_partitions(part_num) def _update_random_key(self): partition, part_num = self.kv_store.acquire_random_partition() if partition is None: return key = partition.get_random_valid_key() if key is None: self.kv_store.release_partitions(part_num) return self._unlocked_update(partition, key) self.kv_store.release_partitions(part_num) def _delete_random_key(self): partition, part_num = self.kv_store.acquire_random_partition() if partition is None: return key = partition.get_random_valid_key() if key is None: self.kv_store.release_partitions(part_num) return self._unlocked_delete(partition, key) self.kv_store.release_partitions(part_num) class ValidateDataTask(GenericLoadingTask): def __init__(self, server, bucket, kv_store, max_verify=None, only_store_hash=True, replica_to_read=None, compression=True, scope=None, collection=None): GenericLoadingTask.__init__(self, server, bucket, kv_store, compression=compression, scope=scope, collection=collection) self.collection = collection self.scope = scope self.bucket = bucket self.valid_keys, self.deleted_keys = kv_store.key_set(bucket=self.bucket, scope=self.scope, collection=self.collection) self.num_valid_keys = len(self.valid_keys) self.num_deleted_keys = len(self.deleted_keys) self.itr = 0 self.max_verify = self.num_valid_keys + self.num_deleted_keys self.only_store_hash = only_store_hash self.replica_to_read = replica_to_read self.bucket = bucket self.server = server if max_verify is not None: self.max_verify = min(max_verify, self.max_verify) self.log.info( "%s items will be verified on %s bucket on scope %s on collection %s" % (self.max_verify, bucket, self.scope, self.collection)) self.start_time = time.time() def has_next(self): if self.itr < (self.num_valid_keys + self.num_deleted_keys) and \ self.itr < self.max_verify: if not self.itr % 50000: self.log.info("{0} items were verified".format(self.itr)) return True self.log.info("{0} items were verified in {1} sec.the average number of ops\ - {2} per second ".format(self.itr, time.time() - self.start_time, self.itr // (time.time() - self.start_time)).rstrip()) return False def __next__(self): if self.itr < self.num_valid_keys: self._check_valid_key(self.valid_keys[self.itr], self.bucket, scope=self.scope, collection=self.collection) else: self._check_deleted_key(self.deleted_keys[self.itr - self.num_valid_keys], self.bucket, scope=self.scope, collection=self.collection) self.itr += 1 def _check_valid_key(self, key, bucket="default", scope=None, collection=None): partition = self.kv_store.acquire_partition(key, bucket, scope=scope, collection=collection) value = partition.get_valid(key) flag = partition.get_flag(key) if value is None or flag is None: self.kv_store.release_partition(key, bucket, scope=scope, collection=collection) return try: if self.replica_to_read is None: o, c, d = self.client.get(key, scope=scope, collection=collection) else: o, c, d = self.client.getr(key, replica_index=self.replica_to_read, scope=scope, collection=collection) try: d = d.decode() except AttributeError: pass if self.only_store_hash: if crc32.crc32_hash(d) != int(value): self.state = FINISHED self.set_exception(Exception( 'Key: %s, Bad hash result: %d != %d for key %s' % (key, crc32.crc32_hash(d), int(value), key))) else: value = json.dumps(value) if d != json.loads(value): self.log.info(f"the scope {scope} collection is {collection} for which the value is failing") self.state = FINISHED self.set_exception( Exception('Key: %s, Bad result: %s != %s for key %s' % (key, json.dumps(d), value, key))) if CHECK_FLAG and o != flag: self.state = FINISHED self.set_exception( Exception('Key: %s, Bad result for flag value: %s != the value we set: %s' % (key, o, flag))) except MemcachedError as error: if error.status == ERR_NOT_FOUND and partition.get_valid(key) is None: pass else: self.state = FINISHED self.set_exception(error) except Exception as error: self.log.error("Unexpected error: %s" % str(error)) self.state = FINISHED self.set_exception(error) self.kv_store.release_partition(key, bucket, scope=scope, collection=collection) def _check_deleted_key(self, key, bucket="default", scope=None, collection=None): partition = self.kv_store.acquire_partition(key, bucket, scope=scope, collection=collection) try: self.client.delete(key, scope=scope, collection=collection) if partition.get_valid(key) is not None: self.state = FINISHED self.set_exception(Exception('Not Deletes: %s' % (key))) except MemcachedError as error: if error.status == ERR_NOT_FOUND: pass else: self.state = FINISHED self.set_exception(error) except Exception as error: if error.rc != NotFoundError: self.state = FINISHED self.set_exception(error) self.kv_store.release_partition(key, bucket, scope=scope, collection=collection) class ValidateDataWithActiveAndReplicaTask(GenericLoadingTask): def __init__(self, server, bucket, kv_store, max_verify=None, compression=True, scope=None, collection=None): GenericLoadingTask.__init__(self, server, bucket, kv_store, compression=compression, scope=scope, collection=collection) self.collection = collection self.scope = scope self.bucket = bucket self.valid_keys, self.deleted_keys = kv_store.key_set(bucket=self.bucket, scope=self.scope, collection=self.collection) self.num_valid_keys = len(self.valid_keys) self.num_deleted_keys = len(self.deleted_keys) self.itr = 0 self.max_verify = self.num_valid_keys + self.num_deleted_keys if max_verify is not None: self.max_verify = min(max_verify, self.max_verify) self.log.info("%s items will be verified on %s bucket" % (self.max_verify, bucket)) self.start_time = time.time() def has_next(self): if self.itr < (self.num_valid_keys + self.num_deleted_keys) and \ self.itr < self.max_verify: if not self.itr % 50000: self.log.info("{0} items were verified".format(self.itr)) return True self.log.info("{0} items were verified in {1} sec.the average number of ops\ - {2} per second ".format(self.itr, time.time() - self.start_time, self.itr // (time.time() - self.start_time)).rstrip()) return False def __next__(self): if self.itr < self.num_valid_keys: self._check_valid_key(self.valid_keys[self.itr], self.bucket, self.scope, self.collection) else: self._check_deleted_key(self.deleted_keys[self.itr - self.num_valid_keys], self.bucket, self.scope, self.collection) self.itr += 1 def _check_valid_key(self, key, bucket, scope=None, collection=None): partition = self.kv_store.acquire_partition(key, bucket, scope=scope, collection=collection) try: o, c, d = self.client.get(key, scope=scope, collection=collection) o_r, c_r, d_r = self.client.getr(key, replica_index=0, scope=scope, collection=collection) if o != o_r: self.state = FINISHED self.set_exception(Exception( 'ACTIVE AND REPLICA FLAG CHECK FAILED :: Key: %s, Bad result for CAS value: REPLICA FLAG %s != ACTIVE FLAG %s' % ( key, o_r, o))) if c != c_r: self.state = FINISHED self.set_exception(Exception( 'ACTIVE AND REPLICA CAS CHECK FAILED :: Key: %s, Bad result for CAS value: REPLICA CAS %s != ACTIVE CAS %s' % ( key, c_r, c))) if d != d_r: self.state = FINISHED self.set_exception(Exception( 'ACTIVE AND REPLICA VALUE CHECK FAILED :: Key: %s, Bad result for Value value: REPLICA VALUE %s != ACTIVE VALUE %s' % ( key, d_r, d))) except MemcachedError as error: if error.status == ERR_NOT_FOUND and partition.get_valid(key) is None: pass else: self.state = FINISHED self.set_exception(error) except Exception as error: self.log.error("Unexpected error: %s" % str(error)) self.state = FINISHED self.set_exception(error) def _check_deleted_key(self, key, bucket, scope=None, collection=None): partition = self.kv_store.acquire_partition(key, bucket, scope=scope, collection=collection) try: self.client.delete(key, scope=scope, collection=collection) if partition.get_valid(key) is not None: self.state = FINISHED self.set_exception(Exception('ACTIVE CHECK :: Not Deletes: %s' % key)) except MemcachedError as error: if error.status == ERR_NOT_FOUND: pass else: self.state = FINISHED self.set_exception(error) except Exception as error: if error.rc != NotFoundError: self.state = FINISHED self.set_exception(error) self.kv_store.release_partition(key, bucket, scope=scope, collection=collection) class BatchedValidateDataTask(GenericLoadingTask): def __init__(self, server, bucket, kv_store, max_verify=None, only_store_hash=True, batch_size=100, timeout_sec=30, compression=True, scope=None, collection=None): GenericLoadingTask.__init__(self, server, bucket, kv_store, compression=compression, scope=scope, collection=collection) self.collection = collection self.scope = scope self.bucket = bucket self.valid_keys, self.deleted_keys = kv_store.key_set(bucket=self.bucket, scope=self.scope, collection=self.collection) self.num_valid_keys = len(self.valid_keys) self.num_deleted_keys = len(self.deleted_keys) self.itr = 0 self.max_verify = self.num_valid_keys + self.num_deleted_keys self.timeout_sec = timeout_sec self.only_store_hash = only_store_hash if max_verify is not None: self.max_verify = min(max_verify, self.max_verify) self.log.info("%s items will be verified on %s bucket" % (self.max_verify, bucket)) self.batch_size = batch_size self.start_time = time.time() def has_next(self): has = False if self.itr < (self.num_valid_keys + self.num_deleted_keys) and self.itr < self.max_verify: has = True if math.fmod(self.itr, 10000) == 0.0: self.log.info("{0} items were verified".format(self.itr)) if not has: self.log.info("{0} items were verified in {1} sec.the average number of ops\ - {2} per second".format(self.itr, time.time() - self.start_time, self.itr // (time.time() - self.start_time)).rstrip()) return has def __next__(self): if self.itr < self.num_valid_keys: keys_batch = self.valid_keys[self.itr:self.itr + self.batch_size] self.itr += len(keys_batch) self._check_valid_keys(keys_batch, self.bucket, self.scope, self.collection) else: self._check_deleted_key(self.deleted_keys[self.itr - self.num_valid_keys], self.bucket, self.scope, self.collection) self.itr += 1 def _check_valid_keys(self, keys, bucket, scope=None, collection=None): partition_keys_dic = self.kv_store.acquire_partitions(keys, bucket, scope=scope, collection=collection) try: key_vals = self.client.getMulti(keys, parallel=True, timeout_sec=self.timeout_sec, scope=scope, collection=collection) except ValueError as error: self.log.error("Read failed via memcached client. Error: %s" % str(error)) self.state = FINISHED self.kv_store.release_partitions(list(partition_keys_dic.keys())) self.set_exception(error) return except BaseException as error: # handle all other exception, for instance concurrent.futures._base.TimeoutError self.log.error("Read failed via memcached client. Error: %s" % str(error)) self.state = FINISHED self.kv_store.release_partitions(list(partition_keys_dic.keys())) self.set_exception(error) return for partition, keys in list(partition_keys_dic.items()): self._check_validity(partition, keys, key_vals) self.kv_store.release_partitions(list(partition_keys_dic.keys())) def _check_validity(self, partition, keys, key_vals): for key in keys: value = partition.get_valid(key) flag = partition.get_flag(key) if value is None: continue try: o, c, d = key_vals[key] if self.only_store_hash: if crc32.crc32_hash(d) != int(value): self.state = FINISHED self.set_exception( Exception('Key: %s Bad hash result: %d != %d' % (key, crc32.crc32_hash(d), int(value)))) else: # value = json.dumps(value) if json.loads(d) != json.loads(value): self.state = FINISHED self.set_exception(Exception('Key: %s Bad result: %s != %s' % (key, json.dumps(d), value))) if CHECK_FLAG and o != flag: self.state = FINISHED self.set_exception( Exception('Key: %s Bad result for flag value: %s != the value we set: %s' % (key, o, flag))) except KeyError as error: self.state = FINISHED self.set_exception(error) def _check_deleted_key(self, key, bucket, scope=None, collection=None): partition = self.kv_store.acquire_partition(key, bucket, scope=scope, collection=collection) try: self.client.delete(key, scope=scope, collection=collection) if partition.get_valid(key) is not None: self.state = FINISHED self.set_exception(Exception('Not Deletes: %s' % (key))) except MemcachedError as error: if error.status == ERR_NOT_FOUND: pass else: self.state = FINISHED self.kv_store.release_partition(key, bucket, scope=scope, collection=collection) self.set_exception(error) except Exception as error: if error.rc != NotFoundError: self.state = FINISHED self.kv_store.release_partition(key, bucket, scope=scope, collection=collection) self.set_exception(error) self.kv_store.release_partition(key, bucket, scope=scope, collection=collection) class VerifyRevIdTask(GenericLoadingTask): def __init__(self, src_server, dest_server, bucket, src_kv_store, dest_kv_store, max_err_count=200000, max_verify=None, compression=True, scope=None, collection=None): GenericLoadingTask.__init__(self, src_server, bucket, src_kv_store, compression=compression, scope=scope, collection=collection) from memcached.helper.data_helper import VBucketAwareMemcached as SmartClient self.collection = collection self.scope = scope self.client_src = SmartClient(RestConnection(src_server), bucket) self.client_dest = SmartClient(RestConnection(dest_server), bucket) self.src_valid_keys, self.src_deleted_keys = src_kv_store.key_set(bucket=self.bucket, scope=self.scope, collection=self.collection) self.dest_valid_keys, self.dest_del_keys = dest_kv_store.key_set(bucket=self.bucket, scope=self.scope, collection=self.collection) self.num_valid_keys = len(self.src_valid_keys) self.num_deleted_keys = len(self.src_deleted_keys) self.keys_not_found = {self.client.rest.ip: [], self.client_dest.rest.ip: []} if max_verify: self.max_verify = max_verify else: self.max_verify = self.num_valid_keys + self.num_deleted_keys self.itr = 0 self.not_matching_filter_keys = 0 self.err_count = 0 self.max_err_count = max_err_count self.src_server = src_server self.bucket = bucket self.log.info(f"RevID verification: in progress for {self.bucket.name} in scope:{scope}" f" in collection: {collection}") def has_next(self): if self.itr < (self.num_valid_keys + self.num_deleted_keys) and \ self.err_count < self.max_err_count and \ self.itr < self.max_verify: return True self.log.info("RevId Verification : {0} existing items have been verified" .format(self.itr if self.itr < self.num_valid_keys else self.num_valid_keys)) self.log.info("RevId Verification : {0} deleted items have been verified" .format(self.itr - self.num_valid_keys if self.itr > self.num_valid_keys else 0)) self.log.info("RevId Verification : {0} keys were apparently filtered " "out and not found in target bucket" .format(self.not_matching_filter_keys)) # if there are missing keys, we would have printed them by now # check if excess keys are present on server, if yes, set an exception # TODO : print excess keys server = RestConnection(self.src_server) server_count = server.fetch_bucket_stats(bucket=self.bucket.name)["op"]["samples"]["curr_items"][-1] if server_count > self.num_valid_keys: self.set_exception(Exception("ERROR: {0} keys present on bucket {1} " "on {2} while kvstore expects only {3}" .format(server_count, self.bucket.name, self.src_server.ip, self.num_valid_keys))) return False def __next__(self): if self.itr < self.num_valid_keys: self._check_key_revId(self.src_valid_keys[self.itr], collection=self.collection) elif self.itr < (self.num_valid_keys + self.num_deleted_keys): # verify deleted/expired keys self._check_key_revId(self.src_deleted_keys[self.itr - self.num_valid_keys], ignore_meta_data=['expiration', 'cas'], collection=self.collection) self.itr += 1 # show progress of verification for every 50k items if math.fmod(self.itr, 50000) == 0.0: self.log.info("{0} items have been verified".format(self.itr)) def __get_meta_data(self, client, key, scope=None, collection=None): try: mc = client.memcached(key) meta_data = eval("{'deleted': %s, 'flags': %s, 'expiration': %s, 'seqno': %s, 'cas': %s}" % ( mc.getMeta(key, scope=scope, collection=collection))) return meta_data except MemcachedError as error: if error.status == ERR_NOT_FOUND: # if a filter was specified, the key will not be found in # target kv store if key did not match filter expression if key not in self.src_deleted_keys and key in (self.dest_valid_keys + self.dest_del_keys): self.err_count += 1 self.keys_not_found[client.rest.ip].append( ("key: %s" % key, "vbucket: %s" % client._get_vBucket_id(key, scope=scope, collection=collection))) else: self.not_matching_filter_keys += 1 else: self.state = FINISHED self.set_exception(error) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def _check_key_revId(self, key, ignore_meta_data=None, scope=None, collection=None): if ignore_meta_data is None: ignore_meta_data = [] src_meta_data = self.__get_meta_data(self.client_src, key, scope=scope, collection=collection) dest_meta_data = self.__get_meta_data(self.client_dest, key, scope=scope, collection=collection) if not src_meta_data or not dest_meta_data: return prev_error_count = self.err_count err_msg = [] # seqno number should never be zero if src_meta_data['seqno'] == 0: self.err_count += 1 err_msg.append( "seqno on Source should not be 0, Error Count:{0}".format(self.err_count)) if dest_meta_data['seqno'] == 0: self.err_count += 1 err_msg.append( "seqno on Destination should not be 0, Error Count:{0}".format(self.err_count)) # verify all metadata for meta_key in list(src_meta_data.keys()): check = True if meta_key == 'flags' and not CHECK_FLAG: check = False if check and src_meta_data[meta_key] != dest_meta_data[meta_key] and meta_key not in ignore_meta_data: self.err_count += 1 err_msg.append("{0} mismatch: Source {0}:{1}, Destination {0}:{2}, Error Count:{3}" .format(meta_key, src_meta_data[meta_key], dest_meta_data[meta_key], self.err_count)) if self.err_count - prev_error_count > 0 and self.err_count < 200: self.log.error("===== Verifying rev_ids failed for key: {0}, bucket:{1} =====".format(key, self.bucket)) [self.log.error(err) for err in err_msg] self.log.error("Source meta data: %s" % src_meta_data) self.log.error("Dest meta data: %s" % dest_meta_data) self.state = FINISHED class VerifyCollectionDocCountTask(Task): def __init__(self, src, dest, bucket, mapping): Task.__init__(self, "verify_collection_doc_count_task") self.src = src self.dest = dest self.bucket = bucket self.mapping = mapping self.src_conn = CollectionsStats(src.get_master_node()) self.dest_conn = CollectionsStats(dest.get_master_node()) self.src_stats = self.src_conn.get_collection_stats(self.bucket)[0] self.dest_stats = self.dest_conn.get_collection_stats(self.bucket)[0] def execute(self, task_manager): try: for map_exp in self.mapping.items(): if ':' in map_exp[0]: src_scope = map_exp[0].split(':')[0] src_collection = map_exp[0].split(':')[1] src_count = self.src_conn.get_collection_item_count(self.bucket, src_scope, src_collection, self.src.get_nodes(), self.src_stats) else: src_scope = map_exp[0] src_collection = "all" src_count = self.src_conn.get_scope_item_count(self.bucket, src_scope, self.src.get_nodes(), self.src_stats) if map_exp[1]: if map_exp[1].lower() == "null": self.log.info("{} mapped to null, skipping doc count verification" .format()) dest_collection_specified = False if ':' in map_exp[1]: dest_collection_specified = True dest_scope = map_exp[1].split(':')[0] dest_collection = map_exp[1].split(':')[1] elif "colon" in map_exp[1]: dest_collection_specified = True dest_scope = map_exp[1].split("colon")[0] dest_collection = map_exp[1].split("colon")[1] if dest_collection_specified: dest_count = self.dest_conn.get_collection_item_count(self.bucket, dest_scope, dest_collection, self.dest.get_nodes(), self.dest_stats) else: dest_scope = map_exp[1] dest_collection = "all" dest_count = self.dest_conn.get_scope_item_count(self.bucket, dest_scope, self.dest.get_nodes(), self.dest_stats) self.log.info('-' * 100) if src_count == dest_count: self.log.info("Item count on src:{} {} = {} on dest:{} for " "bucket {} \nsrc : scope {}-> collection {}," "dest: scope {}-> collection {}" .format(self.src.get_master_node().ip, src_count, dest_count, self.dest.get_master_node().ip, self.bucket, src_scope, src_collection, dest_scope, dest_collection)) else: self.set_exception(Exception("ERROR: Item count on src:{} {} != {} on dest:{} for " "bucket {} \nsrc : scope {}-> collection {}," "dest: scope {}-> collection {}" .format(self.src.get_master_node().ip, src_count, dest_count, self.dest.get_master_node().ip, self.bucket, src_scope, src_collection, dest_scope, dest_collection))) self.log.info('-' * 100) except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) self.check(task_manager) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) class VerifyMetaDataTask(GenericLoadingTask): def __init__(self, dest_server, bucket, kv_store, meta_data_store, max_err_count=100, compression=True, scope=None, collection=None): GenericLoadingTask.__init__(self, dest_server, bucket, kv_store, compression=compression, scope=scope, collection=collection) from memcached.helper.data_helper import VBucketAwareMemcached as SmartClient self.collections = collection self.scope = scope self.client = SmartClient(RestConnection(dest_server), bucket) self.valid_keys, self.deleted_keys = kv_store.key_set(bucket=self.bucket, scope=self.scope, collection=self.collection) self.num_valid_keys = len(self.valid_keys) self.num_deleted_keys = len(self.deleted_keys) self.keys_not_found = {self.client.rest.ip: [], self.client.rest.ip: []} self.itr = 0 self.err_count = 0 self.max_err_count = max_err_count self.meta_data_store = meta_data_store def has_next(self): if self.itr < (self.num_valid_keys + self.num_deleted_keys) and self.err_count < self.max_err_count: return True self.log.info("Meta Data Verification : {0} existing items have been verified" .format(self.itr if self.itr < self.num_valid_keys else self.num_valid_keys)) self.log.info("Meta Data Verification : {0} deleted items have been verified" .format(self.itr - self.num_valid_keys if self.itr > self.num_valid_keys else 0)) return False def __next__(self): if self.itr < self.num_valid_keys: self._check_key_meta_data(self.valid_keys[self.itr], self.collections) elif self.itr < (self.num_valid_keys + self.num_deleted_keys): # verify deleted/expired keys self._check_key_meta_data(self.deleted_keys[self.itr - self.num_valid_keys], ignore_meta_data=['expiration'], scope=self.scope, collection=self.collections) self.itr += 1 # show progress of verification for every 50k items if math.fmod(self.itr, 50000) == 0.0: self.log.info("{0} items have been verified".format(self.itr)) def __get_meta_data(self, client, key, scope=None, collection=None): try: mc = client.memcached(key) meta_data = eval("{'deleted': %s, 'flags': %s, 'expiration': %s, 'seqno': %s, 'cas': %s}" % ( mc.getMeta(key, scope=scope, collection=collection))) return meta_data except MemcachedError as error: if error.status == ERR_NOT_FOUND: if key not in self.deleted_keys: self.err_count += 1 self.keys_not_found[client.rest.ip].append( ("key: %s" % key, "vbucket: %s" % client._get_vBucket_id(key))) else: self.state = FINISHED self.set_exception(error) def _check_key_meta_data(self, key, ignore_meta_data=[], scope=None, collection=None): src_meta_data = self.meta_data_store[key] dest_meta_data = self.__get_meta_data(self.client, key, scope=scope, collection=collection) if not src_meta_data or not dest_meta_data: return prev_error_count = self.err_count err_msg = [] # seqno number should never be zero if dest_meta_data['seqno'] == 0: self.err_count += 1 err_msg.append( "seqno on Destination should not be 0, Error Count:{0}".format(self.err_count)) # verify all metadata for meta_key in list(src_meta_data.keys()): if src_meta_data[meta_key] != dest_meta_data[meta_key] and meta_key not in ignore_meta_data: self.err_count += 1 err_msg.append("{0} mismatch: Source {0}:{1}, Destination {0}:{2}, Error Count:{3}" .format(meta_key, src_meta_data[meta_key], dest_meta_data[meta_key], self.err_count)) if self.err_count - prev_error_count > 0: self.log.error("===== Verifying meta data failed for key: {0} =====".format(key)) [self.log.error(err) for err in err_msg] self.log.error("Source meta data: %s" % src_meta_data) self.log.error("Dest meta data: %s" % dest_meta_data) self.state = FINISHED class GetMetaDataTask(GenericLoadingTask): def __init__(self, dest_server, bucket, kv_store, compression=True, scope=None, collection=None): GenericLoadingTask.__init__(self, dest_server, bucket, kv_store, compression=compression, scope=scope, collection=collection) from memcached.helper.data_helper import VBucketAwareMemcached as SmartClient self.collection = collection self.scope = scope self.client = SmartClient(RestConnection(dest_server), bucket) self.valid_keys, self.deleted_keys = kv_store.key_set(bucket=self.bucket, scope=self.scope, collection=self.collection) self.num_valid_keys = len(self.valid_keys) self.num_deleted_keys = len(self.deleted_keys) self.keys_not_found = {self.client.rest.ip: [], self.client.rest.ip: []} self.itr = 0 self.err_count = 0 self.max_err_count = 100 self.meta_data_store = {} def has_next(self): if self.itr < (self.num_valid_keys + self.num_deleted_keys) and self.err_count < self.max_err_count: return True self.log.info("Get Meta Data : {0} existing items have been gathered" .format(self.itr if self.itr < self.num_valid_keys else self.num_valid_keys)) self.log.info("Get Meta Data : {0} deleted items have been gathered" .format(self.itr - self.num_valid_keys if self.itr > self.num_valid_keys else 0)) return False def __next__(self): if self.itr < self.num_valid_keys: self.meta_data_store[self.valid_keys[self.itr]] = self.__get_meta_data(self.client, self.valid_keys[self.itr], self.scope, self.collection) elif self.itr < (self.num_valid_keys + self.num_deleted_keys): self.meta_data_store[self.deleted_keys[self.itr - self.num_valid_keys]] = self.__get_meta_data(self.client, self.deleted_keys[ self.itr - self.num_valid_keys], scope=self.scope, collection=self.collection) self.itr += 1 def __get_meta_data(self, client, key, scope=None, collection=None): try: mc = client.memcached(key) meta_data = eval("{'deleted': %s, 'flags': %s, 'expiration': %s, 'seqno': %s, 'cas': %s}" % ( mc.getMeta(key, scope=scope, collection=collection))) return meta_data except MemcachedError as error: if error.status == ERR_NOT_FOUND: if key not in self.deleted_keys: self.err_count += 1 self.keys_not_found[client.rest.ip].append( ("key: %s" % key, "vbucket: %s" % client._get_vBucket_id(key))) else: self.state = FINISHED self.set_exception(error) def get_meta_data_store(self): return self.meta_data_store class ViewCreateTask(Task): def __init__(self, server, design_doc_name, view, bucket="default", with_query=True, check_replication=False, ddoc_options=None): Task.__init__(self, "create_view_task") self.server = server self.bucket = bucket self.view = view prefix = "" if self.view: prefix = ("", "dev_")[self.view.dev_view] if design_doc_name.find('/') != -1: design_doc_name = design_doc_name.replace('/', '%2f') self.design_doc_name = prefix + design_doc_name self.ddoc_rev_no = 0 self.with_query = with_query self.check_replication = check_replication self.ddoc_options = ddoc_options self.rest = RestConnection(self.server) def execute(self, task_manager): try: # appending view to existing design doc content, meta = self.rest.get_ddoc(self.bucket, self.design_doc_name) ddoc = DesignDocument._init_from_json(self.design_doc_name, content) # if view is to be updated if self.view: if self.view.is_spatial: ddoc.add_spatial_view(self.view) else: ddoc.add_view(self.view) self.ddoc_rev_no = self._parse_revision(meta['rev']) except ReadDocumentException: # creating first view in design doc if self.view: if self.view.is_spatial: ddoc = DesignDocument(self.design_doc_name, [], spatial_views=[self.view]) else: ddoc = DesignDocument(self.design_doc_name, [self.view]) # create an empty design doc else: ddoc = DesignDocument(self.design_doc_name, []) if self.ddoc_options: ddoc.options = self.ddoc_options # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) try: self.rest.create_design_document(self.bucket, ddoc) self.state = CHECKING task_manager.schedule(self) except DesignDocCreationException as e: self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): try: # only query if the DDoc has a view if self.view: if self.with_query: query = {"stale": "ok"} if self.view.is_spatial: content = \ self.rest.query_view(self.design_doc_name, self.view.name, self.bucket, query, type="spatial") else: content = \ self.rest.query_view(self.design_doc_name, self.view.name, self.bucket, query) else: _, json_parsed, _ = self.rest._get_design_doc(self.bucket, self.design_doc_name) if self.view.is_spatial: if self.view.name not in list(json_parsed["spatial"].keys()): self.set_exception( Exception("design doc {O} doesn't contain spatial view {1}".format( self.design_doc_name, self.view.name))) else: if self.view.name not in list(json_parsed["views"].keys()): self.set_exception(Exception("design doc {O} doesn't contain view {1}".format( self.design_doc_name, self.view.name))) self.log.info( "view : {0} was created successfully in ddoc: {1}".format(self.view.name, self.design_doc_name)) else: # if we have reached here, it means design doc was successfully updated self.log.info("Design Document : {0} was updated successfully".format(self.design_doc_name)) self.state = FINISHED if self._check_ddoc_revision(): self.set_result(self.ddoc_rev_no) else: self.set_exception(Exception("failed to update design document")) if self.check_replication: self._check_ddoc_replication_on_nodes() except QueryViewException as e: if str(e).find('not_found') or str(e).find('view_undefined') > -1: task_manager.schedule(self, 2) else: self.state = FINISHED self.set_unexpected_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def _check_ddoc_revision(self): valid = False try: content, meta = self.rest.get_ddoc(self.bucket, self.design_doc_name) new_rev_id = self._parse_revision(meta['rev']) if new_rev_id != self.ddoc_rev_no: self.ddoc_rev_no = new_rev_id valid = True except ReadDocumentException: pass # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) return valid def _parse_revision(self, rev_string): return int(rev_string.split('-')[0]) def _check_ddoc_replication_on_nodes(self): nodes = self.rest.node_statuses() retry_count = 3 # nothing to check if there is only 1 node if len(nodes) <= 1: return for node in nodes: server_info = {"ip": node.ip, "port": node.port, "username": self.rest.username, "password": self.rest.password} for count in range(retry_count): try: rest_node = RestConnection(server_info) content, meta = rest_node.get_ddoc(self.bucket, self.design_doc_name) new_rev_id = self._parse_revision(meta['rev']) if new_rev_id == self.ddoc_rev_no: break else: self.log.info("Design Doc {0} version is not updated on node {1}:{2}. Retrying.".format( self.design_doc_name, node.ip, node.port)) time.sleep(2) except ReadDocumentException as e: if (count < retry_count): self.log.info( "Design Doc {0} not yet available on node {1}:{2}. Retrying.".format(self.design_doc_name, node.ip, node.port)) time.sleep(2) else: self.log.error( "Design Doc {0} failed to replicate on node {1}:{2}".format(self.design_doc_name, node.ip, node.port)) self.set_exception(e) self.state = FINISHED break except Exception as e: if (count < retry_count): self.log.info("Unexpected Exception Caught. Retrying.") time.sleep(2) else: self.set_unexpected_exception(e) self.state = FINISHED break else: self.set_exception(Exception( "Design Doc {0} version mismatch on node {1}:{2}".format(self.design_doc_name, node.ip, node.port))) class ViewDeleteTask(Task): def __init__(self, server, design_doc_name, view, bucket="default"): Task.__init__(self, "delete_view_task") self.server = server self.bucket = bucket self.view = view prefix = "" if self.view: prefix = ("", "dev_")[self.view.dev_view] self.design_doc_name = prefix + design_doc_name def execute(self, task_manager): try: rest = RestConnection(self.server) if self.view: # remove view from existing design doc content, header = rest.get_ddoc(self.bucket, self.design_doc_name) ddoc = DesignDocument._init_from_json(self.design_doc_name, content) if self.view.is_spatial: status = ddoc.delete_spatial(self.view) else: status = ddoc.delete_view(self.view) if not status: self.state = FINISHED self.set_exception(Exception('View does not exist! %s' % (self.view.name))) # update design doc rest.create_design_document(self.bucket, ddoc) self.state = CHECKING task_manager.schedule(self, 2) else: # delete the design doc rest.delete_view(self.bucket, self.design_doc_name) self.log.info("Design Doc : {0} was successfully deleted".format(self.design_doc_name)) self.state = FINISHED self.set_result(True) except (ValueError, ReadDocumentException, DesignDocCreationException) as e: self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): try: rest = RestConnection(self.server) # make sure view was deleted query = {"stale": "ok"} content = \ rest.query_view(self.design_doc_name, self.view.name, self.bucket, query) self.state = FINISHED self.set_result(False) except QueryViewException as e: self.log.info( "view : {0} was successfully deleted in ddoc: {1}".format(self.view.name, self.design_doc_name)) self.state = FINISHED self.set_result(True) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) class ViewQueryTask(Task): def __init__(self, server, design_doc_name, view_name, query, expected_rows=None, bucket="default", retry_time=2): Task.__init__(self, "query_view_task") self.server = server self.bucket = bucket self.view_name = view_name self.design_doc_name = design_doc_name self.query = query self.expected_rows = expected_rows self.retry_time = retry_time self.timeout = 900 def execute(self, task_manager): try: rest = RestConnection(self.server) # make sure view can be queried content = \ rest.query_view(self.design_doc_name, self.view_name, self.bucket, self.query, self.timeout) if self.expected_rows is None: # no verification self.state = FINISHED self.set_result(content) else: self.state = CHECKING task_manager.schedule(self) except QueryViewException as e: # initial query failed, try again task_manager.schedule(self, self.retry_time) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): try: rest = RestConnection(self.server) # query and verify expected num of rows returned content = \ rest.query_view(self.design_doc_name, self.view_name, self.bucket, self.query, self.timeout) self.log.info("Server: %s, Design Doc: %s, View: %s, (%d rows) expected, (%d rows) returned" % \ (self.server.ip, self.design_doc_name, self.view_name, self.expected_rows, len(content['rows']))) raised_error = content.get('error', '') or ''.join([str(item) for item in content.get('errors', [])]) if raised_error: raise QueryViewException(self.view_name, raised_error) if len(content['rows']) == self.expected_rows: self.log.info("expected number of rows: '{0}' was found for view query".format(self. expected_rows)) self.state = FINISHED self.set_result(True) else: if len(content['rows']) > self.expected_rows: raise QueryViewException(self.view_name, "Server: {0}, Design Doc: {1}, actual returned rows: '{2}' are greater than expected {3}" .format(self.server.ip, self.design_doc_name, len(content['rows']), self.expected_rows, )) if "stale" in self.query: if self.query["stale"].lower() == "false": self.state = FINISHED self.set_result(False) # retry until expected results or task times out task_manager.schedule(self, self.retry_time) except QueryViewException as e: # subsequent query failed! exit self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) class N1QLQueryTask(Task): def __init__(self, server, bucket, query, n1ql_helper=None, expected_result=None, verify_results=True, is_explain_query=False, index_name=None, retry_time=2, scan_consistency=None, scan_vector=None): Task.__init__(self, "query_n1ql_task") self.server = server self.bucket = bucket self.query = query self.expected_result = expected_result self.n1ql_helper = n1ql_helper self.timeout = 900 self.verify_results = verify_results self.is_explain_query = is_explain_query self.index_name = index_name self.retry_time = 2 self.scan_consistency = scan_consistency self.scan_vector = scan_vector def execute(self, task_manager): try: # Query and get results self.log.info(" <<<<< START Executing Query {0} >>>>>>".format(self.query)) if not self.is_explain_query: self.msg, self.isSuccess = self.n1ql_helper.run_query_and_verify_result( query=self.query, server=self.server, expected_result=self.expected_result, scan_consistency=self.scan_consistency, scan_vector=self.scan_vector, verify_results=self.verify_results) else: self.actual_result = self.n1ql_helper.run_cbq_query(query=self.query, server=self.server, scan_consistency=self.scan_consistency, scan_vector=self.scan_vector) self.log.info(self.actual_result) self.log.info(" <<<<< Done Executing Query {0} >>>>>>".format(self.query)) self.state = CHECKING task_manager.schedule(self) except N1QLQueryException as e: self.state = FINISHED # initial query failed, try again task_manager.schedule(self, self.retry_time) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): try: # Verify correctness of result set if self.verify_results: if not self.is_explain_query: if not self.isSuccess: self.log.info(" Query {0} results leads to INCORRECT RESULT ".format(self.query)) raise N1QLQueryException(self.msg) else: check = self.n1ql_helper.verify_index_with_explain(self.actual_result, self.index_name) if not check: actual_result = self.n1ql_helper.run_cbq_query(query="select * from system:indexes", server=self.server) self.log.info(actual_result) raise Exception( " INDEX usage in Query {0} :: NOT FOUND {1} :: as observed in result {2}".format( self.query, self.index_name, self.actual_result)) self.log.info(" <<<<< Done VERIFYING Query {0} >>>>>>".format(self.query)) self.set_result(True) self.state = FINISHED except N1QLQueryException as e: # subsequent query failed! exit self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) class CreateIndexTask(Task): def __init__(self, server, bucket, index_name, query, n1ql_helper=None, retry_time=2, defer_build=False, timeout=240): Task.__init__(self, "create_index_task") self.server = server self.bucket = bucket self.defer_build = defer_build self.query = query self.index_name = index_name self.n1ql_helper = n1ql_helper self.retry_time = 2 self.timeout = timeout def execute(self, task_manager): try: # Query and get results self.n1ql_helper.run_cbq_query(query=self.query, server=self.server) self.state = CHECKING task_manager.schedule(self) except CreateIndexException as e: # initial query failed, try again self.state = FINISHED task_manager.schedule(self, self.retry_time) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.log.error(e) self.set_exception(e) #if not "will retry building in the background for reason" in e: # self.log.error(e) # self.set_exception(e) def check(self, task_manager): try: # Verify correctness of result set check = True if not self.defer_build: check = self.n1ql_helper.is_index_online_and_in_list(self.bucket, self.index_name, server=self.server, timeout=self.timeout) if not check: raise CreateIndexException("Index {0} not created as expected ".format(self.index_name)) self.set_result(True) self.state = FINISHED except CreateIndexException as e: # subsequent query failed! exit self.state = FINISHED self.log.error(e) self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.log.error(e) self.set_exception(e) class BuildIndexTask(Task): def __init__(self, server, bucket, query, n1ql_helper=None, retry_time=2): Task.__init__(self, "build_index_task") self.server = server self.bucket = bucket self.query = query self.n1ql_helper = n1ql_helper self.retry_time = 2 def execute(self, task_manager): try: # Query and get results self.n1ql_helper.run_cbq_query(query=self.query, server=self.server) self.state = CHECKING task_manager.schedule(self) except CreateIndexException as e: # initial query failed, try again self.state = FINISHED task_manager.schedule(self, self.retry_time) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): try: # Verify correctness of result set self.set_result(True) self.state = FINISHED except CreateIndexException as e: # subsequent query failed! exit self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) class MonitorIndexTask(Task): def __init__(self, server, bucket, index_name, n1ql_helper=None, retry_time=2, timeout=240): Task.__init__(self, "build_index_task") self.server = server self.bucket = bucket self.index_name = index_name self.n1ql_helper = n1ql_helper self.retry_time = 2 self.timeout = timeout def execute(self, task_manager): try: check = self.n1ql_helper.is_index_online_and_in_list(self.bucket, self.index_name, server=self.server, timeout=self.timeout) if not check: self.state = FINISHED raise CreateIndexException("Index {0} not created as expected ".format(self.index_name)) self.state = CHECKING task_manager.schedule(self) except CreateIndexException as e: # initial query failed, try again self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): try: self.set_result(True) self.state = FINISHED except CreateIndexException as e: # subsequent query failed! exit self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) class DropIndexTask(Task): def __init__(self, server, bucket, index_name, query, n1ql_helper=None, retry_time=2): Task.__init__(self, "drop_index_task") self.server = server self.bucket = bucket self.query = query self.index_name = index_name self.n1ql_helper = n1ql_helper self.timeout = 900 self.retry_time = 2 def execute(self, task_manager): try: # Query and get results check = self.n1ql_helper._is_index_in_list(self.bucket, self.index_name, server=self.server) if not check: raise DropIndexException("index {0} does not exist will not drop".format(self.index_name)) self.n1ql_helper.run_cbq_query(query=self.query, server=self.server) self.state = CHECKING task_manager.schedule(self) except N1QLQueryException as e: # initial query failed, try again self.state = FINISHED task_manager.schedule(self, self.retry_time) # catch and set all unexpected exceptions except DropIndexException as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): try: # Verify correctness of result set check = self.n1ql_helper._is_index_in_list(self.bucket, self.index_name, server=self.server) if check: raise Exception("Index {0} not dropped as expected ".format(self.index_name)) self.set_result(True) self.state = FINISHED except DropIndexException as e: # subsequent query failed! exit self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) class MonitorViewQueryResultsTask(Task): def __init__(self, servers, design_doc_name, view, query, expected_docs=None, bucket="default", retries=100, error=None, verify_rows=False, server_to_query=0): Task.__init__(self, "query_view_task") self.servers = servers self.bucket = bucket self.view_name = view.name self.view = view self.design_doc_name = design_doc_name self.query = query self.retries = retries self.current_retry = 0 self.timeout = 900 self.error = error self.expected_docs = expected_docs self.verify_rows = verify_rows self.rest = RestConnection(self.servers[server_to_query]) self.results = None self.connection_timeout = 60000 self.query["connection_timeout"] = self.connection_timeout if self.design_doc_name.find("dev_") == 0: self.query["full_set"] = "true" def execute(self, task_manager): try: self.current_retry += 1 self.results = self.rest.query_view( self.design_doc_name, self.view_name, self.bucket, self.query, self.timeout) raised_error = self.results.get('error', '') or ''.join( [str(item) for item in self.results.get('errors', [])]) if raised_error: raise QueryViewException(self.view_name, raised_error) else: self.log.info("view %s, query %s: expected- %s, actual -%s" % ( self.design_doc_name, self.query, len(self.expected_docs), len(self.results.get('rows', [])))) self.state = CHECKING task_manager.schedule(self) except QueryViewException as ex: self.log.error("During query run (ddoc=%s, query=%s, server=%s) error is: %s" % ( self.design_doc_name, self.query, self.servers[0].ip, str(ex))) if self.error and str(ex).find(self.error) != -1: self.state = FINISHED self.set_result({"passed": True, "errors": str(ex)}) elif self.current_retry == self.retries: self.state = FINISHED self.set_result({"passed": False, "errors": str(ex)}) elif str(ex).find('view_undefined') != -1 or \ str(ex).find('not_found') != -1 or \ str(ex).find('unable to reach') != -1 or \ str(ex).find('socket error') != -1 or \ str(ex).find('econnrefused') != -1 or \ str(ex).find("doesn't exist") != -1 or \ str(ex).find('missing') != -1 or \ str(ex).find("Undefined set view") != -1: self.log.error( "view_results not ready yet ddoc=%s , try again in 10 seconds..." % self.design_doc_name) task_manager.schedule(self, 10) elif str(ex).find('timeout') != -1: self.connection_timeout = self.connection_timeout * 2 self.log.error("view_results not ready yet ddoc=%s ," % self.design_doc_name + \ " try again in 10 seconds... and double timeout") task_manager.schedule(self, 10) else: self.state = FINISHED res = {"passed": False, "errors": str(ex)} if self.results and self.results.get('rows', []): res['results'] = self.results self.set_result(res) except Exception as ex: if self.current_retry == self.retries: self.state = CHECKING self.log.error("view %s, query %s: verifying results" % ( self.design_doc_name, self.query)) task_manager.schedule(self) else: self.log.error( "view_results not ready yet ddoc=%s , try again in 10 seconds..." % self.design_doc_name) task_manager.schedule(self, 10) def check(self, task_manager): try: if self.view.red_func and (('reduce' in self.query and \ self.query['reduce'] == "true") or (not 'reduce' in self.query)): if len(self.expected_docs) != len(self.results.get('rows', [])): if self.current_retry == self.retries: self.state = FINISHED msg = "ddoc=%s, query=%s, server=%s" % ( self.design_doc_name, self.query, self.servers[0].ip) msg += "Number of groups expected:%s, actual:%s" % ( len(self.expected_docs), len(self.results.get('rows', []))) self.set_result({"passed": False, "errors": msg}) else: RestHelper(self.rest)._wait_for_indexer_ddoc(self.servers, self.design_doc_name) self.state = EXECUTING task_manager.schedule(self, 10) else: for row in self.expected_docs: key_expected = row['key'] if not (key_expected in [key['key'] for key in self.results.get('rows', [])]): if self.current_retry == self.retries: self.state = FINISHED msg = "ddoc=%s, query=%s, server=%s" % ( self.design_doc_name, self.query, self.servers[0].ip) msg += "Key expected but not present :%s" % (key_expected) self.set_result({"passed": False, "errors": msg}) else: RestHelper(self.rest)._wait_for_indexer_ddoc(self.servers, self.design_doc_name) self.state = EXECUTING task_manager.schedule(self, 10) else: for res in self.results.get('rows', []): if key_expected == res['key']: value = res['value'] break msg = "ddoc=%s, query=%s, server=%s\n" % ( self.design_doc_name, self.query, self.servers[0].ip) msg += "Key %s: expected value %s, actual: %s" % ( key_expected, row['value'], value) self.log.info(msg) if row['value'] == value: self.state = FINISHED self.log.info(msg) self.set_result({"passed": True, "errors": []}) else: if self.current_retry == self.retries: self.state = FINISHED self.log.error(msg) self.set_result({"passed": True, "errors": msg}) else: RestHelper(self.rest)._wait_for_indexer_ddoc(self.servers, self.design_doc_name) self.state = EXECUTING task_manager.schedule(self, 10) return if len(self.expected_docs) > len(self.results.get('rows', [])): if self.current_retry == self.retries: self.state = FINISHED self.set_result({"passed": False, "errors": [], "results": self.results}) else: RestHelper(self.rest)._wait_for_indexer_ddoc(self.servers, self.design_doc_name) if self.current_retry == 70: self.query["stale"] = 'false' self.log.info( "View result is still not expected (ddoc=%s, query=%s, server=%s). retry in 10 sec" % ( self.design_doc_name, self.query, self.servers[0].ip)) self.state = EXECUTING task_manager.schedule(self, 10) elif len(self.expected_docs) < len(self.results.get('rows', [])): self.state = FINISHED self.set_result({"passed": False, "errors": [], "results": self.results}) elif len(self.expected_docs) == len(self.results.get('rows', [])): if self.verify_rows: expected_ids = [row['id'] for row in self.expected_docs] rows_ids = [str(row['id']) for row in self.results['rows']] if expected_ids == rows_ids: self.state = FINISHED self.set_result({"passed": True, "errors": []}) else: if self.current_retry == self.retries: self.state = FINISHED self.set_result({"passed": False, "errors": [], "results": self.results}) else: self.state = EXECUTING task_manager.schedule(self, 10) else: self.state = FINISHED self.set_result({"passed": True, "errors": []}) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.log.error("Exception caught %s" % str(e)) self.set_exception(e) self.set_result({"passed": False, "errors": str(e)}) class ModifyFragmentationConfigTask(Task): """ Given a config dictionary attempt to configure fragmentation settings. This task will override the default settings that are provided for a given <bucket>. """ def __init__(self, server, config=None, bucket="default"): Task.__init__(self, "modify_frag_config_task") self.server = server self.config = {"parallelDBAndVC": "false", "dbFragmentThreshold": None, "viewFragmntThreshold": None, "dbFragmentThresholdPercentage": 100, "viewFragmntThresholdPercentage": 100, "allowedTimePeriodFromHour": None, "allowedTimePeriodFromMin": None, "allowedTimePeriodToHour": None, "allowedTimePeriodToMin": None, "allowedTimePeriodAbort": None, "autoCompactionDefined": "true"} self.bucket = bucket for key in config: self.config[key] = config[key] def execute(self, task_manager): try: rest = RestConnection(self.server) rest.set_auto_compaction(parallelDBAndVC=self.config["parallelDBAndVC"], dbFragmentThreshold=self.config["dbFragmentThreshold"], viewFragmntThreshold=self.config["viewFragmntThreshold"], dbFragmentThresholdPercentage=self.config["dbFragmentThresholdPercentage"], viewFragmntThresholdPercentage=self.config["viewFragmntThresholdPercentage"], allowedTimePeriodFromHour=self.config["allowedTimePeriodFromHour"], allowedTimePeriodFromMin=self.config["allowedTimePeriodFromMin"], allowedTimePeriodToHour=self.config["allowedTimePeriodToHour"], allowedTimePeriodToMin=self.config["allowedTimePeriodToMin"], allowedTimePeriodAbort=self.config["allowedTimePeriodAbort"], bucket=self.bucket) self.state = CHECKING task_manager.schedule(self, 10) except Exception as e: self.state = FINISHED self.set_exception(e) def check(self, task_manager): try: rest = RestConnection(self.server) # verify server accepted settings content = rest.get_bucket_json(self.bucket) if content["autoCompactionSettings"] == False: self.set_exception(Exception("Failed to set auto compaction settings")) else: # retrieved compaction settings self.set_result(True) self.state = FINISHED except GetBucketInfoFailed as e: # subsequent query failed! exit self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) class MonitorActiveTask(Task): """ Attempt to monitor active task that is available in _active_tasks API. It allows to monitor indexer, bucket compaction. Execute function looks at _active_tasks API and tries to identifies task for monitoring and its pid by: task type('indexer' , 'bucket_compaction', 'view_compaction' ) and target value (for example "_design/ddoc" for indexing, bucket "default" for bucket compaction or "_design/dev_view" for view compaction). wait_task=True means that task should be found in the first attempt otherwise, we can assume that the task has been completed( reached 100%). Check function monitors task by pid that was identified in execute func and matches new progress result with the previous. task is failed if: progress is not changed during num_iterations iteration new progress was gotten less then previous task is passed and completed if: progress reached wait_progress value task was not found by pid(believe that it's over) """ def __init__(self, server, type, target_value, wait_progress=100, num_iterations=100, wait_task=True): Task.__init__(self, "monitor_active_task") self.server = server self.type = type # indexer or bucket_compaction self.target_key = "" if self.type == 'indexer': pass # no special actions elif self.type == "bucket_compaction": self.target_key = "original_target" elif self.type == "view_compaction": self.target_key = "designDocument" else: raise Exception("type %s is not defined!" % self.type) self.target_value = target_value self.wait_progress = wait_progress self.num_iterations = num_iterations self.wait_task = wait_task self.rest = RestConnection(self.server) self.current_progress = None self.current_iter = 0 self.task = None def execute(self, task_manager): tasks = self.rest.active_tasks() for task in tasks: if task["type"] == self.type and (( self.target_key == "designDocument" and task[ self.target_key] == self.target_value) or ( self.target_key == "original_target" and task[self.target_key][ "type"] == self.target_value) or ( self.type == 'indexer')): self.current_progress = task["progress"] self.task = task self.log.info("monitoring active task was found:" + str(task)) self.log.info("progress %s:%s - %s %%" % (self.type, self.target_value, task["progress"])) if self.current_progress >= self.wait_progress: self.log.info("expected progress was gotten: %s" % self.current_progress) self.state = FINISHED self.set_result(True) else: self.state = CHECKING task_manager.schedule(self, 5) return if self.wait_task: # task is not performed self.state = FINISHED self.log.error("expected active task %s:%s was not found" % (self.type, self.target_value)) self.set_result(False) else: # task was completed self.state = FINISHED self.log.info("task for monitoring %s:%s completed" % (self.type, self.target_value)) self.set_result(True) def check(self, task_manager): tasks = self.rest.active_tasks() for task in tasks: # if task still exists if task == self.task: self.log.info("progress %s:%s - %s %%" % (self.type, self.target_value, task["progress"])) # reached expected progress if task["progress"] >= self.wait_progress: self.state = FINISHED self.log.error("progress was reached %s" % self.wait_progress) self.set_result(True) # progress value was changed if task["progress"] > self.current_progress: self.current_progress = task["progress"] self.currebt_iter = 0 task_manager.schedule(self, 2) # progress value was not changed elif task["progress"] == self.current_progress: if self.current_iter < self.num_iterations: time.sleep(2) self.current_iter += 1 task_manager.schedule(self, 2) # num iteration with the same progress = num_iterations else: self.state = FINISHED self.log.error( "progress for active task was not changed during %s sec" % 2 * self.num_iterations) self.set_result(False) else: self.state = FINISHED self.log.error("progress for task %s:%s changed direction!" % (self.type, self.target_value)) self.set_result(False) # task was completed self.state = FINISHED self.log.info("task %s:%s was completed" % (self.type, self.target_value)) self.set_result(True) class MonitorViewFragmentationTask(Task): """ Attempt to monitor fragmentation that is occurring for a given design_doc. execute stage is just for preliminary sanity checking of values and environment. Check function looks at index file accross all nodes and attempts to calculate total fragmentation occurring by the views within the design_doc. Note: If autocompaction is enabled and user attempts to monitor for fragmentation value higher than level at which auto_compaction kicks in a warning is sent and it is best user to use lower value as this can lead to infinite monitoring. """ def __init__(self, server, design_doc_name, fragmentation_value=10, bucket="default"): Task.__init__(self, "monitor_frag_task") self.server = server self.bucket = bucket self.fragmentation_value = fragmentation_value self.design_doc_name = design_doc_name def execute(self, task_manager): # sanity check of fragmentation value if self.fragmentation_value < 0 or self.fragmentation_value > 100: err_msg = \ "Invalid value for fragmentation %d" % self.fragmentation_value self.state = FINISHED self.set_exception(Exception(err_msg)) # warning if autocompaction is less than <fragmentation_value> try: auto_compact_percentage = self._get_current_auto_compaction_percentage() if auto_compact_percentage != "undefined" and auto_compact_percentage < self.fragmentation_value: self.log.warning("Auto compaction is set to %s. Therefore fragmentation_value %s may not be reached" % ( auto_compact_percentage, self.fragmentation_value)) self.state = CHECKING task_manager.schedule(self, 5) except GetBucketInfoFailed as e: self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def _get_current_auto_compaction_percentage(self): """ check at bucket level and cluster level for compaction percentage """ auto_compact_percentage = None rest = RestConnection(self.server) content = rest.get_bucket_json(self.bucket) if content["autoCompactionSettings"] == False: # try to read cluster level compaction settings content = rest.cluster_status() auto_compact_percentage = \ content["autoCompactionSettings"]["viewFragmentationThreshold"]["percentage"] return auto_compact_percentage def check(self, task_manager): rest = RestConnection(self.server) new_frag_value = MonitorViewFragmentationTask. \ calc_ddoc_fragmentation(rest, self.design_doc_name, bucket=self.bucket) self.log.info("%s: current amount of fragmentation = %d" % (self.design_doc_name, new_frag_value)) if new_frag_value > self.fragmentation_value: self.state = FINISHED self.set_result(True) else: # try again task_manager.schedule(self, 2) @staticmethod def aggregate_ddoc_info(rest, design_doc_name, bucket="default", with_rebalance=False): nodes = rest.node_statuses() info = [] for node in nodes: server_info = {"ip": node.ip, "port": node.port, "username": rest.username, "password": rest.password} rest = RestConnection(server_info) status = False try: status, content = rest.set_view_info(bucket, design_doc_name) except Exception as e: print((str(e))) if "Error occured reading set_view _info" in str(e) and with_rebalance: print(("node {0} {1} is not ready yet?: {2}".format( node.id, node.port, str(e)))) else: raise e if status: info.append(content) return info @staticmethod def calc_ddoc_fragmentation(rest, design_doc_name, bucket="default", with_rebalance=False): total_disk_size = 0 total_data_size = 0 total_fragmentation = 0 nodes_ddoc_info = \ MonitorViewFragmentationTask.aggregate_ddoc_info(rest, design_doc_name, bucket, with_rebalance) total_disk_size = sum([content['disk_size'] for content in nodes_ddoc_info]) total_data_size = sum([content['data_size'] for content in nodes_ddoc_info]) if total_disk_size > 0 and total_data_size > 0: total_fragmentation = \ (total_disk_size - total_data_size) / float(total_disk_size) * 100 return total_fragmentation class ViewCompactionTask(Task): """ Executes view compaction for a given design doc. This is technicially view compaction as represented by the api and also because the fragmentation is generated by the keys emitted by map/reduce functions within views. Task will check that compaction history for design doc is incremented and if any work was really done. """ def __init__(self, server, design_doc_name, bucket="default", with_rebalance=False): Task.__init__(self, "view_compaction_task") self.server = server self.bucket = bucket self.design_doc_name = design_doc_name self.ddoc_id = "_design%2f" + design_doc_name self.compaction_revision = 0 self.precompacted_fragmentation = 0 self.with_rebalance = with_rebalance self.rest = RestConnection(self.server) def execute(self, task_manager): try: self.compaction_revision, self.precompacted_fragmentation = \ self._get_compaction_details() self.log.info("{0}: stats compaction before triggering it: ({1},{2})". format(self.design_doc_name, self.compaction_revision, self.precompacted_fragmentation)) if self.precompacted_fragmentation == 0: self.log.info("%s: There is nothing to compact, fragmentation is 0" % self.design_doc_name) self.set_result(False) self.state = FINISHED return self.rest.ddoc_compaction(self.ddoc_id, self.bucket) self.state = CHECKING task_manager.schedule(self, 2) except (CompactViewFailed, SetViewInfoNotFound) as ex: self.state = FINISHED self.set_exception(ex) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) # verify compaction history incremented and some defraging occurred def check(self, task_manager): try: _compaction_running = self._is_compacting() new_compaction_revision, fragmentation = self._get_compaction_details() self.log.info("{0}: stats compaction:revision and fragmentation: ({1},{2})". format(self.design_doc_name, new_compaction_revision, fragmentation)) if new_compaction_revision == self.compaction_revision and _compaction_running: # compaction ran successfully but compaction was not changed # perhaps we are still compacting self.log.info("design doc {0} is compacting".format(self.design_doc_name)) task_manager.schedule(self, 3) elif new_compaction_revision > self.compaction_revision or \ self.precompacted_fragmentation > fragmentation: self.log.info( "{1}: compactor was run, compaction revision was changed on {0}".format(new_compaction_revision, self.design_doc_name)) frag_val_diff = fragmentation - self.precompacted_fragmentation self.log.info("%s: fragmentation went from %d to %d" % \ (self.design_doc_name, self.precompacted_fragmentation, fragmentation)) if frag_val_diff > 0: # compaction ran successfully but datasize still same # perhaps we are still compacting if self._is_compacting(): task_manager.schedule(self, 2) self.log.info( "compaction was completed, but fragmentation value {0} is more than before compaction {1}". format(fragmentation, self.precompacted_fragmentation)) # probably we already compacted, but no work needed to be done self.set_result(self.with_rebalance) else: self.set_result(True) self.state = FINISHED else: # Sometimes the compacting is not started immediately for i in range(17): time.sleep(3) if self._is_compacting(): task_manager.schedule(self, 2) return else: new_compaction_revision, fragmentation = self._get_compaction_details() self.log.info("{2}: stats compaction: ({0},{1})". format(new_compaction_revision, fragmentation, self.design_doc_name)) # case of rebalance when with concurrent updates it's possible that # compaction value has not changed significantly if new_compaction_revision > self.compaction_revision and self.with_rebalance: self.log.warning("the compaction revision was increased,\ but the actual fragmentation value has not changed significantly") self.set_result(True) self.state = FINISHED return else: continue # print details in case of failure self.log.info("design doc {0} is compacting:{1}".format(self.design_doc_name, self._is_compacting())) new_compaction_revision, fragmentation = self._get_compaction_details() self.log.error("stats compaction still: ({0},{1})". format(new_compaction_revision, fragmentation)) status, content = self.rest.set_view_info(self.bucket, self.design_doc_name) stats = content["stats"] self.log.warning("general compaction stats:{0}".format(stats)) self.set_exception(Exception("Check system logs, looks like compaction failed to start")) except (SetViewInfoNotFound) as ex: self.state = FINISHED self.set_exception(ex) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def _get_compaction_details(self): status, content = self.rest.set_view_info(self.bucket, self.design_doc_name) curr_no_of_compactions = content["stats"]["compactions"] curr_ddoc_fragemtation = \ MonitorViewFragmentationTask.calc_ddoc_fragmentation(self.rest, self.design_doc_name, self.bucket, self.with_rebalance) return (curr_no_of_compactions, curr_ddoc_fragemtation) def _is_compacting(self): status, content = self.rest.set_view_info(self.bucket, self.design_doc_name) return content["compact_running"] == True '''task class for failover. This task will only failover nodes but doesn't rebalance as there is already a task to do that''' class FailoverTask(Task): def __init__(self, servers, to_failover=[], wait_for_pending=0, graceful=False, use_hostnames=False): Task.__init__(self, "failover_task") self.servers = servers self.to_failover = to_failover self.graceful = graceful self.wait_for_pending = wait_for_pending self.use_hostnames = use_hostnames def execute(self, task_manager): try: self._failover_nodes(task_manager) self.log.info("{0} seconds sleep after failover, for nodes to go pending....".format(self.wait_for_pending)) time.sleep(self.wait_for_pending) self.state = FINISHED self.set_result(True) except FailoverFailedException as e: self.state = FINISHED self.set_exception(e) except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def _failover_nodes(self, task_manager): rest = RestConnection(self.servers[0]) # call REST fail_over for the nodes to be failed over for server in self.to_failover: for node in rest.node_statuses(): if (server.hostname if self.use_hostnames else server.ip) == node.ip and int(server.port) == int( node.port): self.log.info("Failing over {0}:{1} with graceful={2}".format(node.ip, node.port, self.graceful)) rest.fail_over(node.id, self.graceful) class GenerateExpectedViewResultsTask(Task): """ Task to produce the set of keys that are expected to be returned by querying the provided <view>. Results can be later passed to ViewQueryVerificationTask and compared with actual results from server. Currently only views with map functions that emit a single string or integer as keys are accepted. Also NOTE, this task is to be used with doc_generators that produce json like documentgenerator.DocumentGenerator """ def __init__(self, doc_generators, view, query): Task.__init__(self, "generate_view_query_results_task") self.doc_generators = doc_generators self.view = view self.query = query self.emitted_rows = [] self.is_reduced = self.view.red_func is not None and (('reduce' in query and query['reduce'] == "true") or \ (not 'reduce' in query)) self.custom_red_fn = self.is_reduced and not self.view.red_func in ['_count', '_sum', '_stats'] self.type_filter = None def execute(self, task_manager): try: self.generate_emitted_rows() self.filter_emitted_rows() self.log.info("Finished generating expected query results") self.state = CHECKING task_manager.schedule(self) except Exception as ex: self.state = FINISHED self.set_unexpected_exception(ex) traceback.print_exc() def check(self, task_manager): self.state = FINISHED self.set_result(self.emitted_rows) def generate_emitted_rows(self): emit_key = re.sub(r',.*', '', re.sub(r'.*emit\([ +]?doc\.', '', self.view.map_func)) emit_value = None if re.match(r'.*emit\([ +]?\[doc\.*', self.view.map_func): emit_key = re.sub(r'],.*', '', re.sub(r'.*emit\([ +]?\[doc\.', '', self.view.map_func)) emit_key = emit_key.split(", doc.") if re.match(r'.*new RegExp\("\^.*', self.view.map_func): filter_what = re.sub(r'.*new RegExp\(.*\)*doc\.', '', re.sub(r'\.match\(.*', '', self.view.map_func)) self.type_filter = {"filter_what": filter_what, "filter_expr": re.sub(r'[ +]?"\);.*', '', re.sub(r'.*.new RegExp\("\^', '', self.view.map_func))} if self.is_reduced and self.view.red_func != "_count": emit_value = re.sub(r'\);.*', '', re.sub(r'.*emit\([ +]?\[*],[ +]?doc\.', '', self.view.map_func)) if self.view.map_func.count("[") <= 1: emit_value = re.sub(r'\);.*', '', re.sub(r'.*emit\([ +]?.*,[ +]?doc\.', '', self.view.map_func)) for doc_gen in self.doc_generators: query_doc_gen = copy.deepcopy(doc_gen) while query_doc_gen.has_next(): _id, val = next(query_doc_gen) val = json.loads(val) if isinstance(emit_key, list): val_emit_key = [] for ek in emit_key: val_emit_key.append(val[ek]) else: val_emit_key = val[emit_key] if self.type_filter: filter_expr = r'\A{0}.*'.format(self.type_filter["filter_expr"]) if re.match(filter_expr, val[self.type_filter["filter_what"]]) is None: continue if isinstance(val_emit_key, str): val_emit_key = val_emit_key.encode('utf-8') if not self.is_reduced or self.view.red_func == "_count" or self.custom_red_fn: self.emitted_rows.append({'id': _id, 'key': val_emit_key}) else: val_emit_value = val[emit_value] self.emitted_rows.append({'value': val_emit_value, 'key': val_emit_key, 'id': _id, }) def filter_emitted_rows(self): query = self.query # parse query flags descending_set = 'descending' in query and query['descending'] == "true" startkey_set, endkey_set = 'startkey' in query, 'endkey' in query startkey_docid_set, endkey_docid_set = 'startkey_docid' in query, 'endkey_docid' in query inclusive_end_false = 'inclusive_end' in query and query['inclusive_end'] == "false" key_set = 'key' in query # sort expected results to match view results expected_rows = sorted(self.emitted_rows, key=cmp_to_key(lambda a, b: GenerateExpectedViewResultsTask.cmp_result_rows(a, b)), reverse=descending_set) # filter rows according to query flags if startkey_set: start_key = query['startkey'] if isinstance(start_key, str) and start_key.find('"') == 0: start_key = start_key[1:-1] if isinstance(start_key, str) and start_key.find('[') == 0: start_key = start_key[1:-1].split(',') start_key = [int(x) if x != 'null' else 0 for x in start_key] else: start_key = expected_rows[0]['key'] if isinstance(start_key, str) and start_key.find('"') == 0: start_key = start_key[1:-1] if endkey_set: end_key = query['endkey'] if isinstance(end_key, str) and end_key.find('"') == 0: end_key = end_key[1:-1] if isinstance(end_key, str) and end_key.find('[') == 0: end_key = end_key[1:-1].split(',') end_key = [int(x) if x != 'null' else None for x in end_key] else: end_key = expected_rows[-1]['key'] if isinstance(end_key, str) and end_key.find('"') == 0: end_key = end_key[1:-1] if descending_set: start_key, end_key = end_key, start_key if startkey_set or endkey_set: if isinstance(start_key, str): start_key = start_key.strip("\"") if isinstance(end_key, str): end_key = end_key.strip("\"") expected_rows = [row for row in expected_rows if row['key'] >= start_key and row['key'] <= end_key] if key_set: key_ = query['key'] if isinstance(key_, str) and key_.find('[') == 0: key_ = key_[1:-1].split(',') key_ = [int(x) if x != 'null' else None for x in key_] start_key, end_key = key_, key_ expected_rows = [row for row in expected_rows if row['key'] == key_] if descending_set: startkey_docid_set, endkey_docid_set = endkey_docid_set, startkey_docid_set if startkey_docid_set: if not startkey_set: self.log.warning("Ignoring startkey_docid filter when startkey is not set") else: do_filter = False if descending_set: if endkey_docid_set: startkey_docid = query['endkey_docid'] do_filter = True else: startkey_docid = query['startkey_docid'] do_filter = True if do_filter: expected_rows = \ [row for row in expected_rows if row['id'] >= startkey_docid or row['key'] > start_key] if endkey_docid_set: if not endkey_set: self.log.warning("Ignoring endkey_docid filter when endkey is not set") else: do_filter = False if descending_set: if endkey_docid_set: endkey_docid = query['startkey_docid'] do_filter = True else: endkey_docid = query['endkey_docid'] do_filter = True if do_filter: expected_rows = \ [row for row in expected_rows if row['id'] <= endkey_docid or row['key'] < end_key] if inclusive_end_false: if endkey_set and endkey_docid_set: # remove all keys that match endkey expected_rows = [row for row in expected_rows if row['id'] < query['endkey_docid'] or row['key'] < end_key] elif endkey_set: expected_rows = [row for row in expected_rows if row['key'] != end_key] if self.is_reduced: groups = {} gr_level = None if not 'group' in query and \ not 'group_level' in query: if len(expected_rows) == 0: expected_rows = [] self.emitted_rows = expected_rows return if self.view.red_func == '_count': groups[None] = len(expected_rows) elif self.view.red_func == '_sum': groups[None] = 0 groups[None] = math.fsum([row['value'] for row in expected_rows]) elif self.view.red_func == '_stats': groups[None] = {} values = [row['value'] for row in expected_rows] groups[None]['count'] = len(expected_rows) groups[None]['sum'] = math.fsum(values) groups[None]['max'] = max(values) groups[None]['min'] = min(values) groups[None]['sumsqr'] = math.fsum([x * x for x in values]) elif self.custom_red_fn: custom_action = re.sub(r'.*return[ +]', '', re.sub(r'.*return[ +]', '', self.view.red_func)) if custom_action.find('String') != -1: groups[None] = str(len(expected_rows)) elif custom_action.find('-') != -1: groups[None] = -len(expected_rows) elif 'group' in query and query['group'] == 'true': if not 'group_level' in query: gr_level = len(expected_rows) - 1 elif 'group_level' in query: gr_level = int(query['group_level']) if gr_level is not None: for row in expected_rows: key = str(row['key'][:gr_level]) if not key in groups: if self.view.red_func == '_count': groups[key] = 1 elif self.view.red_func == '_sum': groups[key] = row['value'] elif self.view.red_func == '_stats': groups[key] = {} groups[key]['count'] = 1 groups[key]['sum'] = row['value'] groups[key]['max'] = row['value'] groups[key]['min'] = row['value'] groups[key]['sumsqr'] = row['value'] ** 2 else: if self.view.red_func == '_count': groups[key] += 1 elif self.view.red_func == '_sum': groups[key] += row['value'] elif self.view.red_func == '_stats': groups[key]['count'] += 1 groups[key]['sum'] += row['value'] groups[key]['max'] = max(row['value'], groups[key]['max']) groups[key]['min'] = min(row['value'], groups[key]['min']) groups[key]['sumsqr'] += row['value'] ** 2 expected_rows = [] for group, value in groups.items(): if isinstance(group, str) and group.find("[") == 0: group = group[1:-1].split(",") group = [int(k) for k in group] expected_rows.append({"key": group, "value": value}) expected_rows = sorted(expected_rows, key=cmp_to_key(lambda a, b: GenerateExpectedViewResultsTask.cmp_result_rows(a, b)), reverse=descending_set) if 'skip' in query: expected_rows = expected_rows[(int(query['skip'])):] if 'limit' in query: expected_rows = expected_rows[:(int(query['limit']))] self.emitted_rows = expected_rows @staticmethod def cmp_result_rows(x, y): rc = len(DeepDiff(x['key'], y['key'], ignore_order=True)) if rc == 0: # sort by id is tie breaker rc = len(DeepDiff(x['id'], y['id'], ignore_order=True)) return rc class ViewQueryVerificationTask(Task): """ * query with stale=false * check for duplicates * check for missing docs * check memcached * check couch """ def __init__(self, design_doc_name, view_name, query, expected_rows, server=None, num_verified_docs=20, bucket="default", query_timeout=120, results=None, config=None): Task.__init__(self, "view_query_verification_task") self.server = server self.design_doc_name = design_doc_name self.view_name = view_name self.query = query self.expected_rows = expected_rows self.num_verified_docs = num_verified_docs self.bucket = bucket self.query_timeout = query_timeout self.results = results try: for key in config: self.config[key] = config[key] except: pass def execute(self, task_manager): if not self.results: rest = RestConnection(self.server) try: # query for full view results self.query["stale"] = "false" self.query["reduce"] = "false" self.query["include_docs"] = "true" self.results = rest.query_view(self.design_doc_name, self.view_name, self.bucket, self.query, timeout=self.query_timeout) except QueryViewException as e: self.set_exception(e) self.state = FINISHED msg = "Checking view query results: (%d keys expected) vs (%d keys returned)" % \ (len(self.expected_rows), len(self.results['rows'])) self.log.info(msg) self.state = CHECKING task_manager.schedule(self) def check(self, task_manager): err_infos = [] rc_status = {"passed": False, "errors": err_infos} # array of dicts with keys 'msg' and 'details' try: # create verification id lists expected_ids = [row['id'] for row in self.expected_rows] couch_ids = [str(row['id']) for row in self.results['rows']] # check results self.check_for_duplicate_ids(expected_ids, couch_ids, err_infos) self.check_for_missing_ids(expected_ids, couch_ids, err_infos) self.check_for_extra_ids(expected_ids, couch_ids, err_infos) self.check_for_value_corruption(err_infos) # check for errors if len(rc_status["errors"]) == 0: rc_status["passed"] = True self.state = FINISHED self.set_result(rc_status) except Exception as ex: self.state = FINISHED try: max_example_result = max(100, len(self.results['rows'] - 1)) self.log.info("FIRST %s RESULTS for view %s : %s" % (max_example_result, self.view_name, self.results['rows'][max_example_result])) except Exception as inner_ex: self.log.error(inner_ex) self.set_result({"passed": False, "errors": "ERROR: %s" % ex}) def check_for_duplicate_ids(self, expected_ids, couch_ids, err_infos): extra_id_set = set(couch_ids) - set(expected_ids) seen = set() for id in couch_ids: if id in seen and id not in extra_id_set: extra_id_set.add(id) else: seen.add(id) if len(extra_id_set) > 0: # extra/duplicate id verification dupe_rows = [row for row in self.results['rows'] if row['id'] in extra_id_set] err = {"msg": "duplicate rows found in query results", "details": dupe_rows} err_infos.append(err) def check_for_missing_ids(self, expected_ids, couch_ids, err_infos): missing_id_set = set(expected_ids) - set(couch_ids) if len(missing_id_set) > 0: missing_id_errors = self.debug_missing_items(missing_id_set) if len(missing_id_errors) > 0: err = {"msg": "missing ids from memcached", "details": missing_id_errors} err_infos.append(err) def check_for_extra_ids(self, expected_ids, couch_ids, err_infos): extra_id_set = set(couch_ids) - set(expected_ids) if len(extra_id_set) > 0: err = {"msg": "extra ids from memcached", "details": extra_id_set} err_infos.append(err) def check_for_value_corruption(self, err_infos): if self.num_verified_docs > 0: doc_integrity_errors = self.include_doc_integrity() if len(doc_integrity_errors) > 0: err = {"msg": "missmatch in document values", "details": doc_integrity_errors} err_infos.append(err) def debug_missing_items(self, missing_id_set): rest = RestConnection(self.server) client = KVStoreAwareSmartClient(rest, self.bucket) missing_id_errors = [] # debug missing documents for doc_id in list(missing_id_set)[:self.num_verified_docs]: # attempt to retrieve doc from memcached mc_item = client.mc_get_full(doc_id) if mc_item == None: missing_id_errors.append("document %s missing from memcached" % (doc_id)) # attempt to retrieve doc from disk else: num_vbuckets = len(rest.get_vbuckets(self.bucket)) doc_meta = client.get_doc_metadata(num_vbuckets, doc_id) if (doc_meta != None): if (doc_meta['key_valid'] != 'valid'): msg = "Error expected in results for key with invalid state %s" % doc_meta missing_id_errors.append(msg) else: msg = "query doc_id: %s doesn't exist in bucket: %s" % \ (doc_id, self.bucket) missing_id_errors.append(msg) if (len(missing_id_errors) == 0): msg = "view engine failed to index doc [%s] in query: %s" % (doc_id, self.query) missing_id_errors.append(msg) return missing_id_errors def include_doc_integrity(self): rest = RestConnection(self.server) client = KVStoreAwareSmartClient(rest, self.bucket) doc_integrity_errors = [] if 'doc' not in self.results['rows'][0]: return doc_integrity_errors exp_verify_set = [row['doc'] for row in \ self.results['rows'][:self.num_verified_docs]] for view_doc in exp_verify_set: doc_id = str(view_doc['_id']) mc_item = client.mc_get_full(doc_id) if mc_item is not None: mc_doc = json.loads(mc_item["value"]) # compare doc content for key in list(mc_doc.keys()): if (mc_doc[key] != view_doc[key]): err_msg = \ "error verifying document id %s: retrieved value %s expected %s \n" % \ (doc_id, mc_doc[key], view_doc[key]) doc_integrity_errors.append(err_msg) else: doc_integrity_errors.append("doc_id %s could not be retrieved for verification \n" % doc_id) return doc_integrity_errors class BucketFlushTask(Task): def __init__(self, server, bucket="default"): Task.__init__(self, "bucket_flush_task") self.server = server self.bucket = bucket if isinstance(bucket, Bucket): self.bucket = bucket.name def execute(self, task_manager): try: rest = RestConnection(self.server) if rest.flush_bucket(self.bucket): self.state = CHECKING task_manager.schedule(self) else: self.state = FINISHED self.set_result(False) except BucketFlushFailed as e: self.state = FINISHED self.set_exception(e) except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): try: # check if after flush the vbuckets are ready if BucketOperationHelper.wait_for_vbuckets_ready_state(self.server, self.bucket): self.set_result(True) else: self.log.error("Unable to reach bucket {0} on server {1} after flush".format(self.bucket, self.server)) self.set_result(False) self.state = FINISHED except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) class MonitorDBFragmentationTask(Task): """ Attempt to monitor fragmentation that is occurring for a given bucket. Note: If autocompaction is enabled and user attempts to monitor for fragmentation value higher than level at which auto_compaction kicks in a warning is sent and it is best user to use lower value as this can lead to infinite monitoring. """ def __init__(self, server, fragmentation_value=10, bucket="default", get_view_frag=False): Task.__init__(self, "monitor_frag_db_task") self.server = server self.bucket = bucket self.fragmentation_value = fragmentation_value self.get_view_frag = get_view_frag def execute(self, task_manager): # sanity check of fragmentation value if self.fragmentation_value < 0 or self.fragmentation_value > 100: err_msg = \ "Invalid value for fragmentation %d" % self.fragmentation_value self.state = FINISHED self.set_exception(Exception(err_msg)) self.state = CHECKING task_manager.schedule(self, 5) def check(self, task_manager): try: rest = RestConnection(self.server) stats = rest.fetch_bucket_stats(bucket=self.bucket) if self.get_view_frag: new_frag_value = stats["op"]["samples"]["couch_views_fragmentation"][-1] self.log.info("Current amount of views fragmentation = %d" % new_frag_value) else: new_frag_value = stats["op"]["samples"]["couch_docs_fragmentation"][-1] self.log.info("current amount of docs fragmentation = %d" % new_frag_value) if new_frag_value >= self.fragmentation_value: self.state = FINISHED self.set_result(True) else: # try again task_manager.schedule(self, 2) except Exception as ex: self.state = FINISHED self.set_result(False) self.set_exception(ex) class CBRecoveryTask(Task): def __init__(self, src_server, dest_server, bucket_src='', bucket_dest='', username='', password='', username_dest='', password_dest='', verbose=False, wait_completed=True): Task.__init__(self, "cbrecovery_task") self.src_server = src_server self.dest_server = dest_server self.bucket_src = bucket_src self.bucket_dest = bucket_dest if isinstance(bucket_src, Bucket): self.bucket_src = bucket_src.name if isinstance(bucket_dest, Bucket): self.bucket_dest = bucket_dest.name self.username = username self.password = password self.username_dest = username_dest self.password_dest = password_dest self.verbose = verbose self.wait_completed = wait_completed try: self.shell = RemoteMachineShellConnection(src_server) self.info = self.shell.extract_remote_info() self.rest = RestConnection(dest_server) except Exception as e: self.log.error(e) self.state = FINISHED self.set_exception(e) self.progress = {} self.started = False self.retries = 0 def execute(self, task_manager): try: if self.info.type.lower() == "linux": command = "/opt/couchbase/bin/cbrecovery " elif self.info.type.lower() == "windows": command = "C:/Program\ Files/Couchbase/Server/bin/cbrecovery.exe " src_url = "http://{0}:{1}".format(self.src_server.ip, self.src_server.port) dest_url = "http://{0}:{1}".format(self.dest_server.ip, self.dest_server.port) command += "{0} {1} ".format(src_url, dest_url) if self.bucket_src: command += "-b {0} ".format(self.bucket_src) if self.bucket_dest: command += "-B {0} ".format(self.bucket_dest) if self.username: command += "-u {0} ".format(self.username) if self.password: command += "-p {0} ".format(self.password) if self.username_dest: command += "-U {0} ".format(self.username_dest) if self.password_dest: command += "-P {0} ".format(self.password_dest) if self.verbose: command += " -v " transport = self.shell._ssh_client.get_transport() transport.set_keepalive(1) self.chan = transport.open_session() self.chan.settimeout(10 * 60.0) self.chan.exec_command(command) self.log.info("command was executed: '{0}'".format(command)) self.state = CHECKING task_manager.schedule(self, 20) except Exception as e: self.state = FINISHED self.set_exception(e) # it was done to keep connection alive def checkChannel(self): try: if self.chan.exit_status_ready(): if self.chan.recv_ready(): output = self.chan.recv(1048576) if self.chan.recv_stderr_ready(): error = self.chan.recv_stderr(1048576) except socket.timeout: print("SSH channel timeout exceeded.") except Exception: traceback.print_exc() def check(self, task_manager): self.checkChannel() self.recovery_task = self.rest.get_recovery_task() if self.recovery_task is not None: if not self.started: self.started = True if not self.wait_completed: progress = self.rest.get_recovery_progress(self.recovery_task["recoveryStatusURI"]) self.log.info("cbrecovery strarted with progress: {0}".format(progress)) self.log.info("will not wait for the end of the cbrecovery") self.state = FINISHED self.set_result(True) progress = self.rest.get_recovery_progress(self.recovery_task["recoveryStatusURI"]) if progress == self.progress: self.log.warning("cbrecovery progress was not changed") if self.retries > 20: self.shell.disconnect() self.rest.print_UI_logs() self.state = FINISHED self.log.warning("ns_server_tasks: {0}".format(self.rest.ns_server_tasks())) self.log.warning("cbrecovery progress: {0}".format( self.rest.get_recovery_progress(self.recovery_task["recoveryStatusURI"]))) self.set_exception(CBRecoveryFailedException("cbrecovery hangs")) return self.retries += 1 task_manager.schedule(self, 20) else: self.progress = progress self.log.info("cbrecovery progress: {0}".format(self.progress)) self.retries = 0 task_manager.schedule(self, 20) else: if self.started: self.shell.disconnect() self.log.info("cbrecovery completed succesfully") self.state = FINISHED self.set_result(True) if self.retries > 5: self.shell.disconnect() self.rest.print_UI_logs() self.state = FINISHED self.log.warning("ns_server_tasks: {0}".format(self.rest.ns_server_tasks())) self.set_exception(CBRecoveryFailedException("cbrecovery was not started")) return else: self.retries += 1 task_manager.schedule(self, 20) class CompactBucketTask(Task): def __init__(self, server, bucket="default"): Task.__init__(self, "bucket_compaction_task") self.server = server self.bucket = bucket self.rest = RestConnection(server) self.retries = 20 self.statuses = {} # get the current count of compactions nodes = self.rest.get_nodes() self.compaction_count = {} for node in nodes: self.compaction_count[node.ip] = 0 def execute(self, task_manager): try: status = self.rest.compact_bucket(self.bucket) self.state = CHECKING except BucketCompactionException as e: self.log.error("Bucket compaction failed for unknown reason") self.set_exception(e) self.state = FINISHED self.set_result(False) task_manager.schedule(self) def check(self, task_manager): # check bucket compaction status across all nodes nodes = self.rest.get_nodes() current_compaction_count = {} for node in nodes: current_compaction_count[node.ip] = 0 s = TestInputServer() s.ip = node.ip s.ssh_username = self.server.ssh_username s.ssh_password = self.server.ssh_password shell = RemoteMachineShellConnection(s) res = shell.execute_cbstats("", "raw", keyname="kvtimings", vbid="") for i in res[0]: # check for lines that look like # rw_0:compact_131072,262144: 8 if 'compact' in i: current_compaction_count[node.ip] += int(i.split(':')[2]) if len(DeepDiff(current_compaction_count, self.compaction_count)) == 1: # compaction count has increased self.set_result(True) self.state = FINISHED else: if self.retries > 0: # retry self.retries = self.retries - 1 task_manager.schedule(self, 10) else: # never detected a compaction task running self.set_result(False) self.state = FINISHED def _get_disk_size(self): stats = self.rest.fetch_bucket_stats(bucket=self.bucket) total_disk_size = stats["op"]["samples"]["couch_total_disk_size"][-1] self.log.info("Disk size is = %d" % total_disk_size) return total_disk_size class MonitorViewCompactionTask(ViewCompactionTask): def __init__(self, server, design_doc_name, bucket="default", with_rebalance=False, frag_value=0): ViewCompactionTask.__init__(self, server, design_doc_name, bucket, with_rebalance) self.ddoc_id = "_design%2f" + design_doc_name self.compaction_revision = 0 self.precompacted_fragmentation = 0 self.fragmentation_value = frag_value self.rest = RestConnection(self.server) def execute(self, task_manager): try: self.compaction_revision, self.precompacted_fragmentation = self._get_compaction_details() self.log.info("{0}: stats compaction before triggering it: ({1},{2})". format(self.design_doc_name, self.compaction_revision, self.precompacted_fragmentation)) self.disk_size = self._get_disk_size() self.log.info("Disk Size Before Compaction {0}".format(self.disk_size)) if self.precompacted_fragmentation == 0: self.log.warning("%s: There is nothing to compact, fragmentation is 0" % self.design_doc_name) self.set_result(False) self.state = FINISHED elif self.precompacted_fragmentation < self.fragmentation_value: self.log.info( "{0}: Compaction is already done and there is nothing to compact, current fragmentation is lesser {1} {2}". format(self.design_doc_name, self.precompacted_fragmentation, self.fragmentation_value)) self.compaction_revision, self.precompacted_fragmentation = self._get_compaction_details() self.log.info("{0}: stats compaction before triggering it: ({1},{2})". format(self.design_doc_name, self.compaction_revision, self.precompacted_fragmentation)) self.set_result(True) self.state = FINISHED return self.state = CHECKING task_manager.schedule(self, 2) except (CompactViewFailed, SetViewInfoNotFound) as ex: self.state = FINISHED self.set_exception(ex) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) # verify compaction history incremented and some defraging occurred def check(self, task_manager): try: _compaction_running = self._is_compacting() new_compaction_revision, fragmentation = self._get_compaction_details() self.log.info("{0}: stats compaction:revision and fragmentation: ({1},{2})". format(self.design_doc_name, new_compaction_revision, fragmentation)) curr_disk_size = self._get_disk_size() self.log.info("Current Disk Size {0}".format(curr_disk_size)) if new_compaction_revision == self.compaction_revision and _compaction_running: # compaction ran successfully but compaction was not changed, perhaps we are still compacting self.log.info("design doc {0} is compacting".format(self.design_doc_name)) task_manager.schedule(self, 3) elif self.precompacted_fragmentation > fragmentation: self.log.info("%s: Pre Compacted fragmentation is more, before Compaction %d and after Compaction %d" % \ (self.design_doc_name, self.precompacted_fragmentation, fragmentation)) frag_val_diff = fragmentation - self.precompacted_fragmentation if new_compaction_revision == self.compaction_revision or new_compaction_revision > self.compaction_revision: self.log.info("{1}: compactor was run, compaction revision was changed on {0}". format(new_compaction_revision, self.design_doc_name)) self.log.info("%s: fragmentation went from %d to %d" % ( self.design_doc_name, self.precompacted_fragmentation, fragmentation)) if frag_val_diff > 0: if self._is_compacting(): task_manager.schedule(self, 5) self.log.info( "compaction was completed, but fragmentation value {0} is more than before compaction {1}". format(fragmentation, self.precompacted_fragmentation)) self.log.info("Load is still in progress, Need to be checked") self.set_result(self.with_rebalance) else: self.set_result(True) self.state = FINISHED else: for i in range(10): time.sleep(3) if self._is_compacting(): task_manager.schedule(self, 2) return else: new_compaction_revision, fragmentation = self._get_compaction_details() self.log.info("{2}: stats compaction: ({0},{1})".format(new_compaction_revision, fragmentation, self.design_doc_name)) curr_disk_size = self._get_disk_size() self.log.info("Disk Size went from {0} {1}".format(self.disk_size, curr_disk_size)) if new_compaction_revision > self.compaction_revision and self.precompacted_fragmentation > fragmentation: self.log.warning( "the compaction revision was increase and fragmentation value went from {0} {1}". format(self.precompacted_fragmentation, fragmentation)) self.set_result(True) self.state = FINISHED return elif new_compaction_revision > self.compaction_revision and self.with_rebalance: self.log.warning( "the compaction revision was increased, but the actual fragmentation value has not changed significantly") self.set_result(True) self.state = FINISHED return else: continue self.log.info("design doc {0} is compacting:{1}".format(self.design_doc_name, self._is_compacting())) new_compaction_revision, fragmentation = self._get_compaction_details() self.log.error("stats compaction still: ({0},{1})". format(new_compaction_revision, fragmentation)) status, content = self.rest.set_view_info(self.bucket, self.design_doc_name) stats = content["stats"] self.log.warning("general compaction stats:{0}".format(stats)) self.state = FINISHED self.set_result(False) self.set_exception(Exception("Check system logs, looks like compaction failed to start")) except (SetViewInfoNotFound) as ex: self.state = FINISHED self.set_exception(ex) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def _get_disk_size(self): nodes_ddoc_info = MonitorViewFragmentationTask.aggregate_ddoc_info(self.rest, self.design_doc_name, self.bucket, self.with_rebalance) disk_size = sum([content['disk_size'] for content in nodes_ddoc_info]) return disk_size class MonitorDiskSizeFragmentationTask(Task): def __init__(self, server, fragmentation_value=10, bucket="default", get_view_frag=False): Task.__init__(self, "monitor_frag_db_task") self.server = server self.bucket = bucket self.fragmentation_value = fragmentation_value self.get_view_frag = get_view_frag self.rest = RestConnection(self.server) self.curr_disk_size = 0 def execute(self, task_manager): if self.fragmentation_value < 0: err_msg = \ "Invalid value for fragmentation %d" % self.fragmentation_value self.state = FINISHED self.set_exception(Exception(err_msg)) self.state = CHECKING task_manager.schedule(self, 5) def check(self, task_manager): try: rest = RestConnection(self.server) stats = rest.fetch_bucket_stats(bucket=self.bucket) if self.get_view_frag: new_disk_size = stats["op"]["samples"]["couch_views_actual_disk_size"][-1] else: new_disk_size = stats["op"]["samples"]["couch_total_disk_size"][-1] if self.curr_disk_size > new_disk_size: self.state = FINISHED self.set_result(True) else: # try again task_manager.schedule(self, 5) self.log.info("New and Current Disk size is {0} {1}".format(new_disk_size, self.curr_disk_size)) self.curr_disk_size = new_disk_size except Exception as ex: self.state = FINISHED self.set_result(False) self.set_exception(ex) class CancelBucketCompactionTask(Task): def __init__(self, server, bucket="default"): Task.__init__(self, "cancel_bucket_compaction_task") self.server = server self.bucket = bucket self.retries = 20 self.statuses = {} try: self.rest = RestConnection(server) except ServerUnavailableException as e: self.log.error(e) self.state = FINISHED self.set_exception(e) def execute(self, task_manager): try: status = self.rest.cancel_bucket_compaction(self.bucket) self.state = CHECKING except BucketCompactionException as e: self.log.error("Cancel Bucket compaction failed for unknown reason") self.set_exception(e) self.state = FINISHED self.set_result(False) task_manager.schedule(self) def check(self, task_manager): # check cancel bucket compaction status across all nodes nodes = self.rest.get_nodes() for node in nodes: last_status = self.statuses.get(node.id) try: rest = RestConnection(node) except ServerUnavailableException as e: self.log.error(e) self.state = FINISHED self.set_exception(e) running, progress = rest.check_compaction_status(self.bucket) if progress is None and last_status is False: # finished if previously detected running but not == 100% self.statuses[node.id] = True if running: self.log.info("Progress is {0}".format(progress)) self.statuses[node.id] = (progress == 100) done = all(self.statuses.values()) if done: self.log.info("Bucket Compaction Cancelled successfully") # task was completed sucessfully self.set_result(True) self.state = FINISHED else: if self.retries > 0: self.retries = self.retries - 1 task_manager.schedule(self, 10) else: # never detected a compaction task running self.log.error("Bucket Compaction Cancellation not started") self.set_result(False) self.state = FINISHED class EnterpriseBackupTask(Task): def __init__(self, backupset, objstore_provider, resume=False, purge=False, no_progress_bar=False, cli_command_location='', cb_version=None, num_shards=''): Task.__init__(self, "enterprise_backup_task") self.backupset = backupset self.objstore_provider = objstore_provider self.resume = resume self.purge = purge self.no_progress_bar = no_progress_bar self.cli_command_location = cli_command_location self.cb_version = cb_version self.cluster_flag = "--host" self.num_shards = num_shards """ from couchbase version 4.6.x, --host flag is not supported """ if self.cb_version is None: raise Exception("Need to pass Couchbase version to run correctly bk/rt ") elif self.cb_version[:5] in COUCHBASE_FROM_4DOT6: self.cluster_flag = "--cluster" self.output = [] self.error = [] try: self.remote_client = RemoteMachineShellConnection(self.backupset.backup_host) except Exception as e: self.log.error(e) self.state = FINISHED self.set_exception(e) def execute(self, task_manager): try: args = ( f"backup --archive {self.objstore_provider.schema_prefix() + self.backupset.objstore_bucket + "/" if self.objstore_provider else ""}{self.backupset.directory}" f" --repo {self.backupset.name}" f" {self.cluster_flag} http://{self.backupset.cluster_host.ip}:{self.backupset.cluster_host.port}" f" --username {self.backupset.cluster_host.rest_username}" f" --password {self.backupset.cluster_host.rest_password}" f" {self.num_shards}" f"{" --obj-staging-dir " + self.backupset.objstore_staging_directory if self.objstore_provider else ""}" f"{" --obj-endpoint " + self.backupset.objstore_endpoint if self.objstore_provider and self.backupset.objstore_endpoint else ""}" f"{" --obj-region " + self.backupset.objstore_region if self.objstore_provider and self.backupset.objstore_region else ""}" f"{" --obj-access-key-id " + self.backupset.objstore_access_key_id if self.objstore_provider and self.backupset.objstore_access_key_id else ""}" f"{" --obj-secret-access-key " + self.backupset.objstore_secret_access_key if self.objstore_provider and self.backupset.objstore_secret_access_key else ""}" f"{" --s3-force-path-style" if self.objstore_provider and self.objstore_provider.schema_prefix() == "s3://" else ""}" ) if self.resume: args += " --resume" if self.purge: args += " --purge" if self.no_progress_bar: args += " --no-progress-bar" command = "{0}/cbbackupmgr {1}".format(self.cli_command_location, args) self.output, self.error = self.remote_client.execute_command(command) self.state = CHECKING except Exception as e: self.log.error("Backup cluster failed for unknown reason") self.set_exception(e) self.state = FINISHED self.set_result(False) task_manager.schedule(self) def check(self, task_manager): if self.output: self.state = FINISHED self.set_result(self.output) self.remote_client.log_command_output(self.output, self.error) elif self.error: self.state = FINISHED self.set_result(self.error) self.remote_client.log_command_output(self.output, self.error) else: task_manager.schedule(self, 10) class EnterpriseRestoreTask(Task): def __init__(self, backupset, objstore_provider, no_progress_bar=False, cli_command_location='', cb_version=None, start="start", end="end", backups=[], force_updates=False, no_resume=False): Task.__init__(self, "enterprise_backup_task") self.backupset = backupset self.objstore_provider = objstore_provider self.no_progress_bar = no_progress_bar self.cli_command_location = cli_command_location self.cb_version = cb_version self.cluster_flag = "--host" """ from couchbase version 4.6.x, --host flag is not supported """ if self.cb_version is None: raise Exception("Need to pass Couchbase version to run correctly bk/rt ") elif self.cb_version[:5] in COUCHBASE_FROM_4DOT6: self.cluster_flag = "--cluster" self.output = [] self.error = [] self.backups = backups self.start = start self.end = end self.force_updates = force_updates self.no_resume = no_resume try: self.remote_client = RemoteMachineShellConnection(self.backupset.backup_host) except Exception as e: self.log.error(e) self.state = FINISHED self.set_exception(e) def execute(self, task_manager): try: if isinstance(self.start, int) and isinstance(self.end, int): try: backup_start = self.backups[int(self.start) - 1] except IndexError: backup_start = "{0}{1}".format(self.backups[-1], self.start) try: backup_end = self.backups[int(self.end) - 1] except IndexError: backup_end = "{0}{1}".format(self.backups[-1], self.end) else: backup_start = self.start backup_end = self.end args = ( f"restore --archive {self.objstore_provider.schema_prefix() + self.backupset.objstore_bucket + "/" if self.objstore_provider else ""}{self.backupset.directory}" f" --repo {self.backupset.name}" f" {self.cluster_flag} http://{self.backupset.restore_cluster_host.ip}:{self.backupset.restore_cluster_host.port}" f" --username {self.backupset.restore_cluster_host.rest_username} " f" --password {self.backupset.restore_cluster_host.rest_password}" f" --start {backup_start}" f" --end {backup_end}" f"{" --obj-staging-dir " + self.backupset.objstore_staging_directory if self.objstore_provider else ""}" f"{" --obj-endpoint " + self.backupset.objstore_endpoint if self.objstore_provider and self.backupset.objstore_endpoint else ""}" f"{" --obj-region " + self.backupset.objstore_region if self.objstore_provider and self.backupset.objstore_region else ""}" f"{" --obj-access-key-id " + self.backupset.objstore_access_key_id if self.objstore_provider and self.backupset.objstore_access_key_id else ""}" f"{" --obj-secret-access-key " + self.backupset.objstore_secret_access_key if self.objstore_provider and self.backupset.objstore_secret_access_key else ""}" f"{" --s3-force-path-style" if self.objstore_provider and self.objstore_provider.schema_prefix() == "s3://" else ""}" f"{" --resume" if self.backupset.resume and not self.no_resume else ""}" ) if self.no_progress_bar: args += " --no-progress-bar" if self.force_updates: args += " --force-updates" command = "{0}/cbbackupmgr {1}".format(self.cli_command_location, args) self.output, self.error = self.remote_client.execute_command(command) self.state = CHECKING except Exception as e: self.log.error("Restore failed for unknown reason") self.set_exception(e) self.state = FINISHED self.set_result(False) task_manager.schedule(self) def check(self, task_manager): if self.output: self.state = FINISHED self.set_result(self.output) self.remote_client.log_command_output(self.output, self.error) elif self.error: self.state = FINISHED self.set_result(self.error) self.remote_client.log_command_output(self.output, self.error) else: task_manager.schedule(self, 10) class EnterpriseMergeTask(Task): def __init__(self, backup_host, backups=[], start=0, end=0, directory='', name='', cli_command_location=''): Task.__init__(self, "enterprise_backup_task") self.backup_host = backup_host self.directory = directory self.name = name self.cli_command_location = cli_command_location self.output = [] self.error = [] self.backups = backups self.start = start self.end = end try: self.remote_client = RemoteMachineShellConnection(self.backup_host) except Exception as e: self.log.error(e) self.state = FINISHED self.set_exception(e) def execute(self, task_manager): try: try: backup_start = self.backups[int(self.start) - 1] except IndexError: backup_start = "{0}{1}".format(self.backups[-1], self.start) try: backup_end = self.backups[int(self.end) - 1] except IndexError: backup_end = "{0}{1}".format(self.backups[-1], self.end) args = "merge --archive {0} --repo {1} --start {2} --end {3}".format(self.directory, self.name, backup_start, backup_end) command = "{0}/cbbackupmgr {1}".format(self.cli_command_location, args) self.output, self.error = self.remote_client.execute_command(command) self.state = CHECKING except Exception as e: self.log.error("Merge failed for unknown reason") self.set_exception(e) self.state = FINISHED self.set_result(False) task_manager.schedule(self) def check(self, task_manager): if self.output: self.state = FINISHED self.set_result(self.output) self.remote_client.log_command_output(self.output, self.error) elif self.error: self.state = FINISHED self.set_result(self.error) self.remote_client.log_command_output(self.output, self.error) else: task_manager.schedule(self, 10) class EnterpriseCompactTask(Task): def __init__(self, backup_host, backup_to_compact, backups=[], directory='', name='', cli_command_location=''): Task.__init__(self, "enterprise_backup_task") self.backup_host = backup_host self.backup_to_compact = backup_to_compact self.directory = directory self.name = name self.cli_command_location = cli_command_location self.output = [] self.error = [] self.backups = backups try: self.remote_client = RemoteMachineShellConnection(self.backup_host) except Exception as e: self.log.error(e) self.state = FINISHED self.set_exception(e) def execute(self, task_manager): try: args = "compact --archive {0} --repo {1} --backup {2}".format(self.directory, self.name, self.backups[self.backup_to_compact]) command = "{0}/cbbackupmgr {1}".format(self.cli_command_location, args) self.output, self.error = self.remote_client.execute_command(command) self.state = CHECKING except Exception as e: self.log.error("Compact failed for unknown reason") self.set_exception(e) self.state = FINISHED self.set_result(False) task_manager.schedule(self) def check(self, task_manager): if self.output: self.state = FINISHED self.set_result(self.output) self.remote_client.log_command_output(self.output, self.error) elif self.error: self.state = FINISHED self.set_result(self.error) self.remote_client.log_command_output(self.output, self.error) else: task_manager.schedule(self, 10) class CBASQueryExecuteTask(Task): def __init__(self, server, cbas_endpoint, statement, mode=None, pretty=True): Task.__init__(self, "cbas_query_execute_task") self.server = server self.cbas_endpoint = cbas_endpoint self.statement = statement self.mode = mode self.pretty = pretty self.response = {} self.passed = True def execute(self, task_manager): try: rest = RestConnection(self.server) self.response = json.loads(rest.execute_statement_on_cbas(self.statement, self.mode, self.pretty, 70)) if self.response: self.state = CHECKING task_manager.schedule(self) else: self.log.info("Some error") self.state = FINISHED self.passed = False self.set_result(False) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.passed = False self.set_unexpected_exception(e) def check(self, task_manager): try: if "errors" in self.response: errors = self.response["errors"] else: errors = None if "results" in self.response: results = self.response["results"] else: results = None if "handle" in self.response: handle = self.response["handle"] else: handle = None if self.mode != "async": if self.response["status"] == "success": self.set_result(True) self.passed = True else: self.log.info(errors) self.passed = False self.set_result(False) else: if self.response["status"] == "started": self.set_result(True) self.passed = True else: self.log.info(errors) self.passed = False self.set_result(False) self.state = FINISHED # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) class NodesFailureTask(Task): def __init__(self, master, servers_to_fail, failure_type, timeout, pause=0, timeout_buffer=3, disk_timeout=0, disk_location=None, disk_size=5000, failure_timeout=60): Task.__init__(self, "NodesFailureTask") self.master = master self.servers_to_fail = servers_to_fail self.num_servers_to_fail = self.servers_to_fail.__len__() self.itr = 0 self.failure_type = failure_type self.timeout = timeout self.failure_timeout = failure_timeout self.pause = pause self.start_time = 0 self.timeout_buffer = timeout_buffer self.current_failure_node = self.servers_to_fail[0] self.max_time_to_wait_for_failover = self.timeout + \ self.timeout_buffer + 60 self.disk_timeout = disk_timeout self.disk_location = disk_location self.disk_size = disk_size self.taskmanager = None self.rebalance_in_progress = False def execute(self, task_manager): self.taskmanager = task_manager rest = RestConnection(self.master) if rest._rebalance_progress_status() == "running": self.rebalance_in_progress = True while self.has_next() and not self.done(): next(self) if self.pause > 0 and self.pause > self.timeout: self.check(task_manager) if self.pause == 0 or 0 < self.pause < self.timeout: self.check(task_manager) self.state = FINISHED self.set_result(True) def check(self, task_manager): rest = RestConnection(self.master) max_timeout = self.timeout + self.timeout_buffer + self.disk_timeout if self.start_time == 0: message = "Did not inject failure in the system." rest.print_UI_logs(10) self.log.error(message) self.state = FINISHED self.set_result(False) self.set_exception(NodesFailureException(message)) def has_next(self): return self.itr < self.num_servers_to_fail def __next__(self): if self.pause != 0: time.sleep(self.pause) if self.pause > self.timeout and self.itr != 0: rest = RestConnection(self.master) status = rest.reset_autofailover() self._rebalance() if not status: self.state = FINISHED self.set_result(False) self.set_exception(Exception("Reset of autofailover " "count failed")) self.current_failure_node = self.servers_to_fail[self.itr] self.start_time = time.time() self.log.info("before failure time: {}".format(time.ctime(time.time()))) if self.failure_type == "limit_file_limits_desc": self._enable_disable_limit_file_limits_desc(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_limit_file_limits_desc": self.enable_file_limit_desc(self.current_failure_node) elif self.failure_type == "disable_limit_file_limits_desc": self.disable_file_limit_desc(self.current_failure_node) elif self.failure_type == "limit_file_limits": self._enable_disable_limit_file_limits(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_limit_file_limits": self.enable_file_limit(self.current_failure_node) elif self.failure_type == "disable_limit_file_limits": self.disable_file_limit(self.current_failure_node) elif self.failure_type == "extra_files_in_log_dir": self._extra_files_in_log_dir(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_extra_files_in_log_dir": self.add_extra_files_in_log_dir(self.current_failure_node) elif self.failure_type == "disable_extra_files_in_log_dir": self.remove_extra_files_in_log_dir(self.current_failure_node) elif self.failure_type == "empty_files_in_log_dir": self._empty_file_in_log_dir(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_empty_files_in_log_dir": self.add_empty_file_in_log_dir(self.current_failure_node) elif self.failure_type == "disable_empty_files_in_log_dir": self.remove_dummy_file_in_log_dir(self.current_failure_node) elif self.failure_type == "dummy_file_in_log_dir": self._dummy_file_in_log_dir(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_dummy_file_in_log_dir": self.add_dummy_file_in_log_dir(self.current_failure_node) elif self.failure_type == "disable_dummy_file_in_log_dir": self.remove_dummy_file_in_log_dir(self.current_failure_node) elif self.failure_type == "limit_file_size_limit": self._enable_disable_limit_file_size_limit(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_limit_file_size_limit": self.enable_file_size_limit(self.current_failure_node) elif self.failure_type == "disable_limit_file_size_limit": self.disable_file_size_limit(self.current_failure_node) elif self.failure_type == "disk_readonly": self._enable_disable_disk_readonly(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_disk_readonly": self._enable_disk_readonly(self.current_failure_node) elif self.failure_type == "disable_disk_readonly": self._disable_disk_readonly(self.current_failure_node) elif self.failure_type == "stress_ram": self._enable_stress_ram(self.current_failure_node, self.failure_timeout) elif self.failure_type == "stress_cpu": self._enable_stress_cpu(self.current_failure_node, self.failure_timeout) elif self.failure_type == "network_delay": self._enable_disable_network_delay(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_network_delay": self.enable_network_delay(self.current_failure_node) elif self.failure_type == "disable_network_delay": self.delete_network_rule(self.current_failure_node) elif self.failure_type == "net_packet_loss": self._enable_disable_packet_loss(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_net_packet_loss": self.enable_packet_loss(self.current_failure_node) elif self.failure_type == "disable_net_packet_loss": self.delete_network_rule(self.current_failure_node) elif self.failure_type == "enable_firewall": self._enable_disable_firewall(self.current_failure_node, self.failure_timeout) if self.failure_type == "induce_enable_firewall": self._enable_firewall(self.current_failure_node) elif self.failure_type == "disable_firewall": self._disable_firewall(self.current_failure_node) elif self.failure_type == "restart_couchbase": self._restart_couchbase_server(self.current_failure_node, self.failure_timeout) elif self.failure_type == "stop_couchbase": self._stop_couchbase_server(self.current_failure_node) elif self.failure_type == "start_couchbase": self._start_couchbase_server(self.current_failure_node) elif self.failure_type == "restart_network": self._stop_restart_network(self.current_failure_node, self.failure_timeout) elif self.failure_type == "restart_machine": self._restart_machine(self.current_failure_node) elif self.failure_type == "stop_memcached": self._stop_memcached(self.current_failure_node) elif self.failure_type == "start_memcached": self._start_memcached(self.current_failure_node) elif self.failure_type == "kill_goxdcr": self._kill_goxdcr(self.current_failure_node) elif self.failure_type == "network_split": self._block_incoming_network_from_node(self.servers_to_fail[0], self.servers_to_fail[ self.itr + 1]) self.itr += 1 elif self.failure_type == "disk_failure": self._fail_recover_disk_failure(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_disk_failure": self._fail_disk(self.current_failure_node) elif self.failure_type == "disk_full": self._disk_full_recover_failure(self.current_failure_node, self.failure_timeout) elif self.failure_type == "shard_json_corruption": self.shard_json_corruption(self.current_failure_node) elif self.failure_type == "induce_disk_full": self._disk_full_failure(self.current_failure_node) elif self.failure_type == "recover_disk_failure": self._recover_disk(self.current_failure_node) elif self.failure_type == "recover_disk_full_failure": self._recover_disk_full_failure(self.current_failure_node) self.log.info("Start time = {}".format(time.ctime(self.start_time))) self.itr += 1 def _enable_disable_firewall(self, node, recover_time): self._enable_firewall(node) time.sleep(recover_time) self._disable_firewall(node) def _enable_disable_packet_loss(self, node, recover_time): self.enable_packet_loss(node) time.sleep(recover_time) self.delete_network_rule(node) def _enable_disable_limit_file_limits(self, node, recover_time): self.enable_file_limit(node) time.sleep(recover_time) self.disable_file_limit(node) def _enable_disable_limit_file_size_limit(self, node, recover_time): self.enable_file_size_limit(node) time.sleep(recover_time) self.disable_file_size_limit(node) def enable_file_size_limit(self, node): shell = RemoteMachineShellConnection(node) self.log.info("Updating file size limit to 10MB on {}".format(node)) shell.enable_file_size_limit() shell.disconnect() self.log.info("Enabled file size limit on {}".format(node)) def disable_file_size_limit(self, node): shell = RemoteMachineShellConnection(node) shell.disable_file_size_limit() shell.disconnect() self.log.info("disabled file size limit on {}".format(node)) def enable_file_limit(self, node): shell = RemoteMachineShellConnection(node) shell.enable_file_limit() shell.disconnect() self.log.info("Enabled file limit on {}".format(node)) def disable_file_limit(self, node): shell = RemoteMachineShellConnection(node) shell.disable_file_limit() shell.disconnect() self.log.info("disabled file limit on {}".format(node)) def _enable_disable_limit_file_limits_desc(self, node, recover_time): self.enable_file_limit_desc(node) time.sleep(recover_time) self.disable_file_limit_desc(node) def enable_file_limit_desc(self, node): shell = RemoteMachineShellConnection(node) shell.enable_file_limit_desc() shell.disconnect() self.log.info("Enabled file limit _desc on {}".format(node)) def disable_file_limit_desc(self, node): shell = RemoteMachineShellConnection(node) shell.disable_file_limit_desc() shell.disconnect() self.log.info("disabled file limit _desc on {}".format(node)) def _enable_disable_network_delay(self, node, recover_time): self.enable_network_delay(node) time.sleep(recover_time) self.delete_network_rule(node) def enable_network_delay(self, node): shell = RemoteMachineShellConnection(node) shell.enable_network_delay() shell.disconnect() self.log.info("Enabled network delay on {}".format(node)) def delete_network_rule(self, node): shell = RemoteMachineShellConnection(node) shell.delete_network_rule() shell.disconnect() self.log.info("Disabled packet loss on {}".format(node)) def enable_packet_loss(self, node): shell = RemoteMachineShellConnection(node) shell.enable_packet_loss() shell.disconnect() self.log.info("Enabled packet loss on {}".format(node)) def _enable_firewall(self, node): RemoteUtilHelper.enable_firewall(node) self.log.info("Enabled firewall on {}".format(node)) def _disable_firewall(self, node): shell = RemoteMachineShellConnection(node) shell.disable_firewall() def _restart_couchbase_server(self, node, failure_timeout): shell = RemoteMachineShellConnection(node) shell.restart_couchbase() shell.disconnect() self.log.info("Restarted the couchbase server on {}".format(node)) time.sleep(failure_timeout) def _stop_couchbase_server(self, node): shell = RemoteMachineShellConnection(node) shell.stop_couchbase() shell.disconnect() self.log.info("Stopped the couchbase server on {}".format(node)) def _start_couchbase_server(self, node): shell = RemoteMachineShellConnection(node) shell.start_couchbase() shell.disconnect() self.log.info("Started the couchbase server on {}".format(node)) def _enable_stress_cpu(self, node, stop_time): shell = RemoteMachineShellConnection(node) shell.cpu_stress(stop_time) shell.disconnect() self.log.info("cpu stressed for {0} sec on node {1}".format(stop_time, node)) def _enable_stress_ram(self, node, stop_time): shell = RemoteMachineShellConnection(node) shell.ram_stress(stop_time) shell.disconnect() self.log.info("ram stressed for {0} sec on node {1}".format(stop_time, node)) def _enable_disk_readonly(self, node): shell = RemoteMachineShellConnection(node) shell.enable_disk_readonly(self.disk_location) shell.disconnect() self.log.info("Dir {} made readonly on node {}".format(self.disk_location, node)) def _disable_disk_readonly(self, node): shell = RemoteMachineShellConnection(node) shell.disable_disk_readonly(self.disk_location) shell.disconnect() self.log.info("Dir {} made read/write on node {}".format(self.disk_location, node)) def _stop_restart_network(self, node, stop_time): shell = RemoteMachineShellConnection(node) shell.stop_network(stop_time) shell.disconnect() self.log.info("Stopped the network for {0} sec and restarted the " "network on {1}".format(stop_time, node)) def _restart_machine(self, node): shell = RemoteMachineShellConnection(node) command = "/sbin/reboot" shell.execute_command(command=command) def _stop_memcached(self, node): time.sleep(1) shell = RemoteMachineShellConnection(node) o, r = shell.stop_memcached() self.log.info("Killed memcached. {0} {1}".format(o, r)) def _start_memcached(self, node): shell = RemoteMachineShellConnection(node) o, r = shell.start_memcached() self.log.info("Started back memcached. {0} {1}".format(o, r)) shell.disconnect() def _kill_goxdcr(self, node): shell = RemoteMachineShellConnection(node) o, r = shell.kill_goxdcr() self.log.info("Killed goxdcr. {0} {1}".format(o, r)) def _block_incoming_network_from_node(self, node1, node2): shell = RemoteMachineShellConnection(node1) self.log.info("Adding {0} into iptables rules on {1}".format( node1.ip, node2.ip)) command = "iptables -A INPUT -s {0} -j DROP".format(node2.ip) shell.execute_command(command) self.start_time = time.time() def _fail_recover_disk_failure(self, node, recover_time): self._fail_disk(node) time.sleep(recover_time) self._recover_disk(node) def _fail_disk(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.unmount_partition(self.disk_location) success = True if output: for line in output: if self.disk_location in line: success = False if success: self.log.info("Unmounted disk at location : {0} on {1}".format(self.disk_location, node.ip)) self.start_time = time.time() else: self.log.info("Could not fail the disk at {0} on {1}".format(self.disk_location, node.ip)) self.state = FINISHED self.set_exception(Exception("Could not fail the disk at {0} on {1}".format(self.disk_location, node.ip))) self.set_result(False) def _recover_disk(self, node): shell = RemoteMachineShellConnection(node) o, r = shell.mount_partition_ext4(self.disk_location) for line in o: if self.disk_location in line: self.log.info("Mounted disk at location : {0} on {1}".format(self.disk_location, node.ip)) return self.set_exception(Exception("Could not mount disk at location {0} on {1}".format(self.disk_location, node.ip))) raise Exception() def _disk_full_recover_failure(self, node, recover_time): self._disk_full_failure(node) time.sleep(recover_time) self._recover_disk_full_failure(node) def _extra_files_in_log_dir(self, node, recover_time): self.add_extra_files_in_log_dir(node) time.sleep(recover_time) self.remove_extra_files_in_log_dir(node) def add_extra_files_in_log_dir(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.add_extra_files_index_log_dir(self.disk_location) if error: self.log.info(error) def remove_extra_files_in_log_dir(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.remove_extra_files_index_log_dir(self.disk_location) if error: self.log.info(error) def _dummy_file_in_log_dir(self, node, recover_time): self.add_dummy_file_in_log_dir(node) time.sleep(recover_time) self.remove_dummy_file_in_log_dir(node) def add_dummy_file_in_log_dir(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.add_dummy_file_index_log_dir(self.disk_location) if error: self.log.info(error) def shard_json_corruption(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.shard_json_corruption(self.disk_location) if error: self.log.info(error) def remove_dummy_file_in_log_dir(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.remove_dummy_file_index_log_dir(self.disk_location) if error: self.log.info(error) def _empty_file_in_log_dir(self, node, recover_time): self.add_empty_file_in_log_dir(node) time.sleep(recover_time) self.remove_dummy_file_in_log_dir(node) def add_empty_file_in_log_dir(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.add_empty_file_index_log_dir(self.disk_location) if error: self.log.info(error) def _enable_disable_disk_readonly(self, node, recover_time): self._enable_disk_readonly(node) time.sleep(recover_time) self._disable_disk_readonly(node) def _disk_full_failure(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.fill_disk_space(self.disk_location) success = False if output: for line in output: if self.disk_location in line: if "0 100% {0}".format(self.disk_location) in line: success = True if success: self.log.info("Filled up disk Space at {0} on {1}".format(self.disk_location, node.ip)) self.start_time = time.time() else: self.log.info("Could not fill the disk at {0} on {1}".format(self.disk_location, node.ip)) #self.state = FINISHED #self.set_exception(Exception("Could not fill the disk at {0} on {1}".format(self.disk_location, node.ip))) def _recover_disk_full_failure(self, node): shell = RemoteMachineShellConnection(node) delete_file = "{0}/disk-quota.ext3".format(self.disk_location) output, error = shell.execute_command("rm -f {0}".format(delete_file)) self.log.info(output) if error: self.log.info(error) def _check_for_autofailover_initiation(self, failed_over_node): rest = RestConnection(self.master) ui_logs = rest.get_logs(10) ui_logs_text = [t["text"] for t in ui_logs] ui_logs_time = [t["serverTime"] for t in ui_logs] expected_log = "Starting failing over ['ns_1@{}']".format( failed_over_node.ip) if expected_log in ui_logs_text: failed_over_time = ui_logs_time[ui_logs_text.index(expected_log)] return True, failed_over_time return False, None def _wait_for_autofailover_initiation(self, timeout): autofailover_initated = False while time.time() < timeout + self.start_time: autofailover_initated, failed_over_time = \ self._check_for_autofailover_initiation( self.current_failure_node) if autofailover_initated: end_time = self._get_mktime_from_server_time(failed_over_time) time_taken = end_time - self.start_time return autofailover_initated, time_taken return autofailover_initated, -1 def _get_mktime_from_server_time(self, server_time): time_format = "%Y-%m-%dT%H:%M:%S" server_time = server_time.split('.')[0] mk_time = time.mktime(time.strptime(server_time, time_format)) return mk_time def _rebalance(self): rest = RestConnection(self.master) nodes = rest.node_statuses() rest.rebalance(otpNodes=[node.id for node in nodes]) rebalance_progress = rest.monitorRebalance() if not rebalance_progress: self.set_result(False) self.state = FINISHED self.set_exception(Exception("Failed to rebalance after failover")) def _check_if_rebalance_in_progress(self, timeout): rest = RestConnection(self.master) end_time = time.time() + timeout while time.time() < end_time: try: rebalance_status, progress = \ rest._rebalance_status_and_progress() if rebalance_status == "running": continue elif rebalance_status is None and progress == 100: return False, -1 except RebalanceFailedException: ui_logs = rest.get_logs(10) ui_logs_text = [t["text"] for t in ui_logs] ui_logs_time = [t["serverTime"] for t in ui_logs] rebalace_failure_log = "Rebalance exited with reason" for ui_log in ui_logs_text: if rebalace_failure_log in ui_log: rebalance_failure_time = ui_logs_time[ ui_logs_text.index(ui_log)] failover_log = "Could not automatically fail over " \ "node ('ns_1@{}'). Rebalance is " \ "running.".format( self.current_failure_node.ip) if failover_log in ui_logs_text: return True, self._get_mktime_from_server_time( rebalance_failure_time) else: return False, -2 return False, -3 class AutoFailoverNodesFailureTask(Task): def __init__(self, master, servers_to_fail, failure_type, timeout, pause=0, expect_auto_failover=True, timeout_buffer=3, check_for_failover=True, failure_timers=None, disk_timeout=0, disk_location=None, disk_size=200): Task.__init__(self, "AutoFailoverNodesFailureTask") self.master = master self.servers_to_fail = servers_to_fail self.num_servers_to_fail = self.servers_to_fail.__len__() self.itr = 0 self.failure_type = failure_type self.timeout = timeout self.pause = pause self.expect_auto_failover = expect_auto_failover self.check_for_autofailover = check_for_failover self.start_time = 0 self.timeout_buffer = timeout_buffer self.current_failure_node = self.servers_to_fail[0] self.max_time_to_wait_for_failover = self.timeout + \ self.timeout_buffer + 200 self.disk_timeout = disk_timeout self.disk_location = disk_location self.disk_size = disk_size if failure_timers is None: failure_timers = [] self.failure_timers = failure_timers self.taskmanager = None self.rebalance_in_progress = False def execute(self, task_manager): self.taskmanager = task_manager rest = RestConnection(self.master) if rest._rebalance_progress_status() == "running": self.rebalance_in_progress = True while self.has_next() and not self.done(): next(self) if self.pause > 0 and self.pause > self.timeout: self.check(task_manager) if self.pause == 0 or 0 < self.pause < self.timeout: self.check(task_manager) self.state = FINISHED self.set_result(True) def check(self, task_manager): if not self.check_for_autofailover: self.state = EXECUTING return rest = RestConnection(self.master) max_timeout = self.timeout + self.timeout_buffer + self.disk_timeout if self.start_time == 0: message = "Did not inject failure in the system." rest.print_UI_logs(10) self.log.error(message) self.state = FINISHED self.set_result(False) self.set_exception(AutoFailoverException(message)) if self.rebalance_in_progress: status, stop_time = self._check_if_rebalance_in_progress(120) if not status: if stop_time == -1: message = "Rebalance already completed before failover " \ "of node" self.log.error(message) self.state = FINISHED self.set_result(False) self.set_exception(AutoFailoverException(message)) elif stop_time == -2: message = "Rebalance failed but no failed autofailover " \ "message was printed in logs" self.log.warning(message) else: message = "Rebalance not failed even after 2 minutes " \ "after node failure." self.log.error(message) rest.print_UI_logs(10) self.state = FINISHED self.set_result(False) self.set_exception(AutoFailoverException(message)) else: self.start_time = stop_time autofailover_initiated, time_taken = \ self._wait_for_autofailover_initiation( self.max_time_to_wait_for_failover) if self.expect_auto_failover: if autofailover_initiated: if time_taken < max_timeout + 1: self.log.info("Autofailover of node {0} successfully " "initiated in {1} sec".format( self.current_failure_node.ip, time_taken)) rest.print_UI_logs(10) self.state = EXECUTING else: message = "Autofailover of node {0} was initiated after " \ "the timeout period. Expected timeout: {1} " \ "Actual time taken: {2}".format( self.current_failure_node.ip, self.timeout, time_taken) self.log.error(message) rest.print_UI_logs(10) self.state = FINISHED self.set_result(False) self.set_exception(AutoFailoverException(message)) else: message = "Autofailover of node {0} was not initiated after " \ "the expected timeout period of {1}".format( self.current_failure_node.ip, self.timeout) rest.print_UI_logs(10) self.log.error(message) self.state = FINISHED self.set_result(False) self.set_exception(AutoFailoverException(message)) else: if autofailover_initiated: message = "Node {0} was autofailed over but no autofailover " \ "of the node was expected".format( self.current_failure_node.ip) rest.print_UI_logs(10) self.log.error(message) self.state = FINISHED self.set_result(False) self.set_exception(AutoFailoverException(message)) else: self.log.info("Node not autofailed over as expected") rest.print_UI_logs(10) self.state = EXECUTING def has_next(self): return self.itr < self.num_servers_to_fail def __next__(self): if self.pause != 0: time.sleep(self.pause) if self.pause > self.timeout and self.itr != 0: rest = RestConnection(self.master) status = rest.reset_autofailover() self._rebalance() if not status: self.state = FINISHED self.set_result(False) self.set_exception(Exception("Reset of autofailover " "count failed")) self.current_failure_node = self.servers_to_fail[self.itr] self.log.info("before failure time: {}".format(time.ctime(time.time()))) if self.failure_type == "enable_firewall": self._enable_firewall(self.current_failure_node) elif self.failure_type == "disable_firewall": self._disable_firewall(self.current_failure_node) elif self.failure_type == "restart_couchbase": self._restart_couchbase_server(self.current_failure_node) elif self.failure_type == "stop_couchbase": self._stop_couchbase_server(self.current_failure_node) elif self.failure_type == "start_couchbase": self._start_couchbase_server(self.current_failure_node) elif self.failure_type == "restart_network": self._stop_restart_network(self.current_failure_node, self.timeout + self.timeout_buffer + 30) elif self.failure_type == "restart_machine": self._restart_machine(self.current_failure_node) elif self.failure_type == "stop_indexer": self._stop_indexer(self.current_failure_node) elif self.failure_type == "start_indexer": self._start_indexer(self.current_failure_node) elif self.failure_type == "block_indexer_port": self._block_indexer_port(self.current_failure_node) elif self.failure_type == "resume_indexer_port": self._resume_indexer_port(self.current_failure_node) elif self.failure_type == "stop_memcached": self._stop_memcached(self.current_failure_node) elif self.failure_type == "start_memcached": self._start_memcached(self.current_failure_node) elif self.failure_type == "network_split": self._block_incoming_network_from_node(self.servers_to_fail[0], self.servers_to_fail[ self.itr + 1]) self.itr += 1 elif self.failure_type == "disk_failure": self._fail_disk(self.current_failure_node) elif self.failure_type == "disk_full": self._disk_full_failure(self.current_failure_node) elif self.failure_type == "recover_disk_failure": self._recover_disk(self.current_failure_node) elif self.failure_type == "recover_disk_full_failure": self._recover_disk_full_failure(self.current_failure_node) self.log.info("Start time = {}".format(time.ctime(self.start_time))) self.itr += 1 def _enable_firewall(self, node): node_failure_timer = self.failure_timers[self.itr] time.sleep(1) RemoteUtilHelper.enable_firewall(node) self.log.info("Enabled firewall on {}".format(node)) node_failure_timer.result() self.start_time = node_failure_timer.start_time def _disable_firewall(self, node): shell = RemoteMachineShellConnection(node) shell.disable_firewall() def _restart_couchbase_server(self, node): node_failure_timer = self.failure_timers[self.itr] time.sleep(1) shell = RemoteMachineShellConnection(node) shell.restart_couchbase() shell.disconnect() self.log.info("Restarted the couchbase server on {}".format(node)) node_failure_timer.result() self.start_time = node_failure_timer.start_time def _stop_couchbase_server(self, node): node_failure_timer = self.failure_timers[self.itr] time.sleep(1) shell = RemoteMachineShellConnection(node) shell.stop_couchbase() shell.disconnect() self.log.info("Stopped the couchbase server on {}".format(node)) node_failure_timer.result() self.start_time = node_failure_timer.start_time def _start_couchbase_server(self, node): shell = RemoteMachineShellConnection(node) shell.start_couchbase() shell.disconnect() self.log.info("Started the couchbase server on {}".format(node)) def _stop_restart_network(self, node, stop_time): node_failure_timer = self.failure_timers[self.itr] time.sleep(1) shell = RemoteMachineShellConnection(node) shell.stop_network(stop_time) shell.disconnect() self.log.info("Stopped the network for {0} sec and restarted the " "network on {1}".format(stop_time, node)) node_failure_timer.result() self.start_time = node_failure_timer.start_time def _restart_machine(self, node): node_failure_timer = self.failure_timers[self.itr] time.sleep(1) shell = RemoteMachineShellConnection(node) command = "/sbin/reboot" shell.execute_command(command=command) node_failure_timer.result() self.start_time = node_failure_timer.start_time def _block_indexer_port(self, node): shell = RemoteMachineShellConnection(node) self.log.info(f"Blocking port 9103 and 9105 on {node}") shell.execute_command("iptables -A INPUT -p tcp --destination-port 9103 -j DROP") shell.execute_command("iptables -A OUTPUT -p tcp --destination-port 9103 -j DROP") shell.execute_command("iptables -A INPUT -p tcp --destination-port 9105 -j DROP") shell.execute_command("iptables -A OUTPUT -p tcp --destination-port 9105 -j DROP") def _resume_indexer_port(self, node): shell = RemoteMachineShellConnection(node) self.log.info(f"Resuming port 9103 and 9105 on {node}") shell.execute_command("iptables -D INPUT -p tcp --destination-port 9103 -j DROP") shell.execute_command("iptables -D OUTPUT -p tcp --destination-port 9103 -j DROP") shell.execute_command("iptables -D INPUT -p tcp --destination-port 9105 -j DROP") shell.execute_command("iptables -D OUTPUT -p tcp --destination-port 9105 -j DROP") def _stop_indexer(self, node): node_failure_timer = self.failure_timers[self.itr] time.sleep(1) shell = RemoteMachineShellConnection(node) o, r = shell.stop_indexer() self.log.info("Killed indexer. {0} {1}".format(o, r)) node_failure_timer.result() self.start_time = node_failure_timer.start_time def _start_indexer(self, node): shell = RemoteMachineShellConnection(node) o, r = shell.start_indexer() self.log.info("Started back indexer. {0} {1}".format(o, r)) shell.disconnect() def _stop_memcached(self, node): node_failure_timer = self.failure_timers[self.itr] time.sleep(1) shell = RemoteMachineShellConnection(node) o, r = shell.stop_memcached() self.log.info("Killed memcached. {0} {1}".format(o, r)) node_failure_timer.result() self.start_time = node_failure_timer.start_time def _start_memcached(self, node): shell = RemoteMachineShellConnection(node) o, r = shell.start_memcached() self.log.info("Started back memcached. {0} {1}".format(o, r)) shell.disconnect() def _block_incoming_network_from_node(self, node1, node2): shell = RemoteMachineShellConnection(node1) self.log.info("Adding {0} into iptables rules on {1}".format( node1.ip, node2.ip)) command = "iptables -A INPUT -s {0} -j DROP".format(node2.ip) shell.execute_command(command) self.start_time = time.time() def _fail_disk(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.unmount_partition(self.disk_location) success = True if output: for line in output: if self.disk_location in line: success = False if success: self.log.info("Unmounted disk at location : {0} on {1}".format(self.disk_location, node.ip)) self.start_time = time.time() else: self.log.info("Could not fail the disk at {0} on {1}".format(self.disk_location, node.ip)) self.state = FINISHED self.set_exception(Exception("Could not fail the disk at {0} on {1}".format(self.disk_location, node.ip))) self.set_result(False) def _recover_disk(self, node): shell = RemoteMachineShellConnection(node) o, r = shell.mount_partition(self.disk_location) for line in o: if self.disk_location in line: self.log.info("Mounted disk at location : {0} on {1}".format(self.disk_location, node.ip)) return self.set_exception(Exception("Could not mount disk at location {0} on {1}".format(self.disk_location, node.ip))) raise Exception() def _disk_full_failure(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.fill_disk_space(self.disk_location, self.disk_size) success = False if output: for line in output: if self.disk_location in line: if "0 100% {0}".format(self.disk_location) in line: success = True if success: self.log.info("Filled up disk Space at {0} on {1}".format(self.disk_location, node.ip)) self.start_time = time.time() else: self.log.info("Could not fill the disk at {0} on {1}".format(self.disk_location, node.ip)) self.state = FINISHED self.set_exception(Exception("Could not fill the disk at {0} on {1}".format(self.disk_location, node.ip))) def _recover_disk_full_failure(self, node): shell = RemoteMachineShellConnection(node) delete_file = "{0}/disk-quota.ext3".format(self.disk_location) output, error = shell.execute_command("rm -f {0}".format(delete_file)) self.log.info(output) if error: self.log.info(error) def _check_for_autofailover_initiation(self, failed_over_node): rest = RestConnection(self.master) ui_logs = rest.get_logs(10) ui_logs_text = [t["text"] for t in ui_logs] ui_logs_time = [t["serverTime"] for t in ui_logs] expected_log = "Starting failing over ['ns_1@{}']".format( failed_over_node.ip) if expected_log in ui_logs_text: failed_over_time = ui_logs_time[ui_logs_text.index(expected_log)] return True, failed_over_time return False, None def _wait_for_autofailover_initiation(self, timeout): autofailover_initated = False while time.time() < timeout + self.start_time: autofailover_initated, failed_over_time = \ self._check_for_autofailover_initiation( self.current_failure_node) if autofailover_initated: end_time = self._get_mktime_from_server_time(failed_over_time) time_taken = end_time - self.start_time return autofailover_initated, time_taken return autofailover_initated, -1 def _get_mktime_from_server_time(self, server_time): time_format = "%Y-%m-%dT%H:%M:%S" server_time = server_time.split('.')[0] mk_time = time.mktime(time.strptime(server_time, time_format)) return mk_time def _rebalance(self): rest = RestConnection(self.master) nodes = rest.node_statuses() rest.rebalance(otpNodes=[node.id for node in nodes]) rebalance_progress = rest.monitorRebalance() if not rebalance_progress: self.set_result(False) self.state = FINISHED self.set_exception(Exception("Failed to rebalance after failover")) def _check_if_rebalance_in_progress(self, timeout): rest = RestConnection(self.master) end_time = time.time() + timeout while time.time() < end_time: try: rebalance_status, progress = \ rest._rebalance_status_and_progress() if rebalance_status == "running": continue elif rebalance_status is None and progress == 100: return False, -1 except RebalanceFailedException: ui_logs = rest.get_logs(10) ui_logs_text = [t["text"] for t in ui_logs] ui_logs_time = [t["serverTime"] for t in ui_logs] rebalace_failure_log = "Rebalance exited with reason" for ui_log in ui_logs_text: if rebalace_failure_log in ui_log: rebalance_failure_time = ui_logs_time[ ui_logs_text.index(ui_log)] failover_log = "Could not automatically fail over " \ "node ('ns_1@{}'). Rebalance is " \ "running.".format( self.current_failure_node.ip) if failover_log in ui_logs_text: return True, self._get_mktime_from_server_time( rebalance_failure_time) else: return False, -2 return False, -3 class NodeDownTimerTask(Task): def __init__(self, node, port=None, timeout=300): Task.__init__(self, "NodeDownTimerTask") self.log.info("Initializing NodeDownTimerTask") self.node = node self.port = port self.timeout = timeout self.start_time = 0 def execute(self, task_manager): self.log.info("Starting execution of NodeDownTimerTask") end_task = time.time() + self.timeout while not self.done() and time.time() < end_task: if not self.port: try: self.start_time = time.time() response = os.system("ping -c 1 {} > /dev/null".format( self.node)) if response != 0: self.log.info("Injected failure in {}. Caught " "due to ping".format(self.node)) self.state = FINISHED self.set_result(True) break except Exception as e: self.log.warning("Unexpected exception caught {" "}".format(e)) self.state = FINISHED self.set_result(True) break try: self.start_time = time.time() socket.socket().connect(("{}".format(self.node), 8091)) socket.socket().close() socket.socket().connect(("{}".format(self.node), 11210)) socket.socket().close() except socket.error: self.log.info("Injected failure in {}. Caught due " "to ports".format(self.node)) self.state = FINISHED self.set_result(True) break else: try: self.start_time = time.time() socket.socket().connect(("{}".format(self.node), int(self.port))) socket.socket().close() socket.socket().connect(("{}".format(self.node), 11210)) socket.socket().close() except socket.error: self.log.info("Injected failure in {}".format(self.node)) self.state = FINISHED self.set_result(True) break if time.time() >= end_task: self.state = FINISHED self.set_result(False) self.log.info("Could not inject failure in {}".format(self.node)) def check(self, task_manager): pass class NodeMonitorsAnalyserTask(Task): def __init__(self, node, stop=False): Task.__init__(self, "NodeMonitorAnalyzerTask") self.command = "dict:to_list(node_status_analyzer:get_nodes())" self.master = node self.rest = RestConnection(self.master) self.stop = stop def execute(self, task_manager): while not self.done() and not self.stop: self.status, self.content = self.rest.diag_eval(self.command, print_log=False) self.state = CHECKING def check(self, task_manager): if self.status and self.content: self.log.info("NodeStatus: {}".format(self.content)) if not self.master.ip in self.content: self.set_result(False) self.state = FINISHED self.set_exception(Exception("Node status monitors does not " "contain the node status")) return time.sleep(1) self.state = EXECUTING else: raise Exception("Monitors not working correctly") # Runs java sdk client directly on slave class SDKLoadDocumentsTask(Task): def __init__(self, server, bucket, sdk_docloader): Task.__init__(self, "SDKLoadDocumentsTask") self.server = server if isinstance(bucket, Bucket): self.bucket = bucket.name else: self.bucket = bucket self.sdk_docloader = sdk_docloader def execute_for_collection(self, collection, start_seq_num_shift=0): import subprocess command = f"java -jar java_sdk_client/collections/target/javaclient/javaclient.jar " \ f"-i {self.server.ip} -u {self.sdk_docloader.username} -p {self.sdk_docloader.password} -b {self.bucket} " \ f"-s {self.sdk_docloader.scope} -c {collection} " \ f"-n {self.sdk_docloader.num_ops} -pc {self.sdk_docloader.percent_create} -pu {self.sdk_docloader.percent_update} " \ f"-pd {self.sdk_docloader.percent_delete} -l {self.sdk_docloader.load_pattern} " \ f"-dsn {self.sdk_docloader.start_seq_num + start_seq_num_shift} -dpx {self.sdk_docloader.key_prefix} -dt {self.sdk_docloader.json_template} " \ f"-de {self.sdk_docloader.doc_expiry} -ds {self.sdk_docloader.doc_size} -ac {self.sdk_docloader.all_collections} " \ f"-st {self.sdk_docloader.start+start_seq_num_shift} -en {self.sdk_docloader.end+start_seq_num_shift} -o {self.sdk_docloader.output} -sd {self.sdk_docloader.shuffle_docs} --secure {self.sdk_docloader.secure}" if self.sdk_docloader.es_compare: command = command + " -es true -es_host " + str(self.sdk_docloader.es_host) + " -es_port " + str( self.sdk_docloader.es_port) + \ " -es_login " + str(self.sdk_docloader.es_login) + " -es_password " + str( self.sdk_docloader.es_password) if self.sdk_docloader.op_type == "update": arr_fields_to_update = self.sdk_docloader.fields_to_update if self.sdk_docloader.fields_to_update else "" if len(arr_fields_to_update) > 0: command = command + " -fu " command = command + ",".join(arr_fields_to_update) self.log.info(command) try: proc = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) out = proc.communicate(timeout=self.sdk_docloader.timeout) if self.sdk_docloader.get_sdk_logs: self.sdk_docloader.set_sdk_results(out) self.log.info(out[0].decode("utf-8")) if proc.returncode != 0: raise Exception("Exception in java sdk client to {}:{}\n{}".format(self.server.ip, self.bucket, out)) except Exception as e: proc.terminate() self.state = FINISHED self.set_exception(e) proc.terminate() self.state = FINISHED self.set_result(True) def execute(self, task_manager): if type(self.sdk_docloader.collection) is list: start_seq_num_shift = 0 for c in self.sdk_docloader.collection: self.execute_for_collection(c, start_seq_num_shift) start_seq_num_shift = start_seq_num_shift + self.sdk_docloader.upd_del_shift else: self.execute_for_collection(self.sdk_docloader.collection) self.check(task_manager) #TODO additional sleep to let ES finish with docs indexing, should be replaced with something more intelligent. time.sleep(30) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) # Runs java sdk client on a docker container on slave class DockerSDKLoadDocumentsTask(Task): def __init__(self, server, bucket, sdk_docloader, pause_secs, timeout_secs): Task.__init__(self, "SDKLoadDocumentsTask") self.server = server if isinstance(bucket, Bucket): self.bucket = bucket.name else: self.bucket = bucket self.params = sdk_docloader self.pause_secs = pause_secs self.timeout_secs = timeout_secs from lib.collection.collections_dataloader import JavaSDKClient self.javasdkclient = JavaSDKClient(self.server, self.bucket, self.params) def execute(self, task_manager): try: self.javasdkclient.do_ops() self.state = CHECKING task_manager.schedule(self) except Exception as e: self.state = FINISHED self.set_exception(Exception("Exception while loading data to {}:{}" .format(self.server.ip, self.bucket))) finally: self.javasdkclient.cleanup() def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) #TODO: # input params to include,exclude keywords, # populate dictionary {node:matches} in setUp() # call LogScanTask in basetestcase tearDown() and diff dict # add sensitive data patterns # pretty print matches class LogScanTask(Task): def __init__(self, server, file_prefix): Task.__init__(self, "log_scan_task") self.server = server self.log_scan_file_name = f'{self.server.ip}_{file_prefix}' from lib.log_scanner import LogScanner exclude_keywords = TestInputSingleton.input.param("exclude_keywords", None) skip_security_scan = TestInputSingleton.input.param("skip_security_scan", False) self.log_scanner = LogScanner(server=self.server, exclude_keywords=exclude_keywords, skip_security_scan=skip_security_scan) def execute(self, task_manager): try: # Scan logs corresponding to node services matches = self.log_scanner.scan() target = open(self.log_scan_file_name, 'w+') target.write(str(matches)) target.close() self.state = CHECKING task_manager.schedule(self) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self)
import copy import json import math import os import random import re import socket import string import time import traceback import sys from functools import cmp_to_key from http.client import IncompleteRead from multiprocessing import Process, Manager, Semaphore from threading import Thread import crc32 import logger import testconstants from cb_tools.cbstats import Cbstats from remote.remote_util import RemoteMachineShellConnection from collection.collections_rest_client import CollectionsRest from collection.collections_stats import CollectionsStats from couchbase_helper.document import DesignDocument from couchbase_helper.documentgenerator import BatchedDocumentGenerator from couchbase_helper.stats_tools import StatsCommon from deepdiff import DeepDiff from mc_bin_client import MemcachedError from membase.api.exception import BucketCreationException from membase.api.exception import N1QLQueryException, DropIndexException, CreateIndexException, \ DesignDocCreationException, QueryViewException, ReadDocumentException, RebalanceFailedException, \ GetBucketInfoFailed, CompactViewFailed, SetViewInfoNotFound, FailoverFailedException, \ ServerUnavailableException, BucketFlushFailed, CBRecoveryFailedException, BucketCompactionException, \ AutoFailoverException,NodesFailureException, ServerAlreadyJoinedException from membase.api.rest_client import RestConnection, Bucket, RestHelper from membase.helper.bucket_helper import BucketOperationHelper from memcacheConstants import ERR_NOT_FOUND, NotFoundError from memcached.helper.data_helper import MemcachedClientHelper from memcached.helper.kvstore import KVStore from remote.remote_util import RemoteMachineShellConnection, RemoteUtilHelper from tasks.future import Future from testconstants import MIN_KV_QUOTA, INDEX_QUOTA, FTS_QUOTA, COUCHBASE_FROM_4DOT6, \ THROUGHPUT_CONCURRENCY, ALLOW_HTP, CBAS_QUOTA, CLUSTER_QUOTA_RATIO from TestInput import TestInputServer, TestInputSingleton try: CHECK_FLAG = False if (TestInputSingleton.input.param("testrunner_client", None) == testconstants.PYTHON_SDK) or \ ((testconstants.TESTRUNNER_CLIENT in list(os.environ.keys())) and os.environ[testconstants.TESTRUNNER_CLIENT] == testconstants.PYTHON_SDK): try: from sdk_client import SDKSmartClient as VBucketAwareMemcached from sdk_client import SDKBasedKVStoreAwareSmartClient as KVStoreAwareSmartClient except: from sdk_client3 import SDKSmartClient as VBucketAwareMemcached from sdk_client3 import SDKBasedKVStoreAwareSmartClient as KVStoreAwareSmartClient if (TestInputSingleton.input.param("enable_sdk_logging", False)): import logging import couchbase logging.basicConfig(stream=sys.stderr, level=logging.INFO) couchbase.enable_logging() else: CHECK_FLAG = True from memcached.helper.data_helper import VBucketAwareMemcached, KVStoreAwareSmartClient except Exception as e: CHECK_FLAG = False try: from sdk_client import SDKSmartClient as VBucketAwareMemcached from sdk_client import SDKBasedKVStoreAwareSmartClient as KVStoreAwareSmartClient except: from sdk_client3 import SDKSmartClient as VBucketAwareMemcached from sdk_client3 import SDKBasedKVStoreAwareSmartClient as KVStoreAwareSmartClient # TODO: Setup stacktracer # TODO: Needs "easy_install pygments" # import stacktracer # stacktracer.trace_start("trace.html",interval=30,auto=True) # Set auto flag to always update file! CONCURRENCY_LOCK = Semaphore(THROUGHPUT_CONCURRENCY) PENDING = 'PENDING' EXECUTING = 'EXECUTING' CHECKING = 'CHECKING' FINISHED = 'FINISHED' class Task(Future): def __init__(self, name): Future.__init__(self) self.log = logger.Logger.get_logger() self.state = PENDING self.name = name self.cancelled = False self.retries = 0 self.res = None def step(self, task_manager): if not self.done(): if self.state == PENDING: self.state = EXECUTING task_manager.schedule(self) elif self.state == EXECUTING: self.execute(task_manager) elif self.state == CHECKING: self.check(task_manager) elif self.state != FINISHED: raise Exception("Bad State in {0}: {1}".format(self.name, self.state)) def execute(self, task_manager): raise NotImplementedError def check(self, task_manager): raise NotImplementedError def set_unexpected_exception(self, e, suffix=""): self.log.error("Unexpected exception [{0}] caught".format(e) + suffix) self.log.error(''.join(traceback.format_stack())) self.set_exception(e) class NodeInitializeTask(Task): def __init__(self, server, disabled_consistent_view=None, rebalanceIndexWaitingDisabled=None, rebalanceIndexPausingDisabled=None, maxParallelIndexers=None, maxParallelReplicaIndexers=None, port=None, quota_percent=None, index_quota_percent=None, services=None, gsi_type='forestdb'): Task.__init__(self, "node_init_task") self.server = server self.port = port or server.port self.quota = 0 self.index_quota = 0 self.index_quota_percent = index_quota_percent self.quota_percent = quota_percent self.disable_consistent_view = disabled_consistent_view self.rebalanceIndexWaitingDisabled = rebalanceIndexWaitingDisabled self.rebalanceIndexPausingDisabled = rebalanceIndexPausingDisabled self.maxParallelIndexers = maxParallelIndexers self.maxParallelReplicaIndexers = maxParallelReplicaIndexers self.services = services self.gsi_type = gsi_type def execute(self, task_manager): try: rest = RestConnection(self.server) except Exception as error: self.state = FINISHED print("debuging hanging issue task 127" + str(error)) self.set_exception(error) return self.log.info("server: %s, nodes/self ", self.server) info = Future.wait_until(lambda: rest.get_nodes_self(), lambda x: x.memoryTotal > 0 or x.storageTotalRam > 0, timeout_secs=60, interval_time=0.1, exponential_backoff=False) self.log.info(" %s", info.__dict__) username = self.server.rest_username password = self.server.rest_password if int(info.port) in range(9091, 9991): self.state = FINISHED self.set_result(True) return self.quota = int(info.mcdMemoryReserved * CLUSTER_QUOTA_RATIO) if self.index_quota_percent: self.index_quota = int((info.mcdMemoryReserved * CLUSTER_QUOTA_RATIO) * \ self.index_quota_percent // 100) rest.set_service_memoryQuota(service='indexMemoryQuota', username=username, \ password=password, memoryQuota=self.index_quota) if self.quota_percent: self.quota = int(info.mcdMemoryReserved * self.quota_percent / 100) """ Adjust KV RAM to correct value when there is INDEX and FTS services added to node from Watson """ index_quota = INDEX_QUOTA cluster_setting = rest.cluster_status() fts_quota = FTS_QUOTA if cluster_setting: if cluster_setting["ftsMemoryQuota"] and \ int(cluster_setting["ftsMemoryQuota"]) >= 256: fts_quota = int(cluster_setting["ftsMemoryQuota"]) kv_quota = int(info.mcdMemoryReserved * CLUSTER_QUOTA_RATIO) if self.index_quota_percent: index_quota = self.index_quota if not self.quota_percent: set_services = copy.deepcopy(self.services) if set_services is None: set_services = ["kv"] # info = rest.get_nodes_self() # cb_version = info.version[:5] # if cb_version in COUCHBASE_FROM_VERSION_4: if "index" in set_services: self.log.info("quota for index service will be %s MB" % (index_quota)) kv_quota -= index_quota self.log.info("set index quota to node %s " % self.server.ip) rest.set_service_memoryQuota(service='indexMemoryQuota', memoryQuota=index_quota) if "fts" in set_services: self.log.info("quota for fts service will be %s MB" % (fts_quota)) kv_quota -= fts_quota self.log.info("set both index and fts quota at node %s " % self.server.ip) rest.set_service_memoryQuota(service='ftsMemoryQuota', memoryQuota=fts_quota) if "cbas" in set_services: self.log.info("quota for cbas service will be %s MB" % (CBAS_QUOTA)) kv_quota -= CBAS_QUOTA rest.set_service_memoryQuota(service="cbasMemoryQuota", memoryQuota=CBAS_QUOTA) if kv_quota < MIN_KV_QUOTA: raise Exception("KV RAM needs to be more than %s MB" " at node %s" % (MIN_KV_QUOTA, self.server.ip)) if kv_quota < int(self.quota): self.quota = kv_quota rest.init_cluster_memoryQuota(username, password, self.quota) if self.services: status = rest.init_node_services(username=username, password=password, \ port=self.port, hostname=self.server.ip, \ services=self.services) if not status: self.state = FINISHED self.set_exception(Exception('unable to set services for server %s' \ % (self.server.ip))) return if self.disable_consistent_view is not None: rest.set_reb_cons_view(self.disable_consistent_view) if self.rebalanceIndexWaitingDisabled is not None: rest.set_reb_index_waiting(self.rebalanceIndexWaitingDisabled) if self.rebalanceIndexPausingDisabled is not None: rest.set_rebalance_index_pausing(self.rebalanceIndexPausingDisabled) if self.maxParallelIndexers is not None: rest.set_max_parallel_indexers(self.maxParallelIndexers) if self.maxParallelReplicaIndexers is not None: rest.set_max_parallel_replica_indexers(self.maxParallelReplicaIndexers) if self.server.internal_ip: rest.set_alternate_address(self.server.ip) rest.init_cluster(username, password, self.port) remote_shell = RemoteMachineShellConnection(self.server) remote_shell.enable_diag_eval_on_non_local_hosts() remote_shell.disconnect() if rest.is_cluster_compat_mode_greater_than(4.0): if self.gsi_type == "plasma": if (not rest.is_cluster_compat_mode_greater_than(5.0)) or (not rest.is_enterprise_edition()): rest.set_indexer_storage_mode(username, password, "forestdb") else: rest.set_indexer_storage_mode(username, password, self.gsi_type) else: rest.set_indexer_storage_mode(username, password, self.gsi_type) self.server.port = self.port try: rest = RestConnection(self.server) except Exception as error: self.state = FINISHED print("debuging hanging issue task 230" + str(error)) self.set_exception(error) return info = rest.get_nodes_self() if info is None: self.state = FINISHED self.set_exception( Exception('unable to get information on a server %s, it is available?' % (self.server.ip))) return self.state = CHECKING task_manager.schedule(self) def check(self, task_manager): self.state = FINISHED self.set_result(self.quota) class BucketCreateTask(Task): def __init__(self, bucket_params): Task.__init__(self, "bucket_create_task") self.server = bucket_params['server'] self.bucket = bucket_params['bucket_name'] self.alt_addr = TestInputSingleton.input.param("alt_addr", False) self.replicas = bucket_params['replicas'] self.port = bucket_params['port'] self.size = bucket_params['size'] self.password = bucket_params['password'] self.bucket_type = bucket_params['bucket_type'] self.enable_replica_index = bucket_params['enable_replica_index'] self.eviction_policy = bucket_params['eviction_policy'] self.lww = bucket_params['lww'] self.storageBackend = bucket_params['bucket_storage'] if 'maxTTL' in bucket_params: self.maxttl = bucket_params['maxTTL'] else: self.maxttl = 0 if 'compressionMode' in bucket_params: self.compressionMode = bucket_params['compressionMode'] else: self.compressionMode = 'passive' self.flush_enabled = bucket_params['flush_enabled'] if bucket_params['bucket_priority'] is None or bucket_params['bucket_priority'].lower() is 'low': self.bucket_priority = 3 else: self.bucket_priority = 8 def execute(self, task_manager): try: rest = RestConnection(self.server) except Exception as error: self.state = FINISHED print("debuging hanging issue task 279" + str(error)) self.set_exception(error) return info = rest.get_nodes_self() if self.size is None or int(self.size) <= 0: self.size = info.memoryQuota * 2 // 3 if int(info.port) in range(9091, 9991): try: self.port = info.port rest.create_bucket(bucket=self.bucket) self.state = CHECKING task_manager.schedule(self) except Exception as e: self.state = FINISHED self.set_exception(e) return version = rest.get_nodes_self().version try: if float(version[:2]) >= 3.0 and self.bucket_priority is not None: rest.create_bucket(bucket=self.bucket, ramQuotaMB=self.size, replicaNumber=self.replicas, proxyPort=self.port, bucketType=self.bucket_type, replica_index=self.enable_replica_index, flushEnabled=self.flush_enabled, evictionPolicy=self.eviction_policy, threadsNumber=self.bucket_priority, lww=self.lww, maxTTL=self.maxttl, compressionMode=self.compressionMode, storageBackend=self.storageBackend) else: rest.create_bucket(bucket=self.bucket, ramQuotaMB=self.size, replicaNumber=self.replicas, proxyPort=self.port, bucketType=self.bucket_type, replica_index=self.enable_replica_index, flushEnabled=self.flush_enabled, evictionPolicy=self.eviction_policy, lww=self.lww, maxTTL=self.maxttl, compressionMode=self.compressionMode) self.state = CHECKING task_manager.schedule(self) except BucketCreationException as e: self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): try: if self.bucket_type == 'memcached' or int(self.port) in range(9091, 9991): self.set_result(True) self.state = FINISHED return if BucketOperationHelper.wait_for_memcached(self.server, self.bucket): self.log.info("bucket '{0}' was created with per node RAM quota: {1}".format(self.bucket, self.size)) self.set_result(True) self.state = FINISHED return else: self.log.warning("vbucket map not ready after try {0}".format(self.retries)) if self.retries >= 5: self.set_result(False) self.state = FINISHED return except Exception as e: self.log.error("Unexpected error: %s" % str(e)) self.log.warning("vbucket map not ready after try {0}".format(self.retries)) if self.retries >= 5: self.state = FINISHED self.set_exception(e) self.retries = self.retries + 1 task_manager.schedule(self) class BucketDeleteTask(Task): def __init__(self, server, bucket="default"): Task.__init__(self, "bucket_delete_task") self.server = server self.bucket = bucket def execute(self, task_manager): try: rest = RestConnection(self.server) if rest.delete_bucket(self.bucket): self.state = CHECKING task_manager.schedule(self) else: self.log.info(StatsCommon.get_stats([self.server], self.bucket, "timings")) self.state = FINISHED self.set_result(False) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.log.info(StatsCommon.get_stats([self.server], self.bucket, "timings")) self.set_unexpected_exception(e) def check(self, task_manager): try: rest = RestConnection(self.server) if BucketOperationHelper.wait_for_bucket_deletion(self.bucket, rest, 200): self.set_result(True) else: self.set_result(False) self.state = FINISHED # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.log.info(StatsCommon.get_stats([self.server], self.bucket, "timings")) self.set_unexpected_exception(e) class CollectionCreateTask(Task): def __init__(self, server, bucket, scope, collection, params=None): Task.__init__(self, "collection_create_task") self.server = server self.bucket_name = bucket self.scope_name = scope self.collection_name = collection self.collection_params = params def execute(self, task_manager): try: rest = RestConnection(self.server) except ServerUnavailableException as error: self.state = FINISHED self.set_exception(error) return try: rest.create_collection(bucket=self.bucket_name, scope=self.scope_name, collection=self.collection_name, params=self.collection_params) self.state = CHECKING task_manager.schedule(self) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) class ConcurrentIndexCreateTask(Task): def __init__(self, server, bucket, scope, collection, query_definitions=None, IndexTrackingObject=None, n1ql_helper=None, num_indexes=1, defer_build="", itr=0, expected_failure=[], query_def_group="plasma_test"): Task.__init__(self, "collection_create_task") self.server = server self.bucket_name = bucket self.scope_name = scope self.collection_name = collection self.query_definitions = query_definitions self.test_fail = False self.index_tracking_obj = IndexTrackingObject self.n1ql_helper=n1ql_helper self.num_indexes = num_indexes self.defer_build = defer_build self.itr = itr self.expected_failure = expected_failure self.query_def_group = query_def_group def execute(self, task_manager): try: RestConnection(self.server) except ServerUnavailableException as error: self.state = FINISHED self.set_exception(error) return try: itr = self.itr while itr < (self.num_indexes + self.itr) and not self.index_tracking_obj.get_stop_create_index(): for query_def in self.query_definitions: if itr >= (self.num_indexes + self.itr): break if self.query_def_group in query_def.groups: query_def_copy = copy.deepcopy(query_def) index_name = query_def_copy.get_index_name() index_name = index_name + str(itr) query_def_copy.update_index_name(index_name) if self.defer_build == "": defer_build = random.choice([True, False]) else: defer_build = self.defer_build index_meta = {"name": query_def_copy.get_index_name(), "query_def": query_def_copy, "defer_build": defer_build} if "primary" in query_def.groups: query = query_def_copy.generate_primary_index_create_query(defer_build=defer_build) else: query = query_def_copy.generate_index_create_query(use_gsi_for_secondary=True, gsi_type="plasma", defer_build=defer_build) try: # create index self.n1ql_helper.run_cbq_query(query=query, server=self.server) self.index_tracking_obj.all_indexes_metadata(index_meta=index_meta, operation="create", defer_build=defer_build) except Exception as err: if not any(error in str(err) for error in self.expected_failure) \ and "Build Already In Progress" not in str(err) \ and "Timeout 1ms exceeded" not in str(err): error_map = {"query": query, "error": str(err)} self.index_tracking_obj.update_errors(error_map) elif not any(error in str(err) for error in self.expected_failure): self.index_tracking_obj.all_indexes_metadata(index_meta=index_meta, operation="create", defer_build=defer_build) itr += 1 self.state = CHECKING task_manager.schedule(self) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) task_manager.schedule(self) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) class CollectionDeleteTask(Task): def __init__(self, server, bucket, scope, collection): Task.__init__(self, "collection_delete_task") self.server = server self.bucket_name = bucket self.scope_name = scope self.collection_name = collection def execute(self, task_manager): try: RestConnection(self.server) except ServerUnavailableException as error: self.state = FINISHED self.set_exception(error) return try: CollectionsRest(self.server).delete_collection(bucket=self.bucket_name, scope=self.scope_name, collection=self.collection_name) self.state = CHECKING task_manager.schedule(self) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) class ScopeCollectionCreateTask(Task): def __init__(self, server, bucket, scope, collection, params=None): Task.__init__(self, "collection_create_task") self.server = server self.bucket_name = bucket self.scope_name = scope self.collection_name = collection self.collection_params = params def execute(self, task_manager): try: RestConnection(self.server) except ServerUnavailableException as error: self.state = FINISHED self.set_exception(error) return try: CollectionsRest(self.server).create_scope_collection(bucket=self.bucket_name, scope=self.scope_name, collection=self.collection_name, params=self.collection_params) self.state = CHECKING task_manager.schedule(self) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) class ScopeCollectionDeleteTask(Task): def __init__(self, server, bucket, scope, collection): Task.__init__(self, "collection_delete_task") self.server = server self.bucket_name = bucket self.scope_name = scope self.collection_name = collection def execute(self, task_manager): try: RestConnection(self.server) except ServerUnavailableException as error: self.state = FINISHED self.set_exception(error) return try: CollectionsRest(self.server).delete_scope_collection(bucket=self.bucket_name, scope=self.scope_name, collection=self.collection_name) self.state = CHECKING task_manager.schedule(self) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) class ScopeCreateTask(Task): def __init__(self, server, bucket, scope, params=None): Task.__init__(self, "scope_create_task") self.server = server self.bucket_name = bucket self.scope_name = scope self.scope_params = params def execute(self, task_manager): try: RestConnection(self.server) except ServerUnavailableException as error: self.state = FINISHED self.set_exception(error) return try: CollectionsRest(self.server).create_scope(bucket=self.bucket_name, scope=self.scope_name, params=self.scope_params) self.state = CHECKING task_manager.schedule(self) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) class ScopeDeleteTask(Task): def __init__(self, server, bucket, scope): Task.__init__(self, "scope_delete_task") self.server = server self.bucket_name = bucket self.scope_name = scope def execute(self, task_manager): try: RestConnection(self.server) except ServerUnavailableException as error: self.state = FINISHED self.set_exception(error) return try: CollectionsRest(self.server).delete_scope(bucket=self.bucket_name, scope=self.scope_name) self.state = CHECKING task_manager.schedule(self) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) class RebalanceTask(Task): def __init__(self, servers, to_add=[], to_remove=[], do_stop=False, progress=30, use_hostnames=False, services=None, sleep_before_rebalance=None): Task.__init__(self, "rebalance_task") self.servers = servers self.to_add = to_add self.to_remove = to_remove self.start_time = None if services is not None and not services: services = ["kv"] self.services = services self.monitor_vbuckets_shuffling = False self.sleep_before_rebalance = sleep_before_rebalance try: self.rest = RestConnection(self.servers[0]) except ServerUnavailableException as e: self.log.error(e) self.state = FINISHED self.set_exception(e) self.retry_get_progress = 0 self.use_hostnames = use_hostnames self.previous_progress = 0 self.old_vbuckets = {} def execute(self, task_manager): try: if len(self.to_add) and len(self.to_add) == len(self.to_remove): node_version_check = self.rest.check_node_versions() non_swap_servers = (node for node in self.servers if node not in self.to_add and node not in self.to_remove) self.old_vbuckets = RestHelper(self.rest)._get_vbuckets(non_swap_servers, None) if self.old_vbuckets: self.monitor_vbuckets_shuffling = True if self.monitor_vbuckets_shuffling and node_version_check and self.services: for service_group in self.services: if "kv" not in service_group: self.monitor_vbuckets_shuffling = False if self.monitor_vbuckets_shuffling and node_version_check: services_map = self.rest.get_nodes_services() for remove_node in self.to_remove: key = "{0}:{1}".format(remove_node.ip, remove_node.port) services = services_map[key] if "kv" not in services: self.monitor_vbuckets_shuffling = False if self.monitor_vbuckets_shuffling: self.log.info("This is swap rebalance and we will monitor vbuckets shuffling") self.add_nodes(task_manager) if self.sleep_before_rebalance: self.log.info("Sleep {0}secs before rebalance_start" .format(self.sleep_before_rebalance)) time.sleep(self.sleep_before_rebalance) self.start_rebalance(task_manager) self.state = CHECKING task_manager.schedule(self) except Exception as e: self.state = FINISHED traceback.print_exc() self.set_exception(e) def add_nodes(self, task_manager): master = self.servers[0] services_for_node = None node_index = 0 for node in self.to_add: self.log.info("adding node {0}:{1} to cluster".format(node.ip, node.port)) if self.services is not None: services_for_node = [self.services[node_index]] node_index += 1 if self.use_hostnames: remote_ip = node.hostname else: remote_ip = node.cluster_ip try: self.rest.add_node(master.rest_username, master.rest_password, remote_ip, node.port, services=services_for_node) except ServerAlreadyJoinedException: pass def start_rebalance(self, task_manager): nodes = self.rest.node_statuses() # Determine whether its a cluster_run/not cluster_run = True firstIp = self.servers[0].ip if len(self.servers) == 1 and self.servers[0].port == '8091': cluster_run = False else: for node in self.servers: if node.ip != firstIp: cluster_run = False break ejectedNodes = [] for server in self.to_remove: for node in nodes: if cluster_run: if int(server.port) == int(node.port): ejectedNodes.append(node.id) else: if self.use_hostnames: if server.hostname == node.ip and int(server.port) == int(node.port): ejectedNodes.append(node.id) elif server.ip == node.ip and int(server.port) == int(node.port): ejectedNodes.append(node.id) if self.rest.is_cluster_mixed(): # workaround MB-8094 self.log.warning("cluster is mixed. sleep for 15 seconds before rebalance") time.sleep(15) self.rest.rebalance(otpNodes=[node.id for node in nodes], ejectedNodes=ejectedNodes) self.start_time = time.time() def check(self, task_manager): status = None progress = -100 try: if self.monitor_vbuckets_shuffling: self.log.info("This is swap rebalance and we will monitor vbuckets shuffling") non_swap_servers = set(self.servers) - set(self.to_remove) - set(self.to_add) new_vbuckets = RestHelper(self.rest)._get_vbuckets(non_swap_servers, None) for vb_type in ["active_vb", "replica_vb"]: for srv in non_swap_servers: if not (len(self.old_vbuckets[srv][vb_type]) + 1 >= len(new_vbuckets[srv][vb_type]) and \ len(self.old_vbuckets[srv][vb_type]) - 1 <= len(new_vbuckets[srv][vb_type])): msg = "Vbuckets were suffled! Expected %s for %s" % (vb_type, srv.ip) + \ " are %s. And now are %s" % ( len(self.old_vbuckets[srv][vb_type]), len(new_vbuckets[srv][vb_type])) self.log.error(msg) self.log.error("Old vbuckets: %s, new vbuckets %s" % (self.old_vbuckets, new_vbuckets)) raise Exception(msg) time.sleep(10) (status, progress) = self.rest._rebalance_status_and_progress() self.log.info("Rebalance - status: {}, progress: {:.02f}%".format(status, progress)) # if ServerUnavailableException if progress == -100: self.retry_get_progress += 1 if self.previous_progress != progress: self.previous_progress = progress self.retry_get_progress = 0 else: self.retry_get_progress += 1 except RebalanceFailedException as ex: self.state = FINISHED self.set_exception(ex) self.retry_get_progress += 1 # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e, " in {0} sec".format(time.time() - self.start_time)) retry_get_process_num = 300 if self.rest.is_cluster_mixed(timeout=300): # See MB-40670 """ for mix cluster, rebalance takes longer """ self.log.info("rebalance in mix cluster") retry_get_process_num = 40 # we need to wait for status to be 'none' (i.e. rebalance actually finished and # not just 'running' and at 100%) before we declare ourselves done if progress != -1 and status != 'none': if self.retry_get_progress < retry_get_process_num: task_manager.schedule(self, 10) else: self.state = FINISHED # self.set_result(False) self.rest.print_UI_logs() self.set_exception(RebalanceFailedException( \ "seems like rebalance hangs. please check logs!")) else: success_cleaned = [] for removed in self.to_remove: try: rest = RestConnection(removed) except ServerUnavailableException as e: self.log.error(e) continue start = time.time() while time.time() - start < 30: try: if 'pools' in rest.get_pools_info() and \ (len(rest.get_pools_info()["pools"]) == 0): success_cleaned.append(removed) break else: time.sleep(0.1) except (ServerUnavailableException, IncompleteRead) as e: self.log.error(e) result = True for node in set(self.to_remove) - set(success_cleaned): self.log.error("node {0}:{1} was not cleaned after removing from cluster" \ .format(node.ip, node.port)) result = False self.log.info("rebalancing was completed with progress: {0}% in {1} sec". format(progress, time.time() - self.start_time)) for added in self.to_add: if added.internal_ip: self.log.info("Adding alternate address {} after rebalance in using internal ip {}".format(added.ip, added.internal_ip)) rest = RestConnection(added) rest.set_alternate_address(added.ip) self.state = FINISHED self.set_result(result) class StatsWaitTask(Task): EQUAL = '==' NOT_EQUAL = '!=' LESS_THAN = '<' LESS_THAN_EQ = '<=' GREATER_THAN = '>' GREATER_THAN_EQ = '>=' def __init__(self, servers, bucket, param, stat, comparison, value, scope=None, collection=None): Task.__init__(self, "stats_wait_task") self.servers = servers self.bucket = bucket if isinstance(bucket, Bucket): self.bucket = bucket.name self.param = param self.stat = stat self.comparison = comparison self.value = value self.conns = {} self.scope = scope self.collection = collection def execute(self, task_manager): self.state = CHECKING task_manager.schedule(self) def check(self, task_manager): stat_result = 0 for server in self.servers: try: shell = RemoteMachineShellConnection(server) cbstat = Cbstats(shell) stats = cbstat.all_stats(self.bucket, stat_name=self.param) if self.stat not in stats: self.state = FINISHED self.set_exception(Exception("Stat {0} not found".format(self.stat))) shell.disconnect() return if stats[self.stat].isdigit(): stat_result += int(stats[self.stat]) else: stat_result = stats[self.stat] shell.disconnect() except EOFError as ex: self.state = FINISHED self.set_exception(ex) shell.disconnect() return if not self._compare(self.comparison, str(stat_result), self.value): self.log.warning("Not Ready: %s %s %s %s expected on %s, %s bucket" % (self.stat, stat_result, self.comparison, self.value, self._stringify_servers(), self.bucket)) task_manager.schedule(self, 5) return self.log.info("Saw %s %s %s %s expected on %s,%s bucket" % (self.stat, stat_result, self.comparison, self.value, self._stringify_servers(), self.bucket)) for server, conn in list(self.conns.items()): conn.close() self.state = FINISHED self.set_result(True) def _stringify_servers(self): return ''.join([repr(server.ip + ":" + str(server.port)) for server in self.servers]) def _get_connection(self, server, admin_user='cbadminbucket', admin_pass='password'): if server not in self.conns: for i in range(3): try: self.conns[server] = MemcachedClientHelper.direct_client(server, self.bucket, admin_user=admin_user, admin_pass=admin_pass) return self.conns[server] except (EOFError, socket.error): self.log.error("failed to create direct client, retry in 1 sec") time.sleep(1) self.conns[server] = MemcachedClientHelper.direct_client(server, self.bucket, admin_user=admin_user, admin_pass=admin_pass) return self.conns[server] def _compare(self, cmp_type, a, b): if isinstance(b, int) and a.isdigit(): a = int(a) elif isinstance(b, int) and not a.isdigit(): return False if (cmp_type == StatsWaitTask.EQUAL and a == b) or \ (cmp_type == StatsWaitTask.NOT_EQUAL and a != b) or \ (cmp_type == StatsWaitTask.LESS_THAN_EQ and a <= b) or \ (cmp_type == StatsWaitTask.GREATER_THAN_EQ and a >= b) or \ (cmp_type == StatsWaitTask.LESS_THAN and a < b) or \ (cmp_type == StatsWaitTask.GREATER_THAN and a > b): return True return False class XdcrStatsWaitTask(StatsWaitTask): def __init__(self, servers, bucket, param, stat, comparison, value, scope=None, collection=None): StatsWaitTask.__init__(self, servers, bucket, param, stat, comparison, value, scope, collection) def check(self, task_manager): stat_result = 0 for server in self.servers: try: rest = RestConnection(server) stat = 'replications/' + rest.get_replication_for_buckets(self.bucket, self.bucket)[ 'id'] + '/' + self.stat # just get the required value, don't fetch the big big structure of stats stats_value = rest.fetch_bucket_xdcr_stats(self.bucket)['op']['samples'][stat][-1] stat_result += int(stats_value) except (EOFError, Exception) as ex: self.state = FINISHED self.set_exception(ex) return if not self._compare(self.comparison, str(stat_result), self.value): self.log.warning("Not Ready: %s %s %s %s expected on %s, %s bucket" % (self.stat, stat_result, self.comparison, self.value, self._stringify_servers(), self.bucket)) task_manager.schedule(self, 5) return self.log.info("Saw %s %s %s %s expected on %s,%s bucket" % (self.stat, stat_result, self.comparison, self.value, self._stringify_servers(), self.bucket)) for server, conn in list(self.conns.items()): conn.close() self.state = FINISHED self.set_result(True) class GenericLoadingTask(Thread, Task): def __init__(self, server, bucket, kv_store, batch_size=1, pause_secs=1, timeout_secs=60, compression=True, scope=None, collection=None): Thread.__init__(self) Task.__init__(self, "load_gen_task") self.kv_store = kv_store self.batch_size = batch_size self.pause = pause_secs self.timeout = timeout_secs self.server = server self.bucket = bucket self.collection = collection self.scope = scope if CHECK_FLAG: self.client = VBucketAwareMemcached(RestConnection(server), bucket) else: self.client = VBucketAwareMemcached(RestConnection(server), bucket, compression=compression) self.process_concurrency = THROUGHPUT_CONCURRENCY # task queue's for synchronization process_manager = Manager() self.wait_queue = process_manager.Queue() self.shared_kvstore_queue = process_manager.Queue() def execute(self, task_manager): self.start() self.state = EXECUTING def check(self, task_manager): pass def run(self): while self.has_next() and not self.done(): next(self) self.state = FINISHED self.set_result(True) def has_next(self): raise NotImplementedError def __next__(self): raise NotImplementedError def _unlocked_create(self, partition, key, value, is_base64_value=False): try: value_json = json.loads(value) if isinstance(value_json, dict): value_json['mutated'] = 0 value = json.dumps(value_json) except ValueError: index = random.choice(list(range(len(value)))) if not is_base64_value: value = value[0:index] + random.choice(string.ascii_uppercase) + value[index + 1:] except TypeError: value = json.dumps(value) try: self.client.set(key, self.exp, self.flag, value, scope=self.scope, collection=self.collection) if self.only_store_hash: value = str(crc32.crc32_hash(value)) partition.set(key, value, self.exp, self.flag) except Exception as error: self.state = FINISHED self.set_exception(error) def _unlocked_read(self, partition, key): try: o, c, d = self.client.get(key, scope=self.scope, collection=self.collection) except MemcachedError as error: if error.status == ERR_NOT_FOUND and partition.get_valid(key) is None: pass else: self.state = FINISHED self.set_exception(error) def _unlocked_replica_read(self, partition, key): try: o, c, d = self.client.getr(key, scope=self.scope, collection=self.collection) except Exception as error: self.state = FINISHED self.set_exception(error) def _unlocked_update(self, partition, key): value = None try: o, c, value = self.client.get(key, scope=self.scope, collection=self.collection) if value is None: return value_json = json.loads(value) value_json['mutated'] += 1 value = json.dumps(value_json) except MemcachedError as error: if error.status == ERR_NOT_FOUND and partition.get_valid(key) is None: # there is no such item, we do not know what value to set return else: self.state = FINISHED self.log.error("%s, key: %s update operation." % (error, key)) self.set_exception(error) return except (ValueError, json.JSONDecodeError) as e: if value is None: return index = random.choice(list(range(len(value)))) value = value[0:index] + random.choice(string.ascii_uppercase).encode() + value[index + 1:] except BaseException as error: self.state = FINISHED self.set_exception(error) try: self.client.set(key, self.exp, self.flag, value, scope=self.scope, collection=self.collection) if self.only_store_hash: if value != None: value = str(crc32.crc32_hash(value)) partition.set(key, value, self.exp, self.flag) except BaseException as error: self.state = FINISHED self.set_exception(error) def _unlocked_delete(self, partition, key): try: self.client.delete(key, scope=self.scope, collection=self.collection) partition.delete(key) except MemcachedError as error: if error.status == ERR_NOT_FOUND and partition.get_valid(key) is None: pass else: self.state = FINISHED self.log.error("%s, key: %s delete operation." % (error, key)) self.set_exception(error) except BaseException as error: self.state = FINISHED self.set_exception(error) def _unlocked_append(self, partition, key, value): try: o, c, old_value = self.client.get(key, scope=self.scope, collection=self.collection) if value is None: return value_json = json.loads(value) old_value_json = json.loads(old_value) old_value_json.update(value_json) old_value = json.dumps(old_value_json) value = json.dumps(value_json) except MemcachedError as error: if error.status == ERR_NOT_FOUND and partition.get_valid(key) is None: # there is no such item, we do not know what value to set return else: self.state = FINISHED self.set_exception(error) return except ValueError: o, c, old_value = self.client.get(key, scope=self.scope, collection=self.collection) index = random.choice(list(range(len(value)))) value = value[0:index] + random.choice(string.ascii_uppercase) + value[index + 1:] old_value += value except BaseException as error: self.state = FINISHED self.set_exception(error) try: self.client.append(key, value, scope=self.scope, collection=self.collection) if self.only_store_hash: old_value = str(crc32.crc32_hash(old_value)) partition.set(key, old_value) except BaseException as error: self.state = FINISHED self.set_exception(error) # start of batch methods def _create_batch_client(self, key_val, shared_client=None): """ standalone method for creating key/values in batch (sans kvstore) arguments: key_val -- array of key/value dicts to load size = self.batch_size shared_client -- optional client to use for data loading """ try: self._process_values_for_create(key_val) client = shared_client or self.client client.setMulti(self.exp, self.flag, key_val, self.pause, self.timeout, parallel=False, scope=self.scope, collection=self.collection) except ( MemcachedError, ServerUnavailableException, socket.error, EOFError, AttributeError, RuntimeError) as error: self.state = FINISHED self.set_exception(error) def _create_batch(self, partition_keys_dic, key_val): self._create_batch_client(key_val) self._populate_kvstore(partition_keys_dic, key_val) def _update_batch(self, partition_keys_dic, key_val): try: self._process_values_for_update(partition_keys_dic, key_val) self.client.setMulti(self.exp, self.flag, key_val, self.pause, self.timeout, parallel=False, scope=self.scope, collection=self.collection) self._populate_kvstore(partition_keys_dic, key_val) except ( MemcachedError, ServerUnavailableException, socket.error, EOFError, AttributeError, RuntimeError) as error: self.state = FINISHED self.set_exception(error) def _delete_batch(self, partition_keys_dic, key_val): for partition, keys in list(partition_keys_dic.items()): for key in keys: try: self.client.delete(key, scope=self.scope, collection=self.collection) partition.delete(key) except MemcachedError as error: if error.status == ERR_NOT_FOUND and partition.get_valid(key) is None: pass else: self.state = FINISHED self.set_exception(error) return except (ServerUnavailableException, socket.error, EOFError, AttributeError) as error: self.state = FINISHED self.set_exception(error) def _read_batch(self, partition_keys_dic, key_val): try: self.client.getMulti(list(key_val.keys()), self.pause, self.timeout, scope=self.scope, collection=self.collection) # print "the key is {} from collection {}".format(c, collection) except MemcachedError as error: self.state = FINISHED self.set_exception(error) def _process_values_for_create(self, key_val): for key, value in list(key_val.items()): try: value_json = json.loads(value) value_json['mutated'] = 0 value = json.dumps(value_json) except ValueError: index = random.choice(list(range(len(value)))) value = value[0:index] + random.choice(string.ascii_uppercase) + value[index + 1:] except TypeError: value = json.dumps(value) finally: key_val[key] = value def _process_values_for_update(self, partition_keys_dic, key_val): for partition, keys in list(partition_keys_dic.items()): for key in keys: value = partition.get_valid(key) if value is None: del key_val[key] continue try: value = key_val[ key] # new updated value, however it is not their in orginal code "LoadDocumentsTask" value_json = json.loads(value) value_json['mutated'] += 1 value = json.dumps(value_json) except ValueError: index = random.choice(list(range(len(value)))) value = value[0:index] + random.choice(string.ascii_uppercase) + value[index + 1:] finally: key_val[key] = value def _populate_kvstore(self, partition_keys_dic, key_val): for partition, keys in list(partition_keys_dic.items()): self._populate_kvstore_partition(partition, keys, key_val) def _release_locks_on_kvstore(self): for part in self._partitions_keyvals_dic.keys: self.kv_store.release_lock(part) def _populate_kvstore_partition(self, partition, keys, key_val): for key in keys: if self.only_store_hash: key_val[key] = str(crc32.crc32_hash(key_val[key])) partition.set(key, key_val[key], self.exp, self.flag) class LoadDocumentsTask(GenericLoadingTask): def __init__(self, server, bucket, generator, kv_store, op_type, exp, flag=0, only_store_hash=True, proxy_client=None, batch_size=1, pause_secs=1, timeout_secs=30, compression=True, scope=None, collection=None): GenericLoadingTask.__init__(self, server, bucket, kv_store, batch_size=batch_size, pause_secs=pause_secs, timeout_secs=timeout_secs, compression=compression, scope=scope, collection=collection) self.generator = generator self.op_type = op_type self.exp = exp self.flag = flag self.only_store_hash = only_store_hash self.scope = scope self.collection = collection if proxy_client: self.log.info("Changing client to proxy %s:%s..." % (proxy_client.host, proxy_client.port)) self.client = proxy_client def has_next(self): return self.generator.has_next() def next(self, override_generator=None): if self.batch_size == 1: key, value = next(self.generator) partition = self.kv_store.acquire_partition(key, self.bucket, self.scope, self.collection) if self.op_type == 'create': is_base64_value = (self.generator.__class__.__name__ == 'Base64Generator') self._unlocked_create(partition, key, value, is_base64_value=is_base64_value) elif self.op_type == 'read': self._unlocked_read(partition, key) elif self.op_type == 'read_replica': self._unlocked_replica_read(partition, key) elif self.op_type == 'update': self._unlocked_update(partition, key) elif self.op_type == 'delete': self._unlocked_delete(partition, key) elif self.op_type == 'append': self._unlocked_append(partition, key, value) else: self.state = FINISHED self.set_exception(Exception("Bad operation type: %s" % self.op_type)) self.kv_store.release_partition(key, self.bucket, self.scope, self.collection) else: doc_gen = override_generator or self.generator key_value = doc_gen.next_batch() partition_keys_dic = self.kv_store.acquire_partitions(list(key_value.keys()), self.bucket, self.scope, self.collection) if self.op_type == 'create': self._create_batch(partition_keys_dic, key_value) elif self.op_type == 'update': self._update_batch(partition_keys_dic, key_value) elif self.op_type == 'delete': self._delete_batch(partition_keys_dic, key_value) elif self.op_type == 'read': self._read_batch(partition_keys_dic, key_value) else: self.state = FINISHED self.set_exception(Exception("Bad operation type: %s" % self.op_type)) self.kv_store.release_partitions(list(partition_keys_dic.keys())) class LoadDocumentsGeneratorsTask(LoadDocumentsTask): def __init__(self, server, bucket, generators, kv_store, op_type, exp, flag=0, only_store_hash=True, batch_size=1, pause_secs=1, timeout_secs=60, compression=True, scope=None, collection=None): LoadDocumentsTask.__init__(self, server, bucket, generators[0], kv_store, op_type, exp, flag=flag, only_store_hash=only_store_hash, batch_size=batch_size, pause_secs=pause_secs, timeout_secs=timeout_secs, compression=compression, scope=scope, collection=collection) if batch_size == 1: self.generators = generators else: self.generators = [] for i in generators: if i.isGenerator(): self.generators.append(BatchedDocumentGenerator(i, batch_size)) else: self.generators.append(i) # only run high throughput for batch-create workloads # also check number of input generators isn't greater than # process_concurrency as too many generators become inefficient self.is_high_throughput_mode = False if ALLOW_HTP and not TestInputSingleton.input.param("disable_HTP", False): self.is_high_throughput_mode = self.op_type == "create" and \ self.batch_size > 1 and \ len(self.generators) < self.process_concurrency self.input_generators = generators self.bucket = bucket self.op_types = None self.buckets = None if isinstance(op_type, list): self.op_types = op_type if isinstance(bucket, list): self.buckets = bucket self.compression = compression self.scope = scope self.collection = collection def run(self): if self.op_types: if len(self.op_types) != len(self.generators): self.state = FINISHED self.set_exception(Exception("not all generators have op_type!")) if self.buckets: if len(self.op_types) != len(self.buckets): self.state = FINISHED self.set_exception(Exception("not all generators have bucket specified!")) # check if running in high throughput mode or normal if self.is_high_throughput_mode: self.run_high_throughput_mode() else: self.run_normal_throughput_mode() self.state = FINISHED self.set_result(True) def run_normal_throughput_mode(self): iterator = 0 for generator in self.generators: self.generator = generator if self.op_types: self.op_type = self.op_types[iterator] if self.buckets: self.bucket = self.buckets[iterator] while self.has_next() and not self.done(): self.next() iterator += 1 def run_high_throughput_mode(self): # high throughput mode requires partitioning the doc generators self.generators = [] for gen in self.input_generators: gen_start = int(gen.start) gen_end = max(int(gen.end), 1) gen_range = max(int(gen.end / self.process_concurrency), 1) for pos in range(gen_start, gen_end, gen_range): try: partition_gen = copy.deepcopy(gen) partition_gen.start = pos partition_gen.itr = pos partition_gen.end = pos + gen_range if partition_gen.end > gen.end: partition_gen.end = gen.end batch_gen = BatchedDocumentGenerator( partition_gen, self.batch_size) self.generators.append(batch_gen) except Exception as e: traceback.print_exc() iterator = 0 all_processes = [] for generator in self.generators: # only start processing when there resources available CONCURRENCY_LOCK.acquire() # add child process to wait queue self.wait_queue.put(iterator + 1) generator_process = Process( target=self.run_generator, args=(generator, iterator)) generator_process.start() iterator += 1 all_processes.append(generator_process) # wait for all child processes to finish self.wait_queue.join() # merge kvstore partitions while self.shared_kvstore_queue.empty() is False: # get partitions created by child process rv = self.shared_kvstore_queue.get() if rv["err"] is not None: self.state = FINISHED self.set_exception(rv["err"]) return # merge child partitions with parent generator_partitions = rv["partitions"] self.kv_store.merge_partitions(generator_partitions) # terminate child process iterator -= 1 all_processes[iterator].terminate() def run_generator(self, generator, iterator): tmp_kv_store = KVStore() rv = {"err": None, "partitions": None} try: if CHECK_FLAG: client = VBucketAwareMemcached( RestConnection(self.server), self.bucket) else: client = VBucketAwareMemcached( RestConnection(self.server), self.bucket, compression=self.compression) try: if self.op_types: self.op_type = self.op_types[iterator] if self.buckets: self.bucket = self.buckets[iterator] while generator.has_next() and not self.done(): # generate key_value = generator.next_batch() # create self._create_batch_client(key_value, client) # cache self.cache_items(tmp_kv_store, key_value) except Exception as e: traceback.print_exc() except Exception as ex: rv["err"] = ex else: rv["partitions"] = tmp_kv_store.get_partitions() finally: # share the kvstore from this generator self.shared_kvstore_queue.put(rv) self.wait_queue.task_done() # release concurrency lock CONCURRENCY_LOCK.release() def cache_items(self, store, key_value): """ unpacks keys,values and adds them to provided store """ for key, value in key_value.items(): if self.only_store_hash: value = str(crc32.crc32_hash(value)) partition = store.partition(key, self.scope, self.collection, self.bucket) partition["partition"].set( key, value, self.exp, self.flag) class ESLoadGeneratorTask(Task): """ Class to load/update/delete documents into/from Elastic Search """ def __init__(self, es_instance, index_name, generator, op_type="create", scope=None, collection=None): Task.__init__(self, "ES_loader_task") self.es_instance = es_instance self.index_name = index_name self.generator = generator self.iterator = 0 self.scope = scope self.collection = collection self.log.info("Starting to load data into Elastic Search ...") def check(self, task_manager): self.state = FINISHED self.set_result(True) def execute(self, task_manager): for key, doc in self.generator: doc = json.loads(doc) self.es_instance.load_data(self.index_name, json.dumps(doc, encoding='utf-8'), doc['type'], key, self.scope, self.collection) self.iterator += 1 if math.fmod(self.iterator, 500) == 0.0: self.log.info("{0} documents loaded into ES". format(self.iterator)) self.state = FINISHED self.set_result(True) class ESBulkLoadGeneratorTask(Task): """ Class to load/update/delete documents into/from Elastic Search """ def __init__(self, es_instance, index_name, generator, op_type="create", batch=1000, scope=None, collection=None): Task.__init__(self, "ES_loader_task") self.es_instance = es_instance self.index_name = index_name self.generator = generator self.iterator = 0 self.op_type = op_type self.batch_size = batch self.scope = scope self.collection = collection self.log.info("Starting operation '%s' on Elastic Search ..." % op_type) def check(self, task_manager): self.state = FINISHED self.set_result(True) def execute(self, task_manager): es_filename = "/tmp/es_bulk.txt" es_bulk_docs = [] loaded = 0 batched = 0 for key, doc in self.generator: doc = json.loads(doc) es_doc = { self.op_type: { "_index": self.index_name, "_type": doc['type'], "_id": key, } } es_bulk_docs.append(json.dumps(es_doc)) if self.op_type == "create": es_bulk_docs.append(json.dumps(doc)) elif self.op_type == "update": doc['mutated'] += 1 es_bulk_docs.append(json.dumps({"doc": doc})) batched += 1 if batched == self.batch_size or not self.generator.has_next(): es_file = open(es_filename, "wb") for line in es_bulk_docs: es_file.write("{}\n".format(line).encode()) es_file.close() self.es_instance.load_bulk_data(es_filename) loaded += batched self.log.info("{0} documents bulk loaded into ES".format(loaded)) self.es_instance.update_index(self.index_name) batched = 0 indexed = self.es_instance.get_index_count(self.index_name) self.log.info("ES index count for '{0}': {1}". format(self.index_name, indexed)) self.state = FINISHED self.set_result(True) class ESRunQueryCompare(Task): def __init__(self, fts_index, es_instance, query_index, es_index_name=None, n1ql_executor=None, use_collections=False): Task.__init__(self, "Query_runner_task") self.fts_index = fts_index self.fts_query = fts_index.fts_queries[query_index] self.es = es_instance if self.es: self.es_query = es_instance.es_queries[query_index] self.max_verify = None self.show_results = False self.query_index = query_index self.passed = True self.es_index_name = es_index_name or "es_index" self.n1ql_executor = n1ql_executor self.score = TestInputSingleton.input.param("score",'') self.use_collections = use_collections def check(self, task_manager): self.state = FINISHED self.set_result(self.result) def execute(self, task_manager): self.es_compare = True should_verify_n1ql = True try: self.log.info("---------------------------------------" "-------------- Query # %s -------------" "---------------------------------------" % str(self.query_index + 1)) try: fts_hits, fts_doc_ids, fts_time, fts_status = \ self.run_fts_query(self.fts_query, self.score) self.log.info("Status: %s" % fts_status) if fts_status == 'fail': error = fts_doc_ids if "err: TooManyClauses over field" in str(error): self.log.info("FTS chose not to run this big query" "...skipping ES validation") self.passed = True self.es_compare = False should_verify_n1ql = False elif fts_hits < 0: self.passed = False elif 'errors' in list(fts_status.keys()) and fts_status['errors']: if fts_status['successful'] == 0 and \ (list(set(fts_status['errors'].values())) == ['context deadline exceeded'] or "TooManyClauses" in str(list(set(fts_status['errors'].values())))): # too many clauses in the query for fts to process self.log.info("FTS chose not to run this big query" "...skipping ES validation") self.passed = True self.es_compare = False should_verify_n1ql = False elif 0 < fts_status['successful'] < \ self.fts_index.num_pindexes: # partial results self.log.info("FTS returned partial results..." "skipping ES validation") self.passed = True self.es_compare = False self.log.info("FTS hits for query: %s is %s (took %sms)" % \ (json.dumps(self.fts_query, ensure_ascii=False), fts_hits, float(fts_time) / 1000000)) except ServerUnavailableException: self.log.error("ERROR: FTS Query timed out (client timeout=70s)!") self.passed = False es_hits = 0 if self.es and self.es_query: es_hits, es_doc_ids, es_time = self.run_es_query(self.es_query) self.log.info("ES hits for query: %s on %s is %s (took %sms)" % \ (json.dumps(self.es_query, ensure_ascii=False), self.es_index_name, es_hits, es_time)) if self.passed and self.es_compare: if int(es_hits) != int(fts_hits): msg = "FAIL: FTS hits: %s, while ES hits: %s" \ % (fts_hits, es_hits) self.log.error(msg) es_but_not_fts = list(set(es_doc_ids) - set(fts_doc_ids)) fts_but_not_es = list(set(fts_doc_ids) - set(es_doc_ids)) if not (es_but_not_fts or fts_but_not_es): self.log.info("SUCCESS: Docs returned by FTS = docs" " returned by ES, doc_ids verified") else: if fts_but_not_es: msg = "FAIL: Following %s doc(s) were not returned" \ " by ES,but FTS, printing 50: %s" \ % (len(fts_but_not_es), fts_but_not_es[:50]) else: msg = "FAIL: Following %s docs were not returned" \ " by FTS, but ES, printing 50: %s" \ % (len(es_but_not_fts), es_but_not_fts[:50]) self.log.error(msg) self.passed = False if fts_hits <= 0 and es_hits == 0: should_verify_n1ql = False if self.n1ql_executor and should_verify_n1ql: if self.fts_index.dataset == 'all': query_type = 'emp' if int(TestInputSingleton.input.param("doc_maps", 1)) > 1: query_type = 'wiki' wiki_fields = ["revision.text", "title"] if any(field in str(json.dumps(self.fts_query)) for field in wiki_fields): query_type = 'wiki' else: query_type = self.fts_index.dataset geo_strings = ['"field": "geo"'] if any(geo_str in str(json.dumps(self.fts_query)) for geo_str in geo_strings): query_type = 'earthquake' if self.use_collections: kv_container = "default:default.scope1.collection1" else: kv_container = "default" n1ql_queries = [f"select meta().id from {kv_container} where type='" + str( query_type) + "' and search(default, " + str( json.dumps(self.fts_query, ensure_ascii=False)) + ")", f"select meta().id from {kv_container} where type='" + str( query_type) + "' and search(default, " + str( json.dumps(self.fts_query, ensure_ascii=False)) + ",{\"index\": \"" + self.fts_index.name + "\"})", f"select meta().id,* from {kv_container} where type='" + str( query_type) + "' and search(default, " + str( json.dumps(self.fts_query, ensure_ascii=False)) + ",{\"index\": \"" + self.fts_index.name + "\"})"] for n1ql_query in n1ql_queries: if ("disjuncts" not in n1ql_query and "-" not in n1ql_query) or "\"index\"" in n1ql_query: self.log.info("Running N1QL query: " + str(n1ql_query)) n1ql_result = self.n1ql_executor.run_n1ql_query(query=n1ql_query) if n1ql_result['status'] == 'success': n1ql_hits = n1ql_result['metrics']['resultCount'] n1ql_doc_ids = [] for res in n1ql_result['results']: n1ql_doc_ids.append(res['id']) n1ql_time = n1ql_result['metrics']['elapsedTime'] self.log.info("N1QL hits for query: %s is %s (took %s)" % \ (json.dumps(n1ql_query, ensure_ascii=False), n1ql_hits, n1ql_time)) if self.passed: if int(n1ql_hits) != int(fts_hits): msg = "FAIL: FTS hits: %s, while N1QL hits: %s" \ % (fts_hits, n1ql_hits) self.log.error(msg) n1ql_but_not_fts = list(set(n1ql_doc_ids) - set(fts_doc_ids)) fts_but_not_n1ql = list(set(fts_doc_ids) - set(n1ql_doc_ids)) if not (n1ql_but_not_fts or fts_but_not_n1ql): self.log.info("SUCCESS: Docs returned by FTS = docs" " returned by N1QL, doc_ids verified") else: if fts_but_not_n1ql: msg = "FAIL: Following %s doc(s) were not returned" \ " by N1QL,but FTS, printing 50: %s" \ % (len(fts_but_not_n1ql), fts_but_not_n1ql[:50]) else: msg = "FAIL: Following %s docs were not returned" \ " by FTS, but N1QL, printing 50: %s" \ % (len(n1ql_but_not_fts), n1ql_but_not_fts[:50]) self.log.error(msg) self.passed = False else: self.passed = False self.log.info("N1QL query execution is failed.") self.log.error(n1ql_result["errors"][0]['msg']) self.state = CHECKING task_manager.schedule(self) if not should_verify_n1ql and self.n1ql_executor: self.log.info("Skipping N1QL result validation since FTS results are - " + str( fts_hits) + " and es results are - " + str(es_hits) + ".") except Exception as e: self.log.error(e) self.set_exception(e) self.state = FINISHED def run_fts_query(self, query, score=''): return self.fts_index.execute_query(query, score=score) def run_es_query(self, query): return self.es.search(index_name=self.es_index_name, query=query) # This will be obsolete with the implementation of batch operations in LoadDocumentsTaks class BatchedLoadDocumentsTask(GenericLoadingTask): def __init__(self, server, bucket, generator, kv_store, op_type, exp, flag=0, only_store_hash=True, batch_size=100, pause_secs=1, timeout_secs=60, compression=True, scope=None, collection=None): GenericLoadingTask.__init__(self, server, bucket, kv_store, compression=compression, scope=scope, collection=collection) self.batch_generator = BatchedDocumentGenerator(generator, batch_size) self.op_type = op_type self.exp = exp self.flag = flag self.only_store_hash = only_store_hash self.batch_size = batch_size self.pause = pause_secs self.timeout = timeout_secs self.bucket = bucket self.server = server self.scope=scope self.collection = collection def has_next(self): has = self.batch_generator.has_next() if math.fmod(self.batch_generator._doc_gen.itr, 50000) == 0.0 or not has: self.log.info("Batch {0} documents queued #: {1} with exp:{2} @ {3}, bucket {4}". \ format(self.op_type, (self.batch_generator._doc_gen.itr - self.batch_generator._doc_gen.start), self.exp, self.server.ip, self.bucket)) return has def __next__(self): key_value = self.batch_generator.next_batch() partition_keys_dic = self.kv_store.acquire_partitions(list(key_value.keys()), self.bucket, self.scope, self.collection) if self.op_type == 'create': self._create_batch(partition_keys_dic, key_value) elif self.op_type == 'update': self._update_batch(partition_keys_dic, key_value) elif self.op_type == 'delete': self._delete_batch(partition_keys_dic, key_value) elif self.op_type == 'read': self._read_batch(partition_keys_dic, key_value) else: self.state = FINISHED self.set_exception(Exception("Bad operation type: %s" % self.op_type)) self.kv_store.release_partitions(list(partition_keys_dic.keys()), self.scope, self.collection) def _create_batch(self, partition_keys_dic, key_val): try: self._process_values_for_create(key_val) self.client.setMulti(self.exp, self.flag, key_val, self.pause, self.timeout, parallel=False, scope=self.scope, collection=self.collection) self._populate_kvstore(partition_keys_dic, key_val) except ( MemcachedError, ServerUnavailableException, socket.error, EOFError, AttributeError, RuntimeError) as error: self.state = FINISHED self.set_exception(error) def _update_batch(self, partition_keys_dic, key_val): try: self._process_values_for_update(partition_keys_dic, key_val) self.client.setMulti(self.exp, self.flag, key_val, self.pause, self.timeout, parallel=False, scope=self.scope, collection=self.collection) self._populate_kvstore(partition_keys_dic, key_val) except ( MemcachedError, ServerUnavailableException, socket.error, EOFError, AttributeError, RuntimeError) as error: self.state = FINISHED self.set_exception(error) def _delete_batch(self, partition_keys_dic, key_val): for partition, keys in list(partition_keys_dic.items()): for key in keys: try: self.client.delete(key, scope=self.scope, collection=self.collection) partition.delete(key) except MemcachedError as error: if error.status == ERR_NOT_FOUND and partition.get_valid(key) is None: pass else: self.state = FINISHED self.set_exception(error) return except (ServerUnavailableException, socket.error, EOFError, AttributeError) as error: self.state = FINISHED self.set_exception(error) def _read_batch(self, partition_keys_dic, key_val): try: self.client.getMulti(list(key_val.keys()), self.pause, self.timeout, scope=self.scope, collection=self.collection) except MemcachedError as error: self.state = FINISHED self.set_exception(error) def _process_values_for_create(self, key_val): for key, value in list(key_val.items()): try: value_json = json.loads(value) value_json['mutated'] = 0 value = json.dumps(value_json) except ValueError: index = random.choice(list(range(len(value)))) value = value[0:index] + random.choice(string.ascii_uppercase) + value[index + 1:] finally: key_val[key] = value def _process_values_for_update(self, partition_keys_dic, key_val): for partition, keys in list(partition_keys_dic.items()): for key in keys: value = partition.get_valid(key) if value is None: del key_val[key] continue try: value = key_val[ key] # new updated value, however it is not their in orginal code "LoadDocumentsTask" value_json = json.loads(value) value_json['mutated'] += 1 value = json.dumps(value_json) except ValueError: index = random.choice(list(range(len(value)))) value = value[0:index] + random.choice(string.ascii_uppercase) + value[index + 1:] finally: key_val[key] = value def _populate_kvstore(self, partition_keys_dic, key_val): for partition, keys in list(partition_keys_dic.items()): self._populate_kvstore_partition(partition, keys, key_val) def _release_locks_on_kvstore(self): for part in self._partitions_keyvals_dic.keys: self.kv_store.release_lock(part) def _populate_kvstore_partition(self, partition, keys, key_val): for key in keys: if self.only_store_hash: key_val[key] = str(crc32.crc32_hash(key_val[key])) partition.set(key, key_val[key], self.exp, self.flag) class WorkloadTask(GenericLoadingTask): def __init__(self, server, bucket, kv_store, num_ops, create, read, update, delete, exp, compression=True, scope=None, collection=None): GenericLoadingTask.__init__(self, server, bucket, kv_store, compression=compression, scope=scope, collection=collection) self.itr = 0 self.num_ops = num_ops self.create = create self.read = create + read self.update = create + read + update self.delete = create + read + update + delete self.exp = exp self.scope = scope self.collection = collection self.bucket = bucket def has_next(self): if self.num_ops == 0 or self.itr < self.num_ops: return True return False def __next__(self): self.itr += 1 rand = random.randint(1, self.delete) if 0 < rand <= self.create: self._create_random_key() elif self.create < rand <= self.read: self._get_random_key() elif self.read < rand <= self.update: self._update_random_key() elif self.update < rand <= self.delete: self._delete_random_key() def _get_random_key(self): partition, part_num = self.kv_store.acquire_random_partition() if partition is None: return key = partition.get_random_valid_key() if key is None: self.kv_store.release_partitions(part_num) return self._unlocked_read(partition, key) self.kv_store.release_partitions(part_num) def _create_random_key(self): partition, part_num = self.kv_store.acquire_random_partition(False) if partition is None: return key = partition.get_random_deleted_key() if key is None: self.kv_store.release_partitions(part_num) return value = partition.get_deleted(key) if value is None: self.kv_store.release_partitions(part_num) return self._unlocked_create(partition, key, value) self.kv_store.release_partitions(part_num) def _update_random_key(self): partition, part_num = self.kv_store.acquire_random_partition() if partition is None: return key = partition.get_random_valid_key() if key is None: self.kv_store.release_partitions(part_num) return self._unlocked_update(partition, key) self.kv_store.release_partitions(part_num) def _delete_random_key(self): partition, part_num = self.kv_store.acquire_random_partition() if partition is None: return key = partition.get_random_valid_key() if key is None: self.kv_store.release_partitions(part_num) return self._unlocked_delete(partition, key) self.kv_store.release_partitions(part_num) class ValidateDataTask(GenericLoadingTask): def __init__(self, server, bucket, kv_store, max_verify=None, only_store_hash=True, replica_to_read=None, compression=True, scope=None, collection=None): GenericLoadingTask.__init__(self, server, bucket, kv_store, compression=compression, scope=scope, collection=collection) self.collection = collection self.scope = scope self.bucket = bucket self.valid_keys, self.deleted_keys = kv_store.key_set(bucket=self.bucket, scope=self.scope, collection=self.collection) self.num_valid_keys = len(self.valid_keys) self.num_deleted_keys = len(self.deleted_keys) self.itr = 0 self.max_verify = self.num_valid_keys + self.num_deleted_keys self.only_store_hash = only_store_hash self.replica_to_read = replica_to_read self.bucket = bucket self.server = server if max_verify is not None: self.max_verify = min(max_verify, self.max_verify) self.log.info( "%s items will be verified on %s bucket on scope %s on collection %s" % (self.max_verify, bucket, self.scope, self.collection)) self.start_time = time.time() def has_next(self): if self.itr < (self.num_valid_keys + self.num_deleted_keys) and \ self.itr < self.max_verify: if not self.itr % 50000: self.log.info("{0} items were verified".format(self.itr)) return True self.log.info("{0} items were verified in {1} sec.the average number of ops\ - {2} per second ".format(self.itr, time.time() - self.start_time, self.itr // (time.time() - self.start_time)).rstrip()) return False def __next__(self): if self.itr < self.num_valid_keys: self._check_valid_key(self.valid_keys[self.itr], self.bucket, scope=self.scope, collection=self.collection) else: self._check_deleted_key(self.deleted_keys[self.itr - self.num_valid_keys], self.bucket, scope=self.scope, collection=self.collection) self.itr += 1 def _check_valid_key(self, key, bucket="default", scope=None, collection=None): partition = self.kv_store.acquire_partition(key, bucket, scope=scope, collection=collection) value = partition.get_valid(key) flag = partition.get_flag(key) if value is None or flag is None: self.kv_store.release_partition(key, bucket, scope=scope, collection=collection) return try: if self.replica_to_read is None: o, c, d = self.client.get(key, scope=scope, collection=collection) else: o, c, d = self.client.getr(key, replica_index=self.replica_to_read, scope=scope, collection=collection) try: d = d.decode() except AttributeError: pass if self.only_store_hash: if crc32.crc32_hash(d) != int(value): self.state = FINISHED self.set_exception(Exception( 'Key: %s, Bad hash result: %d != %d for key %s' % (key, crc32.crc32_hash(d), int(value), key))) else: value = json.dumps(value) if d != json.loads(value): self.log.info(f"the scope {scope} collection is {collection} for which the value is failing") self.state = FINISHED self.set_exception( Exception('Key: %s, Bad result: %s != %s for key %s' % (key, json.dumps(d), value, key))) if CHECK_FLAG and o != flag: self.state = FINISHED self.set_exception( Exception('Key: %s, Bad result for flag value: %s != the value we set: %s' % (key, o, flag))) except MemcachedError as error: if error.status == ERR_NOT_FOUND and partition.get_valid(key) is None: pass else: self.state = FINISHED self.set_exception(error) except Exception as error: self.log.error("Unexpected error: %s" % str(error)) self.state = FINISHED self.set_exception(error) self.kv_store.release_partition(key, bucket, scope=scope, collection=collection) def _check_deleted_key(self, key, bucket="default", scope=None, collection=None): partition = self.kv_store.acquire_partition(key, bucket, scope=scope, collection=collection) try: self.client.delete(key, scope=scope, collection=collection) if partition.get_valid(key) is not None: self.state = FINISHED self.set_exception(Exception('Not Deletes: %s' % (key))) except MemcachedError as error: if error.status == ERR_NOT_FOUND: pass else: self.state = FINISHED self.set_exception(error) except Exception as error: if error.rc != NotFoundError: self.state = FINISHED self.set_exception(error) self.kv_store.release_partition(key, bucket, scope=scope, collection=collection) class ValidateDataWithActiveAndReplicaTask(GenericLoadingTask): def __init__(self, server, bucket, kv_store, max_verify=None, compression=True, scope=None, collection=None): GenericLoadingTask.__init__(self, server, bucket, kv_store, compression=compression, scope=scope, collection=collection) self.collection = collection self.scope = scope self.bucket = bucket self.valid_keys, self.deleted_keys = kv_store.key_set(bucket=self.bucket, scope=self.scope, collection=self.collection) self.num_valid_keys = len(self.valid_keys) self.num_deleted_keys = len(self.deleted_keys) self.itr = 0 self.max_verify = self.num_valid_keys + self.num_deleted_keys if max_verify is not None: self.max_verify = min(max_verify, self.max_verify) self.log.info("%s items will be verified on %s bucket" % (self.max_verify, bucket)) self.start_time = time.time() def has_next(self): if self.itr < (self.num_valid_keys + self.num_deleted_keys) and \ self.itr < self.max_verify: if not self.itr % 50000: self.log.info("{0} items were verified".format(self.itr)) return True self.log.info("{0} items were verified in {1} sec.the average number of ops\ - {2} per second ".format(self.itr, time.time() - self.start_time, self.itr // (time.time() - self.start_time)).rstrip()) return False def __next__(self): if self.itr < self.num_valid_keys: self._check_valid_key(self.valid_keys[self.itr], self.bucket, self.scope, self.collection) else: self._check_deleted_key(self.deleted_keys[self.itr - self.num_valid_keys], self.bucket, self.scope, self.collection) self.itr += 1 def _check_valid_key(self, key, bucket, scope=None, collection=None): partition = self.kv_store.acquire_partition(key, bucket, scope=scope, collection=collection) try: o, c, d = self.client.get(key, scope=scope, collection=collection) o_r, c_r, d_r = self.client.getr(key, replica_index=0, scope=scope, collection=collection) if o != o_r: self.state = FINISHED self.set_exception(Exception( 'ACTIVE AND REPLICA FLAG CHECK FAILED :: Key: %s, Bad result for CAS value: REPLICA FLAG %s != ACTIVE FLAG %s' % ( key, o_r, o))) if c != c_r: self.state = FINISHED self.set_exception(Exception( 'ACTIVE AND REPLICA CAS CHECK FAILED :: Key: %s, Bad result for CAS value: REPLICA CAS %s != ACTIVE CAS %s' % ( key, c_r, c))) if d != d_r: self.state = FINISHED self.set_exception(Exception( 'ACTIVE AND REPLICA VALUE CHECK FAILED :: Key: %s, Bad result for Value value: REPLICA VALUE %s != ACTIVE VALUE %s' % ( key, d_r, d))) except MemcachedError as error: if error.status == ERR_NOT_FOUND and partition.get_valid(key) is None: pass else: self.state = FINISHED self.set_exception(error) except Exception as error: self.log.error("Unexpected error: %s" % str(error)) self.state = FINISHED self.set_exception(error) def _check_deleted_key(self, key, bucket, scope=None, collection=None): partition = self.kv_store.acquire_partition(key, bucket, scope=scope, collection=collection) try: self.client.delete(key, scope=scope, collection=collection) if partition.get_valid(key) is not None: self.state = FINISHED self.set_exception(Exception('ACTIVE CHECK :: Not Deletes: %s' % key)) except MemcachedError as error: if error.status == ERR_NOT_FOUND: pass else: self.state = FINISHED self.set_exception(error) except Exception as error: if error.rc != NotFoundError: self.state = FINISHED self.set_exception(error) self.kv_store.release_partition(key, bucket, scope=scope, collection=collection) class BatchedValidateDataTask(GenericLoadingTask): def __init__(self, server, bucket, kv_store, max_verify=None, only_store_hash=True, batch_size=100, timeout_sec=30, compression=True, scope=None, collection=None): GenericLoadingTask.__init__(self, server, bucket, kv_store, compression=compression, scope=scope, collection=collection) self.collection = collection self.scope = scope self.bucket = bucket self.valid_keys, self.deleted_keys = kv_store.key_set(bucket=self.bucket, scope=self.scope, collection=self.collection) self.num_valid_keys = len(self.valid_keys) self.num_deleted_keys = len(self.deleted_keys) self.itr = 0 self.max_verify = self.num_valid_keys + self.num_deleted_keys self.timeout_sec = timeout_sec self.only_store_hash = only_store_hash if max_verify is not None: self.max_verify = min(max_verify, self.max_verify) self.log.info("%s items will be verified on %s bucket" % (self.max_verify, bucket)) self.batch_size = batch_size self.start_time = time.time() def has_next(self): has = False if self.itr < (self.num_valid_keys + self.num_deleted_keys) and self.itr < self.max_verify: has = True if math.fmod(self.itr, 10000) == 0.0: self.log.info("{0} items were verified".format(self.itr)) if not has: self.log.info("{0} items were verified in {1} sec.the average number of ops\ - {2} per second".format(self.itr, time.time() - self.start_time, self.itr // (time.time() - self.start_time)).rstrip()) return has def __next__(self): if self.itr < self.num_valid_keys: keys_batch = self.valid_keys[self.itr:self.itr + self.batch_size] self.itr += len(keys_batch) self._check_valid_keys(keys_batch, self.bucket, self.scope, self.collection) else: self._check_deleted_key(self.deleted_keys[self.itr - self.num_valid_keys], self.bucket, self.scope, self.collection) self.itr += 1 def _check_valid_keys(self, keys, bucket, scope=None, collection=None): partition_keys_dic = self.kv_store.acquire_partitions(keys, bucket, scope=scope, collection=collection) try: key_vals = self.client.getMulti(keys, parallel=True, timeout_sec=self.timeout_sec, scope=scope, collection=collection) except ValueError as error: self.log.error("Read failed via memcached client. Error: %s" % str(error)) self.state = FINISHED self.kv_store.release_partitions(list(partition_keys_dic.keys())) self.set_exception(error) return except BaseException as error: # handle all other exception, for instance concurrent.futures._base.TimeoutError self.log.error("Read failed via memcached client. Error: %s" % str(error)) self.state = FINISHED self.kv_store.release_partitions(list(partition_keys_dic.keys())) self.set_exception(error) return for partition, keys in list(partition_keys_dic.items()): self._check_validity(partition, keys, key_vals) self.kv_store.release_partitions(list(partition_keys_dic.keys())) def _check_validity(self, partition, keys, key_vals): for key in keys: value = partition.get_valid(key) flag = partition.get_flag(key) if value is None: continue try: o, c, d = key_vals[key] if self.only_store_hash: if crc32.crc32_hash(d) != int(value): self.state = FINISHED self.set_exception( Exception('Key: %s Bad hash result: %d != %d' % (key, crc32.crc32_hash(d), int(value)))) else: # value = json.dumps(value) if json.loads(d) != json.loads(value): self.state = FINISHED self.set_exception(Exception('Key: %s Bad result: %s != %s' % (key, json.dumps(d), value))) if CHECK_FLAG and o != flag: self.state = FINISHED self.set_exception( Exception('Key: %s Bad result for flag value: %s != the value we set: %s' % (key, o, flag))) except KeyError as error: self.state = FINISHED self.set_exception(error) def _check_deleted_key(self, key, bucket, scope=None, collection=None): partition = self.kv_store.acquire_partition(key, bucket, scope=scope, collection=collection) try: self.client.delete(key, scope=scope, collection=collection) if partition.get_valid(key) is not None: self.state = FINISHED self.set_exception(Exception('Not Deletes: %s' % (key))) except MemcachedError as error: if error.status == ERR_NOT_FOUND: pass else: self.state = FINISHED self.kv_store.release_partition(key, bucket, scope=scope, collection=collection) self.set_exception(error) except Exception as error: if error.rc != NotFoundError: self.state = FINISHED self.kv_store.release_partition(key, bucket, scope=scope, collection=collection) self.set_exception(error) self.kv_store.release_partition(key, bucket, scope=scope, collection=collection) class VerifyRevIdTask(GenericLoadingTask): def __init__(self, src_server, dest_server, bucket, src_kv_store, dest_kv_store, max_err_count=200000, max_verify=None, compression=True, scope=None, collection=None): GenericLoadingTask.__init__(self, src_server, bucket, src_kv_store, compression=compression, scope=scope, collection=collection) from memcached.helper.data_helper import VBucketAwareMemcached as SmartClient self.collection = collection self.scope = scope self.client_src = SmartClient(RestConnection(src_server), bucket) self.client_dest = SmartClient(RestConnection(dest_server), bucket) self.src_valid_keys, self.src_deleted_keys = src_kv_store.key_set(bucket=self.bucket, scope=self.scope, collection=self.collection) self.dest_valid_keys, self.dest_del_keys = dest_kv_store.key_set(bucket=self.bucket, scope=self.scope, collection=self.collection) self.num_valid_keys = len(self.src_valid_keys) self.num_deleted_keys = len(self.src_deleted_keys) self.keys_not_found = {self.client.rest.ip: [], self.client_dest.rest.ip: []} if max_verify: self.max_verify = max_verify else: self.max_verify = self.num_valid_keys + self.num_deleted_keys self.itr = 0 self.not_matching_filter_keys = 0 self.err_count = 0 self.max_err_count = max_err_count self.src_server = src_server self.bucket = bucket self.log.info(f"RevID verification: in progress for {self.bucket.name} in scope:{scope}" f" in collection: {collection}") def has_next(self): if self.itr < (self.num_valid_keys + self.num_deleted_keys) and \ self.err_count < self.max_err_count and \ self.itr < self.max_verify: return True self.log.info("RevId Verification : {0} existing items have been verified" .format(self.itr if self.itr < self.num_valid_keys else self.num_valid_keys)) self.log.info("RevId Verification : {0} deleted items have been verified" .format(self.itr - self.num_valid_keys if self.itr > self.num_valid_keys else 0)) self.log.info("RevId Verification : {0} keys were apparently filtered " "out and not found in target bucket" .format(self.not_matching_filter_keys)) # if there are missing keys, we would have printed them by now # check if excess keys are present on server, if yes, set an exception # TODO : print excess keys server = RestConnection(self.src_server) server_count = server.fetch_bucket_stats(bucket=self.bucket.name)["op"]["samples"]["curr_items"][-1] if server_count > self.num_valid_keys: self.set_exception(Exception("ERROR: {0} keys present on bucket {1} " "on {2} while kvstore expects only {3}" .format(server_count, self.bucket.name, self.src_server.ip, self.num_valid_keys))) return False def __next__(self): if self.itr < self.num_valid_keys: self._check_key_revId(self.src_valid_keys[self.itr], collection=self.collection) elif self.itr < (self.num_valid_keys + self.num_deleted_keys): # verify deleted/expired keys self._check_key_revId(self.src_deleted_keys[self.itr - self.num_valid_keys], ignore_meta_data=['expiration', 'cas'], collection=self.collection) self.itr += 1 # show progress of verification for every 50k items if math.fmod(self.itr, 50000) == 0.0: self.log.info("{0} items have been verified".format(self.itr)) def __get_meta_data(self, client, key, scope=None, collection=None): try: mc = client.memcached(key) meta_data = eval("{'deleted': %s, 'flags': %s, 'expiration': %s, 'seqno': %s, 'cas': %s}" % ( mc.getMeta(key, scope=scope, collection=collection))) return meta_data except MemcachedError as error: if error.status == ERR_NOT_FOUND: # if a filter was specified, the key will not be found in # target kv store if key did not match filter expression if key not in self.src_deleted_keys and key in (self.dest_valid_keys + self.dest_del_keys): self.err_count += 1 self.keys_not_found[client.rest.ip].append( ("key: %s" % key, "vbucket: %s" % client._get_vBucket_id(key, scope=scope, collection=collection))) else: self.not_matching_filter_keys += 1 else: self.state = FINISHED self.set_exception(error) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def _check_key_revId(self, key, ignore_meta_data=None, scope=None, collection=None): if ignore_meta_data is None: ignore_meta_data = [] src_meta_data = self.__get_meta_data(self.client_src, key, scope=scope, collection=collection) dest_meta_data = self.__get_meta_data(self.client_dest, key, scope=scope, collection=collection) if not src_meta_data or not dest_meta_data: return prev_error_count = self.err_count err_msg = [] # seqno number should never be zero if src_meta_data['seqno'] == 0: self.err_count += 1 err_msg.append( "seqno on Source should not be 0, Error Count:{0}".format(self.err_count)) if dest_meta_data['seqno'] == 0: self.err_count += 1 err_msg.append( "seqno on Destination should not be 0, Error Count:{0}".format(self.err_count)) # verify all metadata for meta_key in list(src_meta_data.keys()): check = True if meta_key == 'flags' and not CHECK_FLAG: check = False if check and src_meta_data[meta_key] != dest_meta_data[meta_key] and meta_key not in ignore_meta_data: self.err_count += 1 err_msg.append("{0} mismatch: Source {0}:{1}, Destination {0}:{2}, Error Count:{3}" .format(meta_key, src_meta_data[meta_key], dest_meta_data[meta_key], self.err_count)) if self.err_count - prev_error_count > 0 and self.err_count < 200: self.log.error("===== Verifying rev_ids failed for key: {0}, bucket:{1} =====".format(key, self.bucket)) [self.log.error(err) for err in err_msg] self.log.error("Source meta data: %s" % src_meta_data) self.log.error("Dest meta data: %s" % dest_meta_data) self.state = FINISHED class VerifyCollectionDocCountTask(Task): def __init__(self, src, dest, bucket, mapping): Task.__init__(self, "verify_collection_doc_count_task") self.src = src self.dest = dest self.bucket = bucket self.mapping = mapping self.src_conn = CollectionsStats(src.get_master_node()) self.dest_conn = CollectionsStats(dest.get_master_node()) self.src_stats = self.src_conn.get_collection_stats(self.bucket)[0] self.dest_stats = self.dest_conn.get_collection_stats(self.bucket)[0] def execute(self, task_manager): try: for map_exp in self.mapping.items(): if ':' in map_exp[0]: src_scope = map_exp[0].split(':')[0] src_collection = map_exp[0].split(':')[1] src_count = self.src_conn.get_collection_item_count(self.bucket, src_scope, src_collection, self.src.get_nodes(), self.src_stats) else: src_scope = map_exp[0] src_collection = "all" src_count = self.src_conn.get_scope_item_count(self.bucket, src_scope, self.src.get_nodes(), self.src_stats) if map_exp[1]: if map_exp[1].lower() == "null": self.log.info("{} mapped to null, skipping doc count verification" .format()) dest_collection_specified = False if ':' in map_exp[1]: dest_collection_specified = True dest_scope = map_exp[1].split(':')[0] dest_collection = map_exp[1].split(':')[1] elif "colon" in map_exp[1]: dest_collection_specified = True dest_scope = map_exp[1].split("colon")[0] dest_collection = map_exp[1].split("colon")[1] if dest_collection_specified: dest_count = self.dest_conn.get_collection_item_count(self.bucket, dest_scope, dest_collection, self.dest.get_nodes(), self.dest_stats) else: dest_scope = map_exp[1] dest_collection = "all" dest_count = self.dest_conn.get_scope_item_count(self.bucket, dest_scope, self.dest.get_nodes(), self.dest_stats) self.log.info('-' * 100) if src_count == dest_count: self.log.info("Item count on src:{} {} = {} on dest:{} for " "bucket {} \nsrc : scope {}-> collection {}," "dest: scope {}-> collection {}" .format(self.src.get_master_node().ip, src_count, dest_count, self.dest.get_master_node().ip, self.bucket, src_scope, src_collection, dest_scope, dest_collection)) else: self.set_exception(Exception("ERROR: Item count on src:{} {} != {} on dest:{} for " "bucket {} \nsrc : scope {}-> collection {}," "dest: scope {}-> collection {}" .format(self.src.get_master_node().ip, src_count, dest_count, self.dest.get_master_node().ip, self.bucket, src_scope, src_collection, dest_scope, dest_collection))) self.log.info('-' * 100) except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) self.check(task_manager) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) class VerifyMetaDataTask(GenericLoadingTask): def __init__(self, dest_server, bucket, kv_store, meta_data_store, max_err_count=100, compression=True, scope=None, collection=None): GenericLoadingTask.__init__(self, dest_server, bucket, kv_store, compression=compression, scope=scope, collection=collection) from memcached.helper.data_helper import VBucketAwareMemcached as SmartClient self.collections = collection self.scope = scope self.client = SmartClient(RestConnection(dest_server), bucket) self.valid_keys, self.deleted_keys = kv_store.key_set(bucket=self.bucket, scope=self.scope, collection=self.collection) self.num_valid_keys = len(self.valid_keys) self.num_deleted_keys = len(self.deleted_keys) self.keys_not_found = {self.client.rest.ip: [], self.client.rest.ip: []} self.itr = 0 self.err_count = 0 self.max_err_count = max_err_count self.meta_data_store = meta_data_store def has_next(self): if self.itr < (self.num_valid_keys + self.num_deleted_keys) and self.err_count < self.max_err_count: return True self.log.info("Meta Data Verification : {0} existing items have been verified" .format(self.itr if self.itr < self.num_valid_keys else self.num_valid_keys)) self.log.info("Meta Data Verification : {0} deleted items have been verified" .format(self.itr - self.num_valid_keys if self.itr > self.num_valid_keys else 0)) return False def __next__(self): if self.itr < self.num_valid_keys: self._check_key_meta_data(self.valid_keys[self.itr], self.collections) elif self.itr < (self.num_valid_keys + self.num_deleted_keys): # verify deleted/expired keys self._check_key_meta_data(self.deleted_keys[self.itr - self.num_valid_keys], ignore_meta_data=['expiration'], scope=self.scope, collection=self.collections) self.itr += 1 # show progress of verification for every 50k items if math.fmod(self.itr, 50000) == 0.0: self.log.info("{0} items have been verified".format(self.itr)) def __get_meta_data(self, client, key, scope=None, collection=None): try: mc = client.memcached(key) meta_data = eval("{'deleted': %s, 'flags': %s, 'expiration': %s, 'seqno': %s, 'cas': %s}" % ( mc.getMeta(key, scope=scope, collection=collection))) return meta_data except MemcachedError as error: if error.status == ERR_NOT_FOUND: if key not in self.deleted_keys: self.err_count += 1 self.keys_not_found[client.rest.ip].append( ("key: %s" % key, "vbucket: %s" % client._get_vBucket_id(key))) else: self.state = FINISHED self.set_exception(error) def _check_key_meta_data(self, key, ignore_meta_data=[], scope=None, collection=None): src_meta_data = self.meta_data_store[key] dest_meta_data = self.__get_meta_data(self.client, key, scope=scope, collection=collection) if not src_meta_data or not dest_meta_data: return prev_error_count = self.err_count err_msg = [] # seqno number should never be zero if dest_meta_data['seqno'] == 0: self.err_count += 1 err_msg.append( "seqno on Destination should not be 0, Error Count:{0}".format(self.err_count)) # verify all metadata for meta_key in list(src_meta_data.keys()): if src_meta_data[meta_key] != dest_meta_data[meta_key] and meta_key not in ignore_meta_data: self.err_count += 1 err_msg.append("{0} mismatch: Source {0}:{1}, Destination {0}:{2}, Error Count:{3}" .format(meta_key, src_meta_data[meta_key], dest_meta_data[meta_key], self.err_count)) if self.err_count - prev_error_count > 0: self.log.error("===== Verifying meta data failed for key: {0} =====".format(key)) [self.log.error(err) for err in err_msg] self.log.error("Source meta data: %s" % src_meta_data) self.log.error("Dest meta data: %s" % dest_meta_data) self.state = FINISHED class GetMetaDataTask(GenericLoadingTask): def __init__(self, dest_server, bucket, kv_store, compression=True, scope=None, collection=None): GenericLoadingTask.__init__(self, dest_server, bucket, kv_store, compression=compression, scope=scope, collection=collection) from memcached.helper.data_helper import VBucketAwareMemcached as SmartClient self.collection = collection self.scope = scope self.client = SmartClient(RestConnection(dest_server), bucket) self.valid_keys, self.deleted_keys = kv_store.key_set(bucket=self.bucket, scope=self.scope, collection=self.collection) self.num_valid_keys = len(self.valid_keys) self.num_deleted_keys = len(self.deleted_keys) self.keys_not_found = {self.client.rest.ip: [], self.client.rest.ip: []} self.itr = 0 self.err_count = 0 self.max_err_count = 100 self.meta_data_store = {} def has_next(self): if self.itr < (self.num_valid_keys + self.num_deleted_keys) and self.err_count < self.max_err_count: return True self.log.info("Get Meta Data : {0} existing items have been gathered" .format(self.itr if self.itr < self.num_valid_keys else self.num_valid_keys)) self.log.info("Get Meta Data : {0} deleted items have been gathered" .format(self.itr - self.num_valid_keys if self.itr > self.num_valid_keys else 0)) return False def __next__(self): if self.itr < self.num_valid_keys: self.meta_data_store[self.valid_keys[self.itr]] = self.__get_meta_data(self.client, self.valid_keys[self.itr], self.scope, self.collection) elif self.itr < (self.num_valid_keys + self.num_deleted_keys): self.meta_data_store[self.deleted_keys[self.itr - self.num_valid_keys]] = self.__get_meta_data(self.client, self.deleted_keys[ self.itr - self.num_valid_keys], scope=self.scope, collection=self.collection) self.itr += 1 def __get_meta_data(self, client, key, scope=None, collection=None): try: mc = client.memcached(key) meta_data = eval("{'deleted': %s, 'flags': %s, 'expiration': %s, 'seqno': %s, 'cas': %s}" % ( mc.getMeta(key, scope=scope, collection=collection))) return meta_data except MemcachedError as error: if error.status == ERR_NOT_FOUND: if key not in self.deleted_keys: self.err_count += 1 self.keys_not_found[client.rest.ip].append( ("key: %s" % key, "vbucket: %s" % client._get_vBucket_id(key))) else: self.state = FINISHED self.set_exception(error) def get_meta_data_store(self): return self.meta_data_store class ViewCreateTask(Task): def __init__(self, server, design_doc_name, view, bucket="default", with_query=True, check_replication=False, ddoc_options=None): Task.__init__(self, "create_view_task") self.server = server self.bucket = bucket self.view = view prefix = "" if self.view: prefix = ("", "dev_")[self.view.dev_view] if design_doc_name.find('/') != -1: design_doc_name = design_doc_name.replace('/', '%2f') self.design_doc_name = prefix + design_doc_name self.ddoc_rev_no = 0 self.with_query = with_query self.check_replication = check_replication self.ddoc_options = ddoc_options self.rest = RestConnection(self.server) def execute(self, task_manager): try: # appending view to existing design doc content, meta = self.rest.get_ddoc(self.bucket, self.design_doc_name) ddoc = DesignDocument._init_from_json(self.design_doc_name, content) # if view is to be updated if self.view: if self.view.is_spatial: ddoc.add_spatial_view(self.view) else: ddoc.add_view(self.view) self.ddoc_rev_no = self._parse_revision(meta['rev']) except ReadDocumentException: # creating first view in design doc if self.view: if self.view.is_spatial: ddoc = DesignDocument(self.design_doc_name, [], spatial_views=[self.view]) else: ddoc = DesignDocument(self.design_doc_name, [self.view]) # create an empty design doc else: ddoc = DesignDocument(self.design_doc_name, []) if self.ddoc_options: ddoc.options = self.ddoc_options # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) try: self.rest.create_design_document(self.bucket, ddoc) self.state = CHECKING task_manager.schedule(self) except DesignDocCreationException as e: self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): try: # only query if the DDoc has a view if self.view: if self.with_query: query = {"stale": "ok"} if self.view.is_spatial: content = \ self.rest.query_view(self.design_doc_name, self.view.name, self.bucket, query, type="spatial") else: content = \ self.rest.query_view(self.design_doc_name, self.view.name, self.bucket, query) else: _, json_parsed, _ = self.rest._get_design_doc(self.bucket, self.design_doc_name) if self.view.is_spatial: if self.view.name not in list(json_parsed["spatial"].keys()): self.set_exception( Exception("design doc {O} doesn't contain spatial view {1}".format( self.design_doc_name, self.view.name))) else: if self.view.name not in list(json_parsed["views"].keys()): self.set_exception(Exception("design doc {O} doesn't contain view {1}".format( self.design_doc_name, self.view.name))) self.log.info( "view : {0} was created successfully in ddoc: {1}".format(self.view.name, self.design_doc_name)) else: # if we have reached here, it means design doc was successfully updated self.log.info("Design Document : {0} was updated successfully".format(self.design_doc_name)) self.state = FINISHED if self._check_ddoc_revision(): self.set_result(self.ddoc_rev_no) else: self.set_exception(Exception("failed to update design document")) if self.check_replication: self._check_ddoc_replication_on_nodes() except QueryViewException as e: if str(e).find('not_found') or str(e).find('view_undefined') > -1: task_manager.schedule(self, 2) else: self.state = FINISHED self.set_unexpected_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def _check_ddoc_revision(self): valid = False try: content, meta = self.rest.get_ddoc(self.bucket, self.design_doc_name) new_rev_id = self._parse_revision(meta['rev']) if new_rev_id != self.ddoc_rev_no: self.ddoc_rev_no = new_rev_id valid = True except ReadDocumentException: pass # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) return valid def _parse_revision(self, rev_string): return int(rev_string.split('-')[0]) def _check_ddoc_replication_on_nodes(self): nodes = self.rest.node_statuses() retry_count = 3 # nothing to check if there is only 1 node if len(nodes) <= 1: return for node in nodes: server_info = {"ip": node.ip, "port": node.port, "username": self.rest.username, "password": self.rest.password} for count in range(retry_count): try: rest_node = RestConnection(server_info) content, meta = rest_node.get_ddoc(self.bucket, self.design_doc_name) new_rev_id = self._parse_revision(meta['rev']) if new_rev_id == self.ddoc_rev_no: break else: self.log.info("Design Doc {0} version is not updated on node {1}:{2}. Retrying.".format( self.design_doc_name, node.ip, node.port)) time.sleep(2) except ReadDocumentException as e: if (count < retry_count): self.log.info( "Design Doc {0} not yet available on node {1}:{2}. Retrying.".format(self.design_doc_name, node.ip, node.port)) time.sleep(2) else: self.log.error( "Design Doc {0} failed to replicate on node {1}:{2}".format(self.design_doc_name, node.ip, node.port)) self.set_exception(e) self.state = FINISHED break except Exception as e: if (count < retry_count): self.log.info("Unexpected Exception Caught. Retrying.") time.sleep(2) else: self.set_unexpected_exception(e) self.state = FINISHED break else: self.set_exception(Exception( "Design Doc {0} version mismatch on node {1}:{2}".format(self.design_doc_name, node.ip, node.port))) class ViewDeleteTask(Task): def __init__(self, server, design_doc_name, view, bucket="default"): Task.__init__(self, "delete_view_task") self.server = server self.bucket = bucket self.view = view prefix = "" if self.view: prefix = ("", "dev_")[self.view.dev_view] self.design_doc_name = prefix + design_doc_name def execute(self, task_manager): try: rest = RestConnection(self.server) if self.view: # remove view from existing design doc content, header = rest.get_ddoc(self.bucket, self.design_doc_name) ddoc = DesignDocument._init_from_json(self.design_doc_name, content) if self.view.is_spatial: status = ddoc.delete_spatial(self.view) else: status = ddoc.delete_view(self.view) if not status: self.state = FINISHED self.set_exception(Exception('View does not exist! %s' % (self.view.name))) # update design doc rest.create_design_document(self.bucket, ddoc) self.state = CHECKING task_manager.schedule(self, 2) else: # delete the design doc rest.delete_view(self.bucket, self.design_doc_name) self.log.info("Design Doc : {0} was successfully deleted".format(self.design_doc_name)) self.state = FINISHED self.set_result(True) except (ValueError, ReadDocumentException, DesignDocCreationException) as e: self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): try: rest = RestConnection(self.server) # make sure view was deleted query = {"stale": "ok"} content = \ rest.query_view(self.design_doc_name, self.view.name, self.bucket, query) self.state = FINISHED self.set_result(False) except QueryViewException as e: self.log.info( "view : {0} was successfully deleted in ddoc: {1}".format(self.view.name, self.design_doc_name)) self.state = FINISHED self.set_result(True) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) class ViewQueryTask(Task): def __init__(self, server, design_doc_name, view_name, query, expected_rows=None, bucket="default", retry_time=2): Task.__init__(self, "query_view_task") self.server = server self.bucket = bucket self.view_name = view_name self.design_doc_name = design_doc_name self.query = query self.expected_rows = expected_rows self.retry_time = retry_time self.timeout = 900 def execute(self, task_manager): try: rest = RestConnection(self.server) # make sure view can be queried content = \ rest.query_view(self.design_doc_name, self.view_name, self.bucket, self.query, self.timeout) if self.expected_rows is None: # no verification self.state = FINISHED self.set_result(content) else: self.state = CHECKING task_manager.schedule(self) except QueryViewException as e: # initial query failed, try again task_manager.schedule(self, self.retry_time) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): try: rest = RestConnection(self.server) # query and verify expected num of rows returned content = \ rest.query_view(self.design_doc_name, self.view_name, self.bucket, self.query, self.timeout) self.log.info("Server: %s, Design Doc: %s, View: %s, (%d rows) expected, (%d rows) returned" % \ (self.server.ip, self.design_doc_name, self.view_name, self.expected_rows, len(content['rows']))) raised_error = content.get('error', '') or ''.join([str(item) for item in content.get('errors', [])]) if raised_error: raise QueryViewException(self.view_name, raised_error) if len(content['rows']) == self.expected_rows: self.log.info("expected number of rows: '{0}' was found for view query".format(self. expected_rows)) self.state = FINISHED self.set_result(True) else: if len(content['rows']) > self.expected_rows: raise QueryViewException(self.view_name, "Server: {0}, Design Doc: {1}, actual returned rows: '{2}' are greater than expected {3}" .format(self.server.ip, self.design_doc_name, len(content['rows']), self.expected_rows, )) if "stale" in self.query: if self.query["stale"].lower() == "false": self.state = FINISHED self.set_result(False) # retry until expected results or task times out task_manager.schedule(self, self.retry_time) except QueryViewException as e: # subsequent query failed! exit self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) class N1QLQueryTask(Task): def __init__(self, server, bucket, query, n1ql_helper=None, expected_result=None, verify_results=True, is_explain_query=False, index_name=None, retry_time=2, scan_consistency=None, scan_vector=None): Task.__init__(self, "query_n1ql_task") self.server = server self.bucket = bucket self.query = query self.expected_result = expected_result self.n1ql_helper = n1ql_helper self.timeout = 900 self.verify_results = verify_results self.is_explain_query = is_explain_query self.index_name = index_name self.retry_time = 2 self.scan_consistency = scan_consistency self.scan_vector = scan_vector def execute(self, task_manager): try: # Query and get results self.log.info(" <<<<< START Executing Query {0} >>>>>>".format(self.query)) if not self.is_explain_query: self.msg, self.isSuccess = self.n1ql_helper.run_query_and_verify_result( query=self.query, server=self.server, expected_result=self.expected_result, scan_consistency=self.scan_consistency, scan_vector=self.scan_vector, verify_results=self.verify_results) else: self.actual_result = self.n1ql_helper.run_cbq_query(query=self.query, server=self.server, scan_consistency=self.scan_consistency, scan_vector=self.scan_vector) self.log.info(self.actual_result) self.log.info(" <<<<< Done Executing Query {0} >>>>>>".format(self.query)) self.state = CHECKING task_manager.schedule(self) except N1QLQueryException as e: self.state = FINISHED # initial query failed, try again task_manager.schedule(self, self.retry_time) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): try: # Verify correctness of result set if self.verify_results: if not self.is_explain_query: if not self.isSuccess: self.log.info(" Query {0} results leads to INCORRECT RESULT ".format(self.query)) raise N1QLQueryException(self.msg) else: check = self.n1ql_helper.verify_index_with_explain(self.actual_result, self.index_name) if not check: actual_result = self.n1ql_helper.run_cbq_query(query="select * from system:indexes", server=self.server) self.log.info(actual_result) raise Exception( " INDEX usage in Query {0} :: NOT FOUND {1} :: as observed in result {2}".format( self.query, self.index_name, self.actual_result)) self.log.info(" <<<<< Done VERIFYING Query {0} >>>>>>".format(self.query)) self.set_result(True) self.state = FINISHED except N1QLQueryException as e: # subsequent query failed! exit self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) class CreateIndexTask(Task): def __init__(self, server, bucket, index_name, query, n1ql_helper=None, retry_time=2, defer_build=False, timeout=240): Task.__init__(self, "create_index_task") self.server = server self.bucket = bucket self.defer_build = defer_build self.query = query self.index_name = index_name self.n1ql_helper = n1ql_helper self.retry_time = 2 self.timeout = timeout def execute(self, task_manager): try: # Query and get results self.n1ql_helper.run_cbq_query(query=self.query, server=self.server) self.state = CHECKING task_manager.schedule(self) except CreateIndexException as e: # initial query failed, try again self.state = FINISHED task_manager.schedule(self, self.retry_time) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.log.error(e) self.set_exception(e) #if not "will retry building in the background for reason" in e: # self.log.error(e) # self.set_exception(e) def check(self, task_manager): try: # Verify correctness of result set check = True if not self.defer_build: check = self.n1ql_helper.is_index_online_and_in_list(self.bucket, self.index_name, server=self.server, timeout=self.timeout) if not check: raise CreateIndexException("Index {0} not created as expected ".format(self.index_name)) self.set_result(True) self.state = FINISHED except CreateIndexException as e: # subsequent query failed! exit self.state = FINISHED self.log.error(e) self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.log.error(e) self.set_exception(e) class BuildIndexTask(Task): def __init__(self, server, bucket, query, n1ql_helper=None, retry_time=2): Task.__init__(self, "build_index_task") self.server = server self.bucket = bucket self.query = query self.n1ql_helper = n1ql_helper self.retry_time = 2 def execute(self, task_manager): try: # Query and get results self.n1ql_helper.run_cbq_query(query=self.query, server=self.server) self.state = CHECKING task_manager.schedule(self) except CreateIndexException as e: # initial query failed, try again self.state = FINISHED task_manager.schedule(self, self.retry_time) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): try: # Verify correctness of result set self.set_result(True) self.state = FINISHED except CreateIndexException as e: # subsequent query failed! exit self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) class MonitorIndexTask(Task): def __init__(self, server, bucket, index_name, n1ql_helper=None, retry_time=2, timeout=240): Task.__init__(self, "build_index_task") self.server = server self.bucket = bucket self.index_name = index_name self.n1ql_helper = n1ql_helper self.retry_time = 2 self.timeout = timeout def execute(self, task_manager): try: check = self.n1ql_helper.is_index_online_and_in_list(self.bucket, self.index_name, server=self.server, timeout=self.timeout) if not check: self.state = FINISHED raise CreateIndexException("Index {0} not created as expected ".format(self.index_name)) self.state = CHECKING task_manager.schedule(self) except CreateIndexException as e: # initial query failed, try again self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): try: self.set_result(True) self.state = FINISHED except CreateIndexException as e: # subsequent query failed! exit self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) class DropIndexTask(Task): def __init__(self, server, bucket, index_name, query, n1ql_helper=None, retry_time=2): Task.__init__(self, "drop_index_task") self.server = server self.bucket = bucket self.query = query self.index_name = index_name self.n1ql_helper = n1ql_helper self.timeout = 900 self.retry_time = 2 def execute(self, task_manager): try: # Query and get results check = self.n1ql_helper._is_index_in_list(self.bucket, self.index_name, server=self.server) if not check: raise DropIndexException("index {0} does not exist will not drop".format(self.index_name)) self.n1ql_helper.run_cbq_query(query=self.query, server=self.server) self.state = CHECKING task_manager.schedule(self) except N1QLQueryException as e: # initial query failed, try again self.state = FINISHED task_manager.schedule(self, self.retry_time) # catch and set all unexpected exceptions except DropIndexException as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): try: # Verify correctness of result set check = self.n1ql_helper._is_index_in_list(self.bucket, self.index_name, server=self.server) if check: raise Exception("Index {0} not dropped as expected ".format(self.index_name)) self.set_result(True) self.state = FINISHED except DropIndexException as e: # subsequent query failed! exit self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) class MonitorViewQueryResultsTask(Task): def __init__(self, servers, design_doc_name, view, query, expected_docs=None, bucket="default", retries=100, error=None, verify_rows=False, server_to_query=0): Task.__init__(self, "query_view_task") self.servers = servers self.bucket = bucket self.view_name = view.name self.view = view self.design_doc_name = design_doc_name self.query = query self.retries = retries self.current_retry = 0 self.timeout = 900 self.error = error self.expected_docs = expected_docs self.verify_rows = verify_rows self.rest = RestConnection(self.servers[server_to_query]) self.results = None self.connection_timeout = 60000 self.query["connection_timeout"] = self.connection_timeout if self.design_doc_name.find("dev_") == 0: self.query["full_set"] = "true" def execute(self, task_manager): try: self.current_retry += 1 self.results = self.rest.query_view( self.design_doc_name, self.view_name, self.bucket, self.query, self.timeout) raised_error = self.results.get('error', '') or ''.join( [str(item) for item in self.results.get('errors', [])]) if raised_error: raise QueryViewException(self.view_name, raised_error) else: self.log.info("view %s, query %s: expected- %s, actual -%s" % ( self.design_doc_name, self.query, len(self.expected_docs), len(self.results.get('rows', [])))) self.state = CHECKING task_manager.schedule(self) except QueryViewException as ex: self.log.error("During query run (ddoc=%s, query=%s, server=%s) error is: %s" % ( self.design_doc_name, self.query, self.servers[0].ip, str(ex))) if self.error and str(ex).find(self.error) != -1: self.state = FINISHED self.set_result({"passed": True, "errors": str(ex)}) elif self.current_retry == self.retries: self.state = FINISHED self.set_result({"passed": False, "errors": str(ex)}) elif str(ex).find('view_undefined') != -1 or \ str(ex).find('not_found') != -1 or \ str(ex).find('unable to reach') != -1 or \ str(ex).find('socket error') != -1 or \ str(ex).find('econnrefused') != -1 or \ str(ex).find("doesn't exist") != -1 or \ str(ex).find('missing') != -1 or \ str(ex).find("Undefined set view") != -1: self.log.error( "view_results not ready yet ddoc=%s , try again in 10 seconds..." % self.design_doc_name) task_manager.schedule(self, 10) elif str(ex).find('timeout') != -1: self.connection_timeout = self.connection_timeout * 2 self.log.error("view_results not ready yet ddoc=%s ," % self.design_doc_name + \ " try again in 10 seconds... and double timeout") task_manager.schedule(self, 10) else: self.state = FINISHED res = {"passed": False, "errors": str(ex)} if self.results and self.results.get('rows', []): res['results'] = self.results self.set_result(res) except Exception as ex: if self.current_retry == self.retries: self.state = CHECKING self.log.error("view %s, query %s: verifying results" % ( self.design_doc_name, self.query)) task_manager.schedule(self) else: self.log.error( "view_results not ready yet ddoc=%s , try again in 10 seconds..." % self.design_doc_name) task_manager.schedule(self, 10) def check(self, task_manager): try: if self.view.red_func and (('reduce' in self.query and \ self.query['reduce'] == "true") or (not 'reduce' in self.query)): if len(self.expected_docs) != len(self.results.get('rows', [])): if self.current_retry == self.retries: self.state = FINISHED msg = "ddoc=%s, query=%s, server=%s" % ( self.design_doc_name, self.query, self.servers[0].ip) msg += "Number of groups expected:%s, actual:%s" % ( len(self.expected_docs), len(self.results.get('rows', []))) self.set_result({"passed": False, "errors": msg}) else: RestHelper(self.rest)._wait_for_indexer_ddoc(self.servers, self.design_doc_name) self.state = EXECUTING task_manager.schedule(self, 10) else: for row in self.expected_docs: key_expected = row['key'] if not (key_expected in [key['key'] for key in self.results.get('rows', [])]): if self.current_retry == self.retries: self.state = FINISHED msg = "ddoc=%s, query=%s, server=%s" % ( self.design_doc_name, self.query, self.servers[0].ip) msg += "Key expected but not present :%s" % (key_expected) self.set_result({"passed": False, "errors": msg}) else: RestHelper(self.rest)._wait_for_indexer_ddoc(self.servers, self.design_doc_name) self.state = EXECUTING task_manager.schedule(self, 10) else: for res in self.results.get('rows', []): if key_expected == res['key']: value = res['value'] break msg = "ddoc=%s, query=%s, server=%s\n" % ( self.design_doc_name, self.query, self.servers[0].ip) msg += "Key %s: expected value %s, actual: %s" % ( key_expected, row['value'], value) self.log.info(msg) if row['value'] == value: self.state = FINISHED self.log.info(msg) self.set_result({"passed": True, "errors": []}) else: if self.current_retry == self.retries: self.state = FINISHED self.log.error(msg) self.set_result({"passed": True, "errors": msg}) else: RestHelper(self.rest)._wait_for_indexer_ddoc(self.servers, self.design_doc_name) self.state = EXECUTING task_manager.schedule(self, 10) return if len(self.expected_docs) > len(self.results.get('rows', [])): if self.current_retry == self.retries: self.state = FINISHED self.set_result({"passed": False, "errors": [], "results": self.results}) else: RestHelper(self.rest)._wait_for_indexer_ddoc(self.servers, self.design_doc_name) if self.current_retry == 70: self.query["stale"] = 'false' self.log.info( "View result is still not expected (ddoc=%s, query=%s, server=%s). retry in 10 sec" % ( self.design_doc_name, self.query, self.servers[0].ip)) self.state = EXECUTING task_manager.schedule(self, 10) elif len(self.expected_docs) < len(self.results.get('rows', [])): self.state = FINISHED self.set_result({"passed": False, "errors": [], "results": self.results}) elif len(self.expected_docs) == len(self.results.get('rows', [])): if self.verify_rows: expected_ids = [row['id'] for row in self.expected_docs] rows_ids = [str(row['id']) for row in self.results['rows']] if expected_ids == rows_ids: self.state = FINISHED self.set_result({"passed": True, "errors": []}) else: if self.current_retry == self.retries: self.state = FINISHED self.set_result({"passed": False, "errors": [], "results": self.results}) else: self.state = EXECUTING task_manager.schedule(self, 10) else: self.state = FINISHED self.set_result({"passed": True, "errors": []}) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.log.error("Exception caught %s" % str(e)) self.set_exception(e) self.set_result({"passed": False, "errors": str(e)}) class ModifyFragmentationConfigTask(Task): """ Given a config dictionary attempt to configure fragmentation settings. This task will override the default settings that are provided for a given <bucket>. """ def __init__(self, server, config=None, bucket="default"): Task.__init__(self, "modify_frag_config_task") self.server = server self.config = {"parallelDBAndVC": "false", "dbFragmentThreshold": None, "viewFragmntThreshold": None, "dbFragmentThresholdPercentage": 100, "viewFragmntThresholdPercentage": 100, "allowedTimePeriodFromHour": None, "allowedTimePeriodFromMin": None, "allowedTimePeriodToHour": None, "allowedTimePeriodToMin": None, "allowedTimePeriodAbort": None, "autoCompactionDefined": "true"} self.bucket = bucket for key in config: self.config[key] = config[key] def execute(self, task_manager): try: rest = RestConnection(self.server) rest.set_auto_compaction(parallelDBAndVC=self.config["parallelDBAndVC"], dbFragmentThreshold=self.config["dbFragmentThreshold"], viewFragmntThreshold=self.config["viewFragmntThreshold"], dbFragmentThresholdPercentage=self.config["dbFragmentThresholdPercentage"], viewFragmntThresholdPercentage=self.config["viewFragmntThresholdPercentage"], allowedTimePeriodFromHour=self.config["allowedTimePeriodFromHour"], allowedTimePeriodFromMin=self.config["allowedTimePeriodFromMin"], allowedTimePeriodToHour=self.config["allowedTimePeriodToHour"], allowedTimePeriodToMin=self.config["allowedTimePeriodToMin"], allowedTimePeriodAbort=self.config["allowedTimePeriodAbort"], bucket=self.bucket) self.state = CHECKING task_manager.schedule(self, 10) except Exception as e: self.state = FINISHED self.set_exception(e) def check(self, task_manager): try: rest = RestConnection(self.server) # verify server accepted settings content = rest.get_bucket_json(self.bucket) if content["autoCompactionSettings"] == False: self.set_exception(Exception("Failed to set auto compaction settings")) else: # retrieved compaction settings self.set_result(True) self.state = FINISHED except GetBucketInfoFailed as e: # subsequent query failed! exit self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) class MonitorActiveTask(Task): """ Attempt to monitor active task that is available in _active_tasks API. It allows to monitor indexer, bucket compaction. Execute function looks at _active_tasks API and tries to identifies task for monitoring and its pid by: task type('indexer' , 'bucket_compaction', 'view_compaction' ) and target value (for example "_design/ddoc" for indexing, bucket "default" for bucket compaction or "_design/dev_view" for view compaction). wait_task=True means that task should be found in the first attempt otherwise, we can assume that the task has been completed( reached 100%). Check function monitors task by pid that was identified in execute func and matches new progress result with the previous. task is failed if: progress is not changed during num_iterations iteration new progress was gotten less then previous task is passed and completed if: progress reached wait_progress value task was not found by pid(believe that it's over) """ def __init__(self, server, type, target_value, wait_progress=100, num_iterations=100, wait_task=True): Task.__init__(self, "monitor_active_task") self.server = server self.type = type # indexer or bucket_compaction self.target_key = "" if self.type == 'indexer': pass # no special actions elif self.type == "bucket_compaction": self.target_key = "original_target" elif self.type == "view_compaction": self.target_key = "designDocument" else: raise Exception("type %s is not defined!" % self.type) self.target_value = target_value self.wait_progress = wait_progress self.num_iterations = num_iterations self.wait_task = wait_task self.rest = RestConnection(self.server) self.current_progress = None self.current_iter = 0 self.task = None def execute(self, task_manager): tasks = self.rest.active_tasks() for task in tasks: if task["type"] == self.type and (( self.target_key == "designDocument" and task[ self.target_key] == self.target_value) or ( self.target_key == "original_target" and task[self.target_key][ "type"] == self.target_value) or ( self.type == 'indexer')): self.current_progress = task["progress"] self.task = task self.log.info("monitoring active task was found:" + str(task)) self.log.info("progress %s:%s - %s %%" % (self.type, self.target_value, task["progress"])) if self.current_progress >= self.wait_progress: self.log.info("expected progress was gotten: %s" % self.current_progress) self.state = FINISHED self.set_result(True) else: self.state = CHECKING task_manager.schedule(self, 5) return if self.wait_task: # task is not performed self.state = FINISHED self.log.error("expected active task %s:%s was not found" % (self.type, self.target_value)) self.set_result(False) else: # task was completed self.state = FINISHED self.log.info("task for monitoring %s:%s completed" % (self.type, self.target_value)) self.set_result(True) def check(self, task_manager): tasks = self.rest.active_tasks() for task in tasks: # if task still exists if task == self.task: self.log.info("progress %s:%s - %s %%" % (self.type, self.target_value, task["progress"])) # reached expected progress if task["progress"] >= self.wait_progress: self.state = FINISHED self.log.error("progress was reached %s" % self.wait_progress) self.set_result(True) # progress value was changed if task["progress"] > self.current_progress: self.current_progress = task["progress"] self.currebt_iter = 0 task_manager.schedule(self, 2) # progress value was not changed elif task["progress"] == self.current_progress: if self.current_iter < self.num_iterations: time.sleep(2) self.current_iter += 1 task_manager.schedule(self, 2) # num iteration with the same progress = num_iterations else: self.state = FINISHED self.log.error( "progress for active task was not changed during %s sec" % 2 * self.num_iterations) self.set_result(False) else: self.state = FINISHED self.log.error("progress for task %s:%s changed direction!" % (self.type, self.target_value)) self.set_result(False) # task was completed self.state = FINISHED self.log.info("task %s:%s was completed" % (self.type, self.target_value)) self.set_result(True) class MonitorViewFragmentationTask(Task): """ Attempt to monitor fragmentation that is occurring for a given design_doc. execute stage is just for preliminary sanity checking of values and environment. Check function looks at index file accross all nodes and attempts to calculate total fragmentation occurring by the views within the design_doc. Note: If autocompaction is enabled and user attempts to monitor for fragmentation value higher than level at which auto_compaction kicks in a warning is sent and it is best user to use lower value as this can lead to infinite monitoring. """ def __init__(self, server, design_doc_name, fragmentation_value=10, bucket="default"): Task.__init__(self, "monitor_frag_task") self.server = server self.bucket = bucket self.fragmentation_value = fragmentation_value self.design_doc_name = design_doc_name def execute(self, task_manager): # sanity check of fragmentation value if self.fragmentation_value < 0 or self.fragmentation_value > 100: err_msg = \ "Invalid value for fragmentation %d" % self.fragmentation_value self.state = FINISHED self.set_exception(Exception(err_msg)) # warning if autocompaction is less than <fragmentation_value> try: auto_compact_percentage = self._get_current_auto_compaction_percentage() if auto_compact_percentage != "undefined" and auto_compact_percentage < self.fragmentation_value: self.log.warning("Auto compaction is set to %s. Therefore fragmentation_value %s may not be reached" % ( auto_compact_percentage, self.fragmentation_value)) self.state = CHECKING task_manager.schedule(self, 5) except GetBucketInfoFailed as e: self.state = FINISHED self.set_exception(e) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def _get_current_auto_compaction_percentage(self): """ check at bucket level and cluster level for compaction percentage """ auto_compact_percentage = None rest = RestConnection(self.server) content = rest.get_bucket_json(self.bucket) if content["autoCompactionSettings"] == False: # try to read cluster level compaction settings content = rest.cluster_status() auto_compact_percentage = \ content["autoCompactionSettings"]["viewFragmentationThreshold"]["percentage"] return auto_compact_percentage def check(self, task_manager): rest = RestConnection(self.server) new_frag_value = MonitorViewFragmentationTask. \ calc_ddoc_fragmentation(rest, self.design_doc_name, bucket=self.bucket) self.log.info("%s: current amount of fragmentation = %d" % (self.design_doc_name, new_frag_value)) if new_frag_value > self.fragmentation_value: self.state = FINISHED self.set_result(True) else: # try again task_manager.schedule(self, 2) @staticmethod def aggregate_ddoc_info(rest, design_doc_name, bucket="default", with_rebalance=False): nodes = rest.node_statuses() info = [] for node in nodes: server_info = {"ip": node.ip, "port": node.port, "username": rest.username, "password": rest.password} rest = RestConnection(server_info) status = False try: status, content = rest.set_view_info(bucket, design_doc_name) except Exception as e: print((str(e))) if "Error occured reading set_view _info" in str(e) and with_rebalance: print(("node {0} {1} is not ready yet?: {2}".format( node.id, node.port, str(e)))) else: raise e if status: info.append(content) return info @staticmethod def calc_ddoc_fragmentation(rest, design_doc_name, bucket="default", with_rebalance=False): total_disk_size = 0 total_data_size = 0 total_fragmentation = 0 nodes_ddoc_info = \ MonitorViewFragmentationTask.aggregate_ddoc_info(rest, design_doc_name, bucket, with_rebalance) total_disk_size = sum([content['disk_size'] for content in nodes_ddoc_info]) total_data_size = sum([content['data_size'] for content in nodes_ddoc_info]) if total_disk_size > 0 and total_data_size > 0: total_fragmentation = \ (total_disk_size - total_data_size) / float(total_disk_size) * 100 return total_fragmentation class ViewCompactionTask(Task): """ Executes view compaction for a given design doc. This is technicially view compaction as represented by the api and also because the fragmentation is generated by the keys emitted by map/reduce functions within views. Task will check that compaction history for design doc is incremented and if any work was really done. """ def __init__(self, server, design_doc_name, bucket="default", with_rebalance=False): Task.__init__(self, "view_compaction_task") self.server = server self.bucket = bucket self.design_doc_name = design_doc_name self.ddoc_id = "_design%2f" + design_doc_name self.compaction_revision = 0 self.precompacted_fragmentation = 0 self.with_rebalance = with_rebalance self.rest = RestConnection(self.server) def execute(self, task_manager): try: self.compaction_revision, self.precompacted_fragmentation = \ self._get_compaction_details() self.log.info("{0}: stats compaction before triggering it: ({1},{2})". format(self.design_doc_name, self.compaction_revision, self.precompacted_fragmentation)) if self.precompacted_fragmentation == 0: self.log.info("%s: There is nothing to compact, fragmentation is 0" % self.design_doc_name) self.set_result(False) self.state = FINISHED return self.rest.ddoc_compaction(self.ddoc_id, self.bucket) self.state = CHECKING task_manager.schedule(self, 2) except (CompactViewFailed, SetViewInfoNotFound) as ex: self.state = FINISHED self.set_exception(ex) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) # verify compaction history incremented and some defraging occurred def check(self, task_manager): try: _compaction_running = self._is_compacting() new_compaction_revision, fragmentation = self._get_compaction_details() self.log.info("{0}: stats compaction:revision and fragmentation: ({1},{2})". format(self.design_doc_name, new_compaction_revision, fragmentation)) if new_compaction_revision == self.compaction_revision and _compaction_running: # compaction ran successfully but compaction was not changed # perhaps we are still compacting self.log.info("design doc {0} is compacting".format(self.design_doc_name)) task_manager.schedule(self, 3) elif new_compaction_revision > self.compaction_revision or \ self.precompacted_fragmentation > fragmentation: self.log.info( "{1}: compactor was run, compaction revision was changed on {0}".format(new_compaction_revision, self.design_doc_name)) frag_val_diff = fragmentation - self.precompacted_fragmentation self.log.info("%s: fragmentation went from %d to %d" % \ (self.design_doc_name, self.precompacted_fragmentation, fragmentation)) if frag_val_diff > 0: # compaction ran successfully but datasize still same # perhaps we are still compacting if self._is_compacting(): task_manager.schedule(self, 2) self.log.info( "compaction was completed, but fragmentation value {0} is more than before compaction {1}". format(fragmentation, self.precompacted_fragmentation)) # probably we already compacted, but no work needed to be done self.set_result(self.with_rebalance) else: self.set_result(True) self.state = FINISHED else: # Sometimes the compacting is not started immediately for i in range(17): time.sleep(3) if self._is_compacting(): task_manager.schedule(self, 2) return else: new_compaction_revision, fragmentation = self._get_compaction_details() self.log.info("{2}: stats compaction: ({0},{1})". format(new_compaction_revision, fragmentation, self.design_doc_name)) # case of rebalance when with concurrent updates it's possible that # compaction value has not changed significantly if new_compaction_revision > self.compaction_revision and self.with_rebalance: self.log.warning("the compaction revision was increased,\ but the actual fragmentation value has not changed significantly") self.set_result(True) self.state = FINISHED return else: continue # print details in case of failure self.log.info("design doc {0} is compacting:{1}".format(self.design_doc_name, self._is_compacting())) new_compaction_revision, fragmentation = self._get_compaction_details() self.log.error("stats compaction still: ({0},{1})". format(new_compaction_revision, fragmentation)) status, content = self.rest.set_view_info(self.bucket, self.design_doc_name) stats = content["stats"] self.log.warning("general compaction stats:{0}".format(stats)) self.set_exception(Exception("Check system logs, looks like compaction failed to start")) except (SetViewInfoNotFound) as ex: self.state = FINISHED self.set_exception(ex) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def _get_compaction_details(self): status, content = self.rest.set_view_info(self.bucket, self.design_doc_name) curr_no_of_compactions = content["stats"]["compactions"] curr_ddoc_fragemtation = \ MonitorViewFragmentationTask.calc_ddoc_fragmentation(self.rest, self.design_doc_name, self.bucket, self.with_rebalance) return (curr_no_of_compactions, curr_ddoc_fragemtation) def _is_compacting(self): status, content = self.rest.set_view_info(self.bucket, self.design_doc_name) return content["compact_running"] == True '''task class for failover. This task will only failover nodes but doesn't rebalance as there is already a task to do that''' class FailoverTask(Task): def __init__(self, servers, to_failover=[], wait_for_pending=0, graceful=False, use_hostnames=False): Task.__init__(self, "failover_task") self.servers = servers self.to_failover = to_failover self.graceful = graceful self.wait_for_pending = wait_for_pending self.use_hostnames = use_hostnames def execute(self, task_manager): try: self._failover_nodes(task_manager) self.log.info("{0} seconds sleep after failover, for nodes to go pending....".format(self.wait_for_pending)) time.sleep(self.wait_for_pending) self.state = FINISHED self.set_result(True) except FailoverFailedException as e: self.state = FINISHED self.set_exception(e) except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def _failover_nodes(self, task_manager): rest = RestConnection(self.servers[0]) # call REST fail_over for the nodes to be failed over for server in self.to_failover: for node in rest.node_statuses(): if (server.hostname if self.use_hostnames else server.ip) == node.ip and int(server.port) == int( node.port): self.log.info("Failing over {0}:{1} with graceful={2}".format(node.ip, node.port, self.graceful)) rest.fail_over(node.id, self.graceful) class GenerateExpectedViewResultsTask(Task): """ Task to produce the set of keys that are expected to be returned by querying the provided <view>. Results can be later passed to ViewQueryVerificationTask and compared with actual results from server. Currently only views with map functions that emit a single string or integer as keys are accepted. Also NOTE, this task is to be used with doc_generators that produce json like documentgenerator.DocumentGenerator """ def __init__(self, doc_generators, view, query): Task.__init__(self, "generate_view_query_results_task") self.doc_generators = doc_generators self.view = view self.query = query self.emitted_rows = [] self.is_reduced = self.view.red_func is not None and (('reduce' in query and query['reduce'] == "true") or \ (not 'reduce' in query)) self.custom_red_fn = self.is_reduced and not self.view.red_func in ['_count', '_sum', '_stats'] self.type_filter = None def execute(self, task_manager): try: self.generate_emitted_rows() self.filter_emitted_rows() self.log.info("Finished generating expected query results") self.state = CHECKING task_manager.schedule(self) except Exception as ex: self.state = FINISHED self.set_unexpected_exception(ex) traceback.print_exc() def check(self, task_manager): self.state = FINISHED self.set_result(self.emitted_rows) def generate_emitted_rows(self): emit_key = re.sub(r',.*', '', re.sub(r'.*emit\([ +]?doc\.', '', self.view.map_func)) emit_value = None if re.match(r'.*emit\([ +]?\[doc\.*', self.view.map_func): emit_key = re.sub(r'],.*', '', re.sub(r'.*emit\([ +]?\[doc\.', '', self.view.map_func)) emit_key = emit_key.split(", doc.") if re.match(r'.*new RegExp\("\^.*', self.view.map_func): filter_what = re.sub(r'.*new RegExp\(.*\)*doc\.', '', re.sub(r'\.match\(.*', '', self.view.map_func)) self.type_filter = {"filter_what": filter_what, "filter_expr": re.sub(r'[ +]?"\);.*', '', re.sub(r'.*.new RegExp\("\^', '', self.view.map_func))} if self.is_reduced and self.view.red_func != "_count": emit_value = re.sub(r'\);.*', '', re.sub(r'.*emit\([ +]?\[*],[ +]?doc\.', '', self.view.map_func)) if self.view.map_func.count("[") <= 1: emit_value = re.sub(r'\);.*', '', re.sub(r'.*emit\([ +]?.*,[ +]?doc\.', '', self.view.map_func)) for doc_gen in self.doc_generators: query_doc_gen = copy.deepcopy(doc_gen) while query_doc_gen.has_next(): _id, val = next(query_doc_gen) val = json.loads(val) if isinstance(emit_key, list): val_emit_key = [] for ek in emit_key: val_emit_key.append(val[ek]) else: val_emit_key = val[emit_key] if self.type_filter: filter_expr = r'\A{0}.*'.format(self.type_filter["filter_expr"]) if re.match(filter_expr, val[self.type_filter["filter_what"]]) is None: continue if isinstance(val_emit_key, str): val_emit_key = val_emit_key.encode('utf-8') if not self.is_reduced or self.view.red_func == "_count" or self.custom_red_fn: self.emitted_rows.append({'id': _id, 'key': val_emit_key}) else: val_emit_value = val[emit_value] self.emitted_rows.append({'value': val_emit_value, 'key': val_emit_key, 'id': _id, }) def filter_emitted_rows(self): query = self.query # parse query flags descending_set = 'descending' in query and query['descending'] == "true" startkey_set, endkey_set = 'startkey' in query, 'endkey' in query startkey_docid_set, endkey_docid_set = 'startkey_docid' in query, 'endkey_docid' in query inclusive_end_false = 'inclusive_end' in query and query['inclusive_end'] == "false" key_set = 'key' in query # sort expected results to match view results expected_rows = sorted(self.emitted_rows, key=cmp_to_key(lambda a, b: GenerateExpectedViewResultsTask.cmp_result_rows(a, b)), reverse=descending_set) # filter rows according to query flags if startkey_set: start_key = query['startkey'] if isinstance(start_key, str) and start_key.find('"') == 0: start_key = start_key[1:-1] if isinstance(start_key, str) and start_key.find('[') == 0: start_key = start_key[1:-1].split(',') start_key = [int(x) if x != 'null' else 0 for x in start_key] else: start_key = expected_rows[0]['key'] if isinstance(start_key, str) and start_key.find('"') == 0: start_key = start_key[1:-1] if endkey_set: end_key = query['endkey'] if isinstance(end_key, str) and end_key.find('"') == 0: end_key = end_key[1:-1] if isinstance(end_key, str) and end_key.find('[') == 0: end_key = end_key[1:-1].split(',') end_key = [int(x) if x != 'null' else None for x in end_key] else: end_key = expected_rows[-1]['key'] if isinstance(end_key, str) and end_key.find('"') == 0: end_key = end_key[1:-1] if descending_set: start_key, end_key = end_key, start_key if startkey_set or endkey_set: if isinstance(start_key, str): start_key = start_key.strip("\"") if isinstance(end_key, str): end_key = end_key.strip("\"") expected_rows = [row for row in expected_rows if row['key'] >= start_key and row['key'] <= end_key] if key_set: key_ = query['key'] if isinstance(key_, str) and key_.find('[') == 0: key_ = key_[1:-1].split(',') key_ = [int(x) if x != 'null' else None for x in key_] start_key, end_key = key_, key_ expected_rows = [row for row in expected_rows if row['key'] == key_] if descending_set: startkey_docid_set, endkey_docid_set = endkey_docid_set, startkey_docid_set if startkey_docid_set: if not startkey_set: self.log.warning("Ignoring startkey_docid filter when startkey is not set") else: do_filter = False if descending_set: if endkey_docid_set: startkey_docid = query['endkey_docid'] do_filter = True else: startkey_docid = query['startkey_docid'] do_filter = True if do_filter: expected_rows = \ [row for row in expected_rows if row['id'] >= startkey_docid or row['key'] > start_key] if endkey_docid_set: if not endkey_set: self.log.warning("Ignoring endkey_docid filter when endkey is not set") else: do_filter = False if descending_set: if endkey_docid_set: endkey_docid = query['startkey_docid'] do_filter = True else: endkey_docid = query['endkey_docid'] do_filter = True if do_filter: expected_rows = \ [row for row in expected_rows if row['id'] <= endkey_docid or row['key'] < end_key] if inclusive_end_false: if endkey_set and endkey_docid_set: # remove all keys that match endkey expected_rows = [row for row in expected_rows if row['id'] < query['endkey_docid'] or row['key'] < end_key] elif endkey_set: expected_rows = [row for row in expected_rows if row['key'] != end_key] if self.is_reduced: groups = {} gr_level = None if not 'group' in query and \ not 'group_level' in query: if len(expected_rows) == 0: expected_rows = [] self.emitted_rows = expected_rows return if self.view.red_func == '_count': groups[None] = len(expected_rows) elif self.view.red_func == '_sum': groups[None] = 0 groups[None] = math.fsum([row['value'] for row in expected_rows]) elif self.view.red_func == '_stats': groups[None] = {} values = [row['value'] for row in expected_rows] groups[None]['count'] = len(expected_rows) groups[None]['sum'] = math.fsum(values) groups[None]['max'] = max(values) groups[None]['min'] = min(values) groups[None]['sumsqr'] = math.fsum([x * x for x in values]) elif self.custom_red_fn: custom_action = re.sub(r'.*return[ +]', '', re.sub(r'.*return[ +]', '', self.view.red_func)) if custom_action.find('String') != -1: groups[None] = str(len(expected_rows)) elif custom_action.find('-') != -1: groups[None] = -len(expected_rows) elif 'group' in query and query['group'] == 'true': if not 'group_level' in query: gr_level = len(expected_rows) - 1 elif 'group_level' in query: gr_level = int(query['group_level']) if gr_level is not None: for row in expected_rows: key = str(row['key'][:gr_level]) if not key in groups: if self.view.red_func == '_count': groups[key] = 1 elif self.view.red_func == '_sum': groups[key] = row['value'] elif self.view.red_func == '_stats': groups[key] = {} groups[key]['count'] = 1 groups[key]['sum'] = row['value'] groups[key]['max'] = row['value'] groups[key]['min'] = row['value'] groups[key]['sumsqr'] = row['value'] ** 2 else: if self.view.red_func == '_count': groups[key] += 1 elif self.view.red_func == '_sum': groups[key] += row['value'] elif self.view.red_func == '_stats': groups[key]['count'] += 1 groups[key]['sum'] += row['value'] groups[key]['max'] = max(row['value'], groups[key]['max']) groups[key]['min'] = min(row['value'], groups[key]['min']) groups[key]['sumsqr'] += row['value'] ** 2 expected_rows = [] for group, value in groups.items(): if isinstance(group, str) and group.find("[") == 0: group = group[1:-1].split(",") group = [int(k) for k in group] expected_rows.append({"key": group, "value": value}) expected_rows = sorted(expected_rows, key=cmp_to_key(lambda a, b: GenerateExpectedViewResultsTask.cmp_result_rows(a, b)), reverse=descending_set) if 'skip' in query: expected_rows = expected_rows[(int(query['skip'])):] if 'limit' in query: expected_rows = expected_rows[:(int(query['limit']))] self.emitted_rows = expected_rows @staticmethod def cmp_result_rows(x, y): rc = len(DeepDiff(x['key'], y['key'], ignore_order=True)) if rc == 0: # sort by id is tie breaker rc = len(DeepDiff(x['id'], y['id'], ignore_order=True)) return rc class ViewQueryVerificationTask(Task): """ * query with stale=false * check for duplicates * check for missing docs * check memcached * check couch """ def __init__(self, design_doc_name, view_name, query, expected_rows, server=None, num_verified_docs=20, bucket="default", query_timeout=120, results=None, config=None): Task.__init__(self, "view_query_verification_task") self.server = server self.design_doc_name = design_doc_name self.view_name = view_name self.query = query self.expected_rows = expected_rows self.num_verified_docs = num_verified_docs self.bucket = bucket self.query_timeout = query_timeout self.results = results try: for key in config: self.config[key] = config[key] except: pass def execute(self, task_manager): if not self.results: rest = RestConnection(self.server) try: # query for full view results self.query["stale"] = "false" self.query["reduce"] = "false" self.query["include_docs"] = "true" self.results = rest.query_view(self.design_doc_name, self.view_name, self.bucket, self.query, timeout=self.query_timeout) except QueryViewException as e: self.set_exception(e) self.state = FINISHED msg = "Checking view query results: (%d keys expected) vs (%d keys returned)" % \ (len(self.expected_rows), len(self.results['rows'])) self.log.info(msg) self.state = CHECKING task_manager.schedule(self) def check(self, task_manager): err_infos = [] rc_status = {"passed": False, "errors": err_infos} # array of dicts with keys 'msg' and 'details' try: # create verification id lists expected_ids = [row['id'] for row in self.expected_rows] couch_ids = [str(row['id']) for row in self.results['rows']] # check results self.check_for_duplicate_ids(expected_ids, couch_ids, err_infos) self.check_for_missing_ids(expected_ids, couch_ids, err_infos) self.check_for_extra_ids(expected_ids, couch_ids, err_infos) self.check_for_value_corruption(err_infos) # check for errors if len(rc_status["errors"]) == 0: rc_status["passed"] = True self.state = FINISHED self.set_result(rc_status) except Exception as ex: self.state = FINISHED try: max_example_result = max(100, len(self.results['rows'] - 1)) self.log.info("FIRST %s RESULTS for view %s : %s" % (max_example_result, self.view_name, self.results['rows'][max_example_result])) except Exception as inner_ex: self.log.error(inner_ex) self.set_result({"passed": False, "errors": "ERROR: %s" % ex}) def check_for_duplicate_ids(self, expected_ids, couch_ids, err_infos): extra_id_set = set(couch_ids) - set(expected_ids) seen = set() for id in couch_ids: if id in seen and id not in extra_id_set: extra_id_set.add(id) else: seen.add(id) if len(extra_id_set) > 0: # extra/duplicate id verification dupe_rows = [row for row in self.results['rows'] if row['id'] in extra_id_set] err = {"msg": "duplicate rows found in query results", "details": dupe_rows} err_infos.append(err) def check_for_missing_ids(self, expected_ids, couch_ids, err_infos): missing_id_set = set(expected_ids) - set(couch_ids) if len(missing_id_set) > 0: missing_id_errors = self.debug_missing_items(missing_id_set) if len(missing_id_errors) > 0: err = {"msg": "missing ids from memcached", "details": missing_id_errors} err_infos.append(err) def check_for_extra_ids(self, expected_ids, couch_ids, err_infos): extra_id_set = set(couch_ids) - set(expected_ids) if len(extra_id_set) > 0: err = {"msg": "extra ids from memcached", "details": extra_id_set} err_infos.append(err) def check_for_value_corruption(self, err_infos): if self.num_verified_docs > 0: doc_integrity_errors = self.include_doc_integrity() if len(doc_integrity_errors) > 0: err = {"msg": "missmatch in document values", "details": doc_integrity_errors} err_infos.append(err) def debug_missing_items(self, missing_id_set): rest = RestConnection(self.server) client = KVStoreAwareSmartClient(rest, self.bucket) missing_id_errors = [] # debug missing documents for doc_id in list(missing_id_set)[:self.num_verified_docs]: # attempt to retrieve doc from memcached mc_item = client.mc_get_full(doc_id) if mc_item == None: missing_id_errors.append("document %s missing from memcached" % (doc_id)) # attempt to retrieve doc from disk else: num_vbuckets = len(rest.get_vbuckets(self.bucket)) doc_meta = client.get_doc_metadata(num_vbuckets, doc_id) if (doc_meta != None): if (doc_meta['key_valid'] != 'valid'): msg = "Error expected in results for key with invalid state %s" % doc_meta missing_id_errors.append(msg) else: msg = "query doc_id: %s doesn't exist in bucket: %s" % \ (doc_id, self.bucket) missing_id_errors.append(msg) if (len(missing_id_errors) == 0): msg = "view engine failed to index doc [%s] in query: %s" % (doc_id, self.query) missing_id_errors.append(msg) return missing_id_errors def include_doc_integrity(self): rest = RestConnection(self.server) client = KVStoreAwareSmartClient(rest, self.bucket) doc_integrity_errors = [] if 'doc' not in self.results['rows'][0]: return doc_integrity_errors exp_verify_set = [row['doc'] for row in \ self.results['rows'][:self.num_verified_docs]] for view_doc in exp_verify_set: doc_id = str(view_doc['_id']) mc_item = client.mc_get_full(doc_id) if mc_item is not None: mc_doc = json.loads(mc_item["value"]) # compare doc content for key in list(mc_doc.keys()): if (mc_doc[key] != view_doc[key]): err_msg = \ "error verifying document id %s: retrieved value %s expected %s \n" % \ (doc_id, mc_doc[key], view_doc[key]) doc_integrity_errors.append(err_msg) else: doc_integrity_errors.append("doc_id %s could not be retrieved for verification \n" % doc_id) return doc_integrity_errors class BucketFlushTask(Task): def __init__(self, server, bucket="default"): Task.__init__(self, "bucket_flush_task") self.server = server self.bucket = bucket if isinstance(bucket, Bucket): self.bucket = bucket.name def execute(self, task_manager): try: rest = RestConnection(self.server) if rest.flush_bucket(self.bucket): self.state = CHECKING task_manager.schedule(self) else: self.state = FINISHED self.set_result(False) except BucketFlushFailed as e: self.state = FINISHED self.set_exception(e) except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): try: # check if after flush the vbuckets are ready if BucketOperationHelper.wait_for_vbuckets_ready_state(self.server, self.bucket): self.set_result(True) else: self.log.error("Unable to reach bucket {0} on server {1} after flush".format(self.bucket, self.server)) self.set_result(False) self.state = FINISHED except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) class MonitorDBFragmentationTask(Task): """ Attempt to monitor fragmentation that is occurring for a given bucket. Note: If autocompaction is enabled and user attempts to monitor for fragmentation value higher than level at which auto_compaction kicks in a warning is sent and it is best user to use lower value as this can lead to infinite monitoring. """ def __init__(self, server, fragmentation_value=10, bucket="default", get_view_frag=False): Task.__init__(self, "monitor_frag_db_task") self.server = server self.bucket = bucket self.fragmentation_value = fragmentation_value self.get_view_frag = get_view_frag def execute(self, task_manager): # sanity check of fragmentation value if self.fragmentation_value < 0 or self.fragmentation_value > 100: err_msg = \ "Invalid value for fragmentation %d" % self.fragmentation_value self.state = FINISHED self.set_exception(Exception(err_msg)) self.state = CHECKING task_manager.schedule(self, 5) def check(self, task_manager): try: rest = RestConnection(self.server) stats = rest.fetch_bucket_stats(bucket=self.bucket) if self.get_view_frag: new_frag_value = stats["op"]["samples"]["couch_views_fragmentation"][-1] self.log.info("Current amount of views fragmentation = %d" % new_frag_value) else: new_frag_value = stats["op"]["samples"]["couch_docs_fragmentation"][-1] self.log.info("current amount of docs fragmentation = %d" % new_frag_value) if new_frag_value >= self.fragmentation_value: self.state = FINISHED self.set_result(True) else: # try again task_manager.schedule(self, 2) except Exception as ex: self.state = FINISHED self.set_result(False) self.set_exception(ex) class CBRecoveryTask(Task): def __init__(self, src_server, dest_server, bucket_src='', bucket_dest='', username='', password='', username_dest='', password_dest='', verbose=False, wait_completed=True): Task.__init__(self, "cbrecovery_task") self.src_server = src_server self.dest_server = dest_server self.bucket_src = bucket_src self.bucket_dest = bucket_dest if isinstance(bucket_src, Bucket): self.bucket_src = bucket_src.name if isinstance(bucket_dest, Bucket): self.bucket_dest = bucket_dest.name self.username = username self.password = password self.username_dest = username_dest self.password_dest = password_dest self.verbose = verbose self.wait_completed = wait_completed try: self.shell = RemoteMachineShellConnection(src_server) self.info = self.shell.extract_remote_info() self.rest = RestConnection(dest_server) except Exception as e: self.log.error(e) self.state = FINISHED self.set_exception(e) self.progress = {} self.started = False self.retries = 0 def execute(self, task_manager): try: if self.info.type.lower() == "linux": command = "/opt/couchbase/bin/cbrecovery " elif self.info.type.lower() == "windows": command = "C:/Program\ Files/Couchbase/Server/bin/cbrecovery.exe " src_url = "http://{0}:{1}".format(self.src_server.ip, self.src_server.port) dest_url = "http://{0}:{1}".format(self.dest_server.ip, self.dest_server.port) command += "{0} {1} ".format(src_url, dest_url) if self.bucket_src: command += "-b {0} ".format(self.bucket_src) if self.bucket_dest: command += "-B {0} ".format(self.bucket_dest) if self.username: command += "-u {0} ".format(self.username) if self.password: command += "-p {0} ".format(self.password) if self.username_dest: command += "-U {0} ".format(self.username_dest) if self.password_dest: command += "-P {0} ".format(self.password_dest) if self.verbose: command += " -v " transport = self.shell._ssh_client.get_transport() transport.set_keepalive(1) self.chan = transport.open_session() self.chan.settimeout(10 * 60.0) self.chan.exec_command(command) self.log.info("command was executed: '{0}'".format(command)) self.state = CHECKING task_manager.schedule(self, 20) except Exception as e: self.state = FINISHED self.set_exception(e) # it was done to keep connection alive def checkChannel(self): try: if self.chan.exit_status_ready(): if self.chan.recv_ready(): output = self.chan.recv(1048576) if self.chan.recv_stderr_ready(): error = self.chan.recv_stderr(1048576) except socket.timeout: print("SSH channel timeout exceeded.") except Exception: traceback.print_exc() def check(self, task_manager): self.checkChannel() self.recovery_task = self.rest.get_recovery_task() if self.recovery_task is not None: if not self.started: self.started = True if not self.wait_completed: progress = self.rest.get_recovery_progress(self.recovery_task["recoveryStatusURI"]) self.log.info("cbrecovery strarted with progress: {0}".format(progress)) self.log.info("will not wait for the end of the cbrecovery") self.state = FINISHED self.set_result(True) progress = self.rest.get_recovery_progress(self.recovery_task["recoveryStatusURI"]) if progress == self.progress: self.log.warning("cbrecovery progress was not changed") if self.retries > 20: self.shell.disconnect() self.rest.print_UI_logs() self.state = FINISHED self.log.warning("ns_server_tasks: {0}".format(self.rest.ns_server_tasks())) self.log.warning("cbrecovery progress: {0}".format( self.rest.get_recovery_progress(self.recovery_task["recoveryStatusURI"]))) self.set_exception(CBRecoveryFailedException("cbrecovery hangs")) return self.retries += 1 task_manager.schedule(self, 20) else: self.progress = progress self.log.info("cbrecovery progress: {0}".format(self.progress)) self.retries = 0 task_manager.schedule(self, 20) else: if self.started: self.shell.disconnect() self.log.info("cbrecovery completed succesfully") self.state = FINISHED self.set_result(True) if self.retries > 5: self.shell.disconnect() self.rest.print_UI_logs() self.state = FINISHED self.log.warning("ns_server_tasks: {0}".format(self.rest.ns_server_tasks())) self.set_exception(CBRecoveryFailedException("cbrecovery was not started")) return else: self.retries += 1 task_manager.schedule(self, 20) class CompactBucketTask(Task): def __init__(self, server, bucket="default"): Task.__init__(self, "bucket_compaction_task") self.server = server self.bucket = bucket self.rest = RestConnection(server) self.retries = 20 self.statuses = {} # get the current count of compactions nodes = self.rest.get_nodes() self.compaction_count = {} for node in nodes: self.compaction_count[node.ip] = 0 def execute(self, task_manager): try: status = self.rest.compact_bucket(self.bucket) self.state = CHECKING except BucketCompactionException as e: self.log.error("Bucket compaction failed for unknown reason") self.set_exception(e) self.state = FINISHED self.set_result(False) task_manager.schedule(self) def check(self, task_manager): # check bucket compaction status across all nodes nodes = self.rest.get_nodes() current_compaction_count = {} for node in nodes: current_compaction_count[node.ip] = 0 s = TestInputServer() s.ip = node.ip s.ssh_username = self.server.ssh_username s.ssh_password = self.server.ssh_password shell = RemoteMachineShellConnection(s) res = shell.execute_cbstats("", "raw", keyname="kvtimings", vbid="") for i in res[0]: # check for lines that look like # rw_0:compact_131072,262144: 8 if 'compact' in i: current_compaction_count[node.ip] += int(i.split(':')[2]) if len(DeepDiff(current_compaction_count, self.compaction_count)) == 1: # compaction count has increased self.set_result(True) self.state = FINISHED else: if self.retries > 0: # retry self.retries = self.retries - 1 task_manager.schedule(self, 10) else: # never detected a compaction task running self.set_result(False) self.state = FINISHED def _get_disk_size(self): stats = self.rest.fetch_bucket_stats(bucket=self.bucket) total_disk_size = stats["op"]["samples"]["couch_total_disk_size"][-1] self.log.info("Disk size is = %d" % total_disk_size) return total_disk_size class MonitorViewCompactionTask(ViewCompactionTask): def __init__(self, server, design_doc_name, bucket="default", with_rebalance=False, frag_value=0): ViewCompactionTask.__init__(self, server, design_doc_name, bucket, with_rebalance) self.ddoc_id = "_design%2f" + design_doc_name self.compaction_revision = 0 self.precompacted_fragmentation = 0 self.fragmentation_value = frag_value self.rest = RestConnection(self.server) def execute(self, task_manager): try: self.compaction_revision, self.precompacted_fragmentation = self._get_compaction_details() self.log.info("{0}: stats compaction before triggering it: ({1},{2})". format(self.design_doc_name, self.compaction_revision, self.precompacted_fragmentation)) self.disk_size = self._get_disk_size() self.log.info("Disk Size Before Compaction {0}".format(self.disk_size)) if self.precompacted_fragmentation == 0: self.log.warning("%s: There is nothing to compact, fragmentation is 0" % self.design_doc_name) self.set_result(False) self.state = FINISHED elif self.precompacted_fragmentation < self.fragmentation_value: self.log.info( "{0}: Compaction is already done and there is nothing to compact, current fragmentation is lesser {1} {2}". format(self.design_doc_name, self.precompacted_fragmentation, self.fragmentation_value)) self.compaction_revision, self.precompacted_fragmentation = self._get_compaction_details() self.log.info("{0}: stats compaction before triggering it: ({1},{2})". format(self.design_doc_name, self.compaction_revision, self.precompacted_fragmentation)) self.set_result(True) self.state = FINISHED return self.state = CHECKING task_manager.schedule(self, 2) except (CompactViewFailed, SetViewInfoNotFound) as ex: self.state = FINISHED self.set_exception(ex) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) # verify compaction history incremented and some defraging occurred def check(self, task_manager): try: _compaction_running = self._is_compacting() new_compaction_revision, fragmentation = self._get_compaction_details() self.log.info("{0}: stats compaction:revision and fragmentation: ({1},{2})". format(self.design_doc_name, new_compaction_revision, fragmentation)) curr_disk_size = self._get_disk_size() self.log.info("Current Disk Size {0}".format(curr_disk_size)) if new_compaction_revision == self.compaction_revision and _compaction_running: # compaction ran successfully but compaction was not changed, perhaps we are still compacting self.log.info("design doc {0} is compacting".format(self.design_doc_name)) task_manager.schedule(self, 3) elif self.precompacted_fragmentation > fragmentation: self.log.info("%s: Pre Compacted fragmentation is more, before Compaction %d and after Compaction %d" % \ (self.design_doc_name, self.precompacted_fragmentation, fragmentation)) frag_val_diff = fragmentation - self.precompacted_fragmentation if new_compaction_revision == self.compaction_revision or new_compaction_revision > self.compaction_revision: self.log.info("{1}: compactor was run, compaction revision was changed on {0}". format(new_compaction_revision, self.design_doc_name)) self.log.info("%s: fragmentation went from %d to %d" % ( self.design_doc_name, self.precompacted_fragmentation, fragmentation)) if frag_val_diff > 0: if self._is_compacting(): task_manager.schedule(self, 5) self.log.info( "compaction was completed, but fragmentation value {0} is more than before compaction {1}". format(fragmentation, self.precompacted_fragmentation)) self.log.info("Load is still in progress, Need to be checked") self.set_result(self.with_rebalance) else: self.set_result(True) self.state = FINISHED else: for i in range(10): time.sleep(3) if self._is_compacting(): task_manager.schedule(self, 2) return else: new_compaction_revision, fragmentation = self._get_compaction_details() self.log.info("{2}: stats compaction: ({0},{1})".format(new_compaction_revision, fragmentation, self.design_doc_name)) curr_disk_size = self._get_disk_size() self.log.info("Disk Size went from {0} {1}".format(self.disk_size, curr_disk_size)) if new_compaction_revision > self.compaction_revision and self.precompacted_fragmentation > fragmentation: self.log.warning( "the compaction revision was increase and fragmentation value went from {0} {1}". format(self.precompacted_fragmentation, fragmentation)) self.set_result(True) self.state = FINISHED return elif new_compaction_revision > self.compaction_revision and self.with_rebalance: self.log.warning( "the compaction revision was increased, but the actual fragmentation value has not changed significantly") self.set_result(True) self.state = FINISHED return else: continue self.log.info("design doc {0} is compacting:{1}".format(self.design_doc_name, self._is_compacting())) new_compaction_revision, fragmentation = self._get_compaction_details() self.log.error("stats compaction still: ({0},{1})". format(new_compaction_revision, fragmentation)) status, content = self.rest.set_view_info(self.bucket, self.design_doc_name) stats = content["stats"] self.log.warning("general compaction stats:{0}".format(stats)) self.state = FINISHED self.set_result(False) self.set_exception(Exception("Check system logs, looks like compaction failed to start")) except (SetViewInfoNotFound) as ex: self.state = FINISHED self.set_exception(ex) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def _get_disk_size(self): nodes_ddoc_info = MonitorViewFragmentationTask.aggregate_ddoc_info(self.rest, self.design_doc_name, self.bucket, self.with_rebalance) disk_size = sum([content['disk_size'] for content in nodes_ddoc_info]) return disk_size class MonitorDiskSizeFragmentationTask(Task): def __init__(self, server, fragmentation_value=10, bucket="default", get_view_frag=False): Task.__init__(self, "monitor_frag_db_task") self.server = server self.bucket = bucket self.fragmentation_value = fragmentation_value self.get_view_frag = get_view_frag self.rest = RestConnection(self.server) self.curr_disk_size = 0 def execute(self, task_manager): if self.fragmentation_value < 0: err_msg = \ "Invalid value for fragmentation %d" % self.fragmentation_value self.state = FINISHED self.set_exception(Exception(err_msg)) self.state = CHECKING task_manager.schedule(self, 5) def check(self, task_manager): try: rest = RestConnection(self.server) stats = rest.fetch_bucket_stats(bucket=self.bucket) if self.get_view_frag: new_disk_size = stats["op"]["samples"]["couch_views_actual_disk_size"][-1] else: new_disk_size = stats["op"]["samples"]["couch_total_disk_size"][-1] if self.curr_disk_size > new_disk_size: self.state = FINISHED self.set_result(True) else: # try again task_manager.schedule(self, 5) self.log.info("New and Current Disk size is {0} {1}".format(new_disk_size, self.curr_disk_size)) self.curr_disk_size = new_disk_size except Exception as ex: self.state = FINISHED self.set_result(False) self.set_exception(ex) class CancelBucketCompactionTask(Task): def __init__(self, server, bucket="default"): Task.__init__(self, "cancel_bucket_compaction_task") self.server = server self.bucket = bucket self.retries = 20 self.statuses = {} try: self.rest = RestConnection(server) except ServerUnavailableException as e: self.log.error(e) self.state = FINISHED self.set_exception(e) def execute(self, task_manager): try: status = self.rest.cancel_bucket_compaction(self.bucket) self.state = CHECKING except BucketCompactionException as e: self.log.error("Cancel Bucket compaction failed for unknown reason") self.set_exception(e) self.state = FINISHED self.set_result(False) task_manager.schedule(self) def check(self, task_manager): # check cancel bucket compaction status across all nodes nodes = self.rest.get_nodes() for node in nodes: last_status = self.statuses.get(node.id) try: rest = RestConnection(node) except ServerUnavailableException as e: self.log.error(e) self.state = FINISHED self.set_exception(e) running, progress = rest.check_compaction_status(self.bucket) if progress is None and last_status is False: # finished if previously detected running but not == 100% self.statuses[node.id] = True if running: self.log.info("Progress is {0}".format(progress)) self.statuses[node.id] = (progress == 100) done = all(self.statuses.values()) if done: self.log.info("Bucket Compaction Cancelled successfully") # task was completed sucessfully self.set_result(True) self.state = FINISHED else: if self.retries > 0: self.retries = self.retries - 1 task_manager.schedule(self, 10) else: # never detected a compaction task running self.log.error("Bucket Compaction Cancellation not started") self.set_result(False) self.state = FINISHED class EnterpriseBackupTask(Task): def __init__(self, backupset, objstore_provider, resume=False, purge=False, no_progress_bar=False, cli_command_location='', cb_version=None, num_shards=''): Task.__init__(self, "enterprise_backup_task") self.backupset = backupset self.objstore_provider = objstore_provider self.resume = resume self.purge = purge self.no_progress_bar = no_progress_bar self.cli_command_location = cli_command_location self.cb_version = cb_version self.cluster_flag = "--host" self.num_shards = num_shards """ from couchbase version 4.6.x, --host flag is not supported """ if self.cb_version is None: raise Exception("Need to pass Couchbase version to run correctly bk/rt ") elif self.cb_version[:5] in COUCHBASE_FROM_4DOT6: self.cluster_flag = "--cluster" self.output = [] self.error = [] try: self.remote_client = RemoteMachineShellConnection(self.backupset.backup_host) except Exception as e: self.log.error(e) self.state = FINISHED self.set_exception(e) def execute(self, task_manager): try: args = ( f"backup --archive {self.objstore_provider.schema_prefix() + self.backupset.objstore_bucket + '/' if self.objstore_provider else ''}{self.backupset.directory}" f" --repo {self.backupset.name}" f" {self.cluster_flag} http://{self.backupset.cluster_host.ip}:{self.backupset.cluster_host.port}" f" --username {self.backupset.cluster_host.rest_username}" f" --password {self.backupset.cluster_host.rest_password}" f" {self.num_shards}" f"{' --obj-staging-dir ' + self.backupset.objstore_staging_directory if self.objstore_provider else ''}" f"{' --obj-endpoint ' + self.backupset.objstore_endpoint if self.objstore_provider and self.backupset.objstore_endpoint else ''}" f"{' --obj-region ' + self.backupset.objstore_region if self.objstore_provider and self.backupset.objstore_region else ''}" f"{' --obj-access-key-id ' + self.backupset.objstore_access_key_id if self.objstore_provider and self.backupset.objstore_access_key_id else ''}" f"{' --obj-secret-access-key ' + self.backupset.objstore_secret_access_key if self.objstore_provider and self.backupset.objstore_secret_access_key else ''}" f"{' --s3-force-path-style' if self.objstore_provider and self.objstore_provider.schema_prefix() == 's3://' else ''}" ) if self.resume: args += " --resume" if self.purge: args += " --purge" if self.no_progress_bar: args += " --no-progress-bar" command = "{0}/cbbackupmgr {1}".format(self.cli_command_location, args) self.output, self.error = self.remote_client.execute_command(command) self.state = CHECKING except Exception as e: self.log.error("Backup cluster failed for unknown reason") self.set_exception(e) self.state = FINISHED self.set_result(False) task_manager.schedule(self) def check(self, task_manager): if self.output: self.state = FINISHED self.set_result(self.output) self.remote_client.log_command_output(self.output, self.error) elif self.error: self.state = FINISHED self.set_result(self.error) self.remote_client.log_command_output(self.output, self.error) else: task_manager.schedule(self, 10) class EnterpriseRestoreTask(Task): def __init__(self, backupset, objstore_provider, no_progress_bar=False, cli_command_location='', cb_version=None, start="start", end="end", backups=[], force_updates=False, no_resume=False): Task.__init__(self, "enterprise_backup_task") self.backupset = backupset self.objstore_provider = objstore_provider self.no_progress_bar = no_progress_bar self.cli_command_location = cli_command_location self.cb_version = cb_version self.cluster_flag = "--host" """ from couchbase version 4.6.x, --host flag is not supported """ if self.cb_version is None: raise Exception("Need to pass Couchbase version to run correctly bk/rt ") elif self.cb_version[:5] in COUCHBASE_FROM_4DOT6: self.cluster_flag = "--cluster" self.output = [] self.error = [] self.backups = backups self.start = start self.end = end self.force_updates = force_updates self.no_resume = no_resume try: self.remote_client = RemoteMachineShellConnection(self.backupset.backup_host) except Exception as e: self.log.error(e) self.state = FINISHED self.set_exception(e) def execute(self, task_manager): try: if isinstance(self.start, int) and isinstance(self.end, int): try: backup_start = self.backups[int(self.start) - 1] except IndexError: backup_start = "{0}{1}".format(self.backups[-1], self.start) try: backup_end = self.backups[int(self.end) - 1] except IndexError: backup_end = "{0}{1}".format(self.backups[-1], self.end) else: backup_start = self.start backup_end = self.end args = ( f"restore --archive {self.objstore_provider.schema_prefix() + self.backupset.objstore_bucket + '/' if self.objstore_provider else ''}{self.backupset.directory}" f" --repo {self.backupset.name}" f" {self.cluster_flag} http://{self.backupset.restore_cluster_host.ip}:{self.backupset.restore_cluster_host.port}" f" --username {self.backupset.restore_cluster_host.rest_username} " f" --password {self.backupset.restore_cluster_host.rest_password}" f" --start {backup_start}" f" --end {backup_end}" f"{' --obj-staging-dir ' + self.backupset.objstore_staging_directory if self.objstore_provider else ''}" f"{' --obj-endpoint ' + self.backupset.objstore_endpoint if self.objstore_provider and self.backupset.objstore_endpoint else ''}" f"{' --obj-region ' + self.backupset.objstore_region if self.objstore_provider and self.backupset.objstore_region else ''}" f"{' --obj-access-key-id ' + self.backupset.objstore_access_key_id if self.objstore_provider and self.backupset.objstore_access_key_id else ''}" f"{' --obj-secret-access-key ' + self.backupset.objstore_secret_access_key if self.objstore_provider and self.backupset.objstore_secret_access_key else ''}" f"{' --s3-force-path-style' if self.objstore_provider and self.objstore_provider.schema_prefix() == 's3://' else ''}" f"{' --resume' if self.backupset.resume and not self.no_resume else ''}" ) if self.no_progress_bar: args += " --no-progress-bar" if self.force_updates: args += " --force-updates" command = "{0}/cbbackupmgr {1}".format(self.cli_command_location, args) self.output, self.error = self.remote_client.execute_command(command) self.state = CHECKING except Exception as e: self.log.error("Restore failed for unknown reason") self.set_exception(e) self.state = FINISHED self.set_result(False) task_manager.schedule(self) def check(self, task_manager): if self.output: self.state = FINISHED self.set_result(self.output) self.remote_client.log_command_output(self.output, self.error) elif self.error: self.state = FINISHED self.set_result(self.error) self.remote_client.log_command_output(self.output, self.error) else: task_manager.schedule(self, 10) class EnterpriseMergeTask(Task): def __init__(self, backup_host, backups=[], start=0, end=0, directory='', name='', cli_command_location=''): Task.__init__(self, "enterprise_backup_task") self.backup_host = backup_host self.directory = directory self.name = name self.cli_command_location = cli_command_location self.output = [] self.error = [] self.backups = backups self.start = start self.end = end try: self.remote_client = RemoteMachineShellConnection(self.backup_host) except Exception as e: self.log.error(e) self.state = FINISHED self.set_exception(e) def execute(self, task_manager): try: try: backup_start = self.backups[int(self.start) - 1] except IndexError: backup_start = "{0}{1}".format(self.backups[-1], self.start) try: backup_end = self.backups[int(self.end) - 1] except IndexError: backup_end = "{0}{1}".format(self.backups[-1], self.end) args = "merge --archive {0} --repo {1} --start {2} --end {3}".format(self.directory, self.name, backup_start, backup_end) command = "{0}/cbbackupmgr {1}".format(self.cli_command_location, args) self.output, self.error = self.remote_client.execute_command(command) self.state = CHECKING except Exception as e: self.log.error("Merge failed for unknown reason") self.set_exception(e) self.state = FINISHED self.set_result(False) task_manager.schedule(self) def check(self, task_manager): if self.output: self.state = FINISHED self.set_result(self.output) self.remote_client.log_command_output(self.output, self.error) elif self.error: self.state = FINISHED self.set_result(self.error) self.remote_client.log_command_output(self.output, self.error) else: task_manager.schedule(self, 10) class EnterpriseCompactTask(Task): def __init__(self, backup_host, backup_to_compact, backups=[], directory='', name='', cli_command_location=''): Task.__init__(self, "enterprise_backup_task") self.backup_host = backup_host self.backup_to_compact = backup_to_compact self.directory = directory self.name = name self.cli_command_location = cli_command_location self.output = [] self.error = [] self.backups = backups try: self.remote_client = RemoteMachineShellConnection(self.backup_host) except Exception as e: self.log.error(e) self.state = FINISHED self.set_exception(e) def execute(self, task_manager): try: args = "compact --archive {0} --repo {1} --backup {2}".format(self.directory, self.name, self.backups[self.backup_to_compact]) command = "{0}/cbbackupmgr {1}".format(self.cli_command_location, args) self.output, self.error = self.remote_client.execute_command(command) self.state = CHECKING except Exception as e: self.log.error("Compact failed for unknown reason") self.set_exception(e) self.state = FINISHED self.set_result(False) task_manager.schedule(self) def check(self, task_manager): if self.output: self.state = FINISHED self.set_result(self.output) self.remote_client.log_command_output(self.output, self.error) elif self.error: self.state = FINISHED self.set_result(self.error) self.remote_client.log_command_output(self.output, self.error) else: task_manager.schedule(self, 10) class CBASQueryExecuteTask(Task): def __init__(self, server, cbas_endpoint, statement, mode=None, pretty=True): Task.__init__(self, "cbas_query_execute_task") self.server = server self.cbas_endpoint = cbas_endpoint self.statement = statement self.mode = mode self.pretty = pretty self.response = {} self.passed = True def execute(self, task_manager): try: rest = RestConnection(self.server) self.response = json.loads(rest.execute_statement_on_cbas(self.statement, self.mode, self.pretty, 70)) if self.response: self.state = CHECKING task_manager.schedule(self) else: self.log.info("Some error") self.state = FINISHED self.passed = False self.set_result(False) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.passed = False self.set_unexpected_exception(e) def check(self, task_manager): try: if "errors" in self.response: errors = self.response["errors"] else: errors = None if "results" in self.response: results = self.response["results"] else: results = None if "handle" in self.response: handle = self.response["handle"] else: handle = None if self.mode != "async": if self.response["status"] == "success": self.set_result(True) self.passed = True else: self.log.info(errors) self.passed = False self.set_result(False) else: if self.response["status"] == "started": self.set_result(True) self.passed = True else: self.log.info(errors) self.passed = False self.set_result(False) self.state = FINISHED # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) class NodesFailureTask(Task): def __init__(self, master, servers_to_fail, failure_type, timeout, pause=0, timeout_buffer=3, disk_timeout=0, disk_location=None, disk_size=5000, failure_timeout=60): Task.__init__(self, "NodesFailureTask") self.master = master self.servers_to_fail = servers_to_fail self.num_servers_to_fail = self.servers_to_fail.__len__() self.itr = 0 self.failure_type = failure_type self.timeout = timeout self.failure_timeout = failure_timeout self.pause = pause self.start_time = 0 self.timeout_buffer = timeout_buffer self.current_failure_node = self.servers_to_fail[0] self.max_time_to_wait_for_failover = self.timeout + \ self.timeout_buffer + 60 self.disk_timeout = disk_timeout self.disk_location = disk_location self.disk_size = disk_size self.taskmanager = None self.rebalance_in_progress = False def execute(self, task_manager): self.taskmanager = task_manager rest = RestConnection(self.master) if rest._rebalance_progress_status() == "running": self.rebalance_in_progress = True while self.has_next() and not self.done(): next(self) if self.pause > 0 and self.pause > self.timeout: self.check(task_manager) if self.pause == 0 or 0 < self.pause < self.timeout: self.check(task_manager) self.state = FINISHED self.set_result(True) def check(self, task_manager): rest = RestConnection(self.master) max_timeout = self.timeout + self.timeout_buffer + self.disk_timeout if self.start_time == 0: message = "Did not inject failure in the system." rest.print_UI_logs(10) self.log.error(message) self.state = FINISHED self.set_result(False) self.set_exception(NodesFailureException(message)) def has_next(self): return self.itr < self.num_servers_to_fail def __next__(self): if self.pause != 0: time.sleep(self.pause) if self.pause > self.timeout and self.itr != 0: rest = RestConnection(self.master) status = rest.reset_autofailover() self._rebalance() if not status: self.state = FINISHED self.set_result(False) self.set_exception(Exception("Reset of autofailover " "count failed")) self.current_failure_node = self.servers_to_fail[self.itr] self.start_time = time.time() self.log.info("before failure time: {}".format(time.ctime(time.time()))) if self.failure_type == "limit_file_limits_desc": self._enable_disable_limit_file_limits_desc(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_limit_file_limits_desc": self.enable_file_limit_desc(self.current_failure_node) elif self.failure_type == "disable_limit_file_limits_desc": self.disable_file_limit_desc(self.current_failure_node) elif self.failure_type == "limit_file_limits": self._enable_disable_limit_file_limits(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_limit_file_limits": self.enable_file_limit(self.current_failure_node) elif self.failure_type == "disable_limit_file_limits": self.disable_file_limit(self.current_failure_node) elif self.failure_type == "extra_files_in_log_dir": self._extra_files_in_log_dir(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_extra_files_in_log_dir": self.add_extra_files_in_log_dir(self.current_failure_node) elif self.failure_type == "disable_extra_files_in_log_dir": self.remove_extra_files_in_log_dir(self.current_failure_node) elif self.failure_type == "empty_files_in_log_dir": self._empty_file_in_log_dir(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_empty_files_in_log_dir": self.add_empty_file_in_log_dir(self.current_failure_node) elif self.failure_type == "disable_empty_files_in_log_dir": self.remove_dummy_file_in_log_dir(self.current_failure_node) elif self.failure_type == "dummy_file_in_log_dir": self._dummy_file_in_log_dir(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_dummy_file_in_log_dir": self.add_dummy_file_in_log_dir(self.current_failure_node) elif self.failure_type == "disable_dummy_file_in_log_dir": self.remove_dummy_file_in_log_dir(self.current_failure_node) elif self.failure_type == "limit_file_size_limit": self._enable_disable_limit_file_size_limit(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_limit_file_size_limit": self.enable_file_size_limit(self.current_failure_node) elif self.failure_type == "disable_limit_file_size_limit": self.disable_file_size_limit(self.current_failure_node) elif self.failure_type == "disk_readonly": self._enable_disable_disk_readonly(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_disk_readonly": self._enable_disk_readonly(self.current_failure_node) elif self.failure_type == "disable_disk_readonly": self._disable_disk_readonly(self.current_failure_node) elif self.failure_type == "stress_ram": self._enable_stress_ram(self.current_failure_node, self.failure_timeout) elif self.failure_type == "stress_cpu": self._enable_stress_cpu(self.current_failure_node, self.failure_timeout) elif self.failure_type == "network_delay": self._enable_disable_network_delay(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_network_delay": self.enable_network_delay(self.current_failure_node) elif self.failure_type == "disable_network_delay": self.delete_network_rule(self.current_failure_node) elif self.failure_type == "net_packet_loss": self._enable_disable_packet_loss(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_net_packet_loss": self.enable_packet_loss(self.current_failure_node) elif self.failure_type == "disable_net_packet_loss": self.delete_network_rule(self.current_failure_node) elif self.failure_type == "enable_firewall": self._enable_disable_firewall(self.current_failure_node, self.failure_timeout) if self.failure_type == "induce_enable_firewall": self._enable_firewall(self.current_failure_node) elif self.failure_type == "disable_firewall": self._disable_firewall(self.current_failure_node) elif self.failure_type == "restart_couchbase": self._restart_couchbase_server(self.current_failure_node, self.failure_timeout) elif self.failure_type == "stop_couchbase": self._stop_couchbase_server(self.current_failure_node) elif self.failure_type == "start_couchbase": self._start_couchbase_server(self.current_failure_node) elif self.failure_type == "restart_network": self._stop_restart_network(self.current_failure_node, self.failure_timeout) elif self.failure_type == "restart_machine": self._restart_machine(self.current_failure_node) elif self.failure_type == "stop_memcached": self._stop_memcached(self.current_failure_node) elif self.failure_type == "start_memcached": self._start_memcached(self.current_failure_node) elif self.failure_type == "kill_goxdcr": self._kill_goxdcr(self.current_failure_node) elif self.failure_type == "network_split": self._block_incoming_network_from_node(self.servers_to_fail[0], self.servers_to_fail[ self.itr + 1]) self.itr += 1 elif self.failure_type == "disk_failure": self._fail_recover_disk_failure(self.current_failure_node, self.failure_timeout) elif self.failure_type == "induce_disk_failure": self._fail_disk(self.current_failure_node) elif self.failure_type == "disk_full": self._disk_full_recover_failure(self.current_failure_node, self.failure_timeout) elif self.failure_type == "shard_json_corruption": self.shard_json_corruption(self.current_failure_node) elif self.failure_type == "induce_disk_full": self._disk_full_failure(self.current_failure_node) elif self.failure_type == "recover_disk_failure": self._recover_disk(self.current_failure_node) elif self.failure_type == "recover_disk_full_failure": self._recover_disk_full_failure(self.current_failure_node) self.log.info("Start time = {}".format(time.ctime(self.start_time))) self.itr += 1 def _enable_disable_firewall(self, node, recover_time): self._enable_firewall(node) time.sleep(recover_time) self._disable_firewall(node) def _enable_disable_packet_loss(self, node, recover_time): self.enable_packet_loss(node) time.sleep(recover_time) self.delete_network_rule(node) def _enable_disable_limit_file_limits(self, node, recover_time): self.enable_file_limit(node) time.sleep(recover_time) self.disable_file_limit(node) def _enable_disable_limit_file_size_limit(self, node, recover_time): self.enable_file_size_limit(node) time.sleep(recover_time) self.disable_file_size_limit(node) def enable_file_size_limit(self, node): shell = RemoteMachineShellConnection(node) self.log.info("Updating file size limit to 10MB on {}".format(node)) shell.enable_file_size_limit() shell.disconnect() self.log.info("Enabled file size limit on {}".format(node)) def disable_file_size_limit(self, node): shell = RemoteMachineShellConnection(node) shell.disable_file_size_limit() shell.disconnect() self.log.info("disabled file size limit on {}".format(node)) def enable_file_limit(self, node): shell = RemoteMachineShellConnection(node) shell.enable_file_limit() shell.disconnect() self.log.info("Enabled file limit on {}".format(node)) def disable_file_limit(self, node): shell = RemoteMachineShellConnection(node) shell.disable_file_limit() shell.disconnect() self.log.info("disabled file limit on {}".format(node)) def _enable_disable_limit_file_limits_desc(self, node, recover_time): self.enable_file_limit_desc(node) time.sleep(recover_time) self.disable_file_limit_desc(node) def enable_file_limit_desc(self, node): shell = RemoteMachineShellConnection(node) shell.enable_file_limit_desc() shell.disconnect() self.log.info("Enabled file limit _desc on {}".format(node)) def disable_file_limit_desc(self, node): shell = RemoteMachineShellConnection(node) shell.disable_file_limit_desc() shell.disconnect() self.log.info("disabled file limit _desc on {}".format(node)) def _enable_disable_network_delay(self, node, recover_time): self.enable_network_delay(node) time.sleep(recover_time) self.delete_network_rule(node) def enable_network_delay(self, node): shell = RemoteMachineShellConnection(node) shell.enable_network_delay() shell.disconnect() self.log.info("Enabled network delay on {}".format(node)) def delete_network_rule(self, node): shell = RemoteMachineShellConnection(node) shell.delete_network_rule() shell.disconnect() self.log.info("Disabled packet loss on {}".format(node)) def enable_packet_loss(self, node): shell = RemoteMachineShellConnection(node) shell.enable_packet_loss() shell.disconnect() self.log.info("Enabled packet loss on {}".format(node)) def _enable_firewall(self, node): RemoteUtilHelper.enable_firewall(node) self.log.info("Enabled firewall on {}".format(node)) def _disable_firewall(self, node): shell = RemoteMachineShellConnection(node) shell.disable_firewall() def _restart_couchbase_server(self, node, failure_timeout): shell = RemoteMachineShellConnection(node) shell.restart_couchbase() shell.disconnect() self.log.info("Restarted the couchbase server on {}".format(node)) time.sleep(failure_timeout) def _stop_couchbase_server(self, node): shell = RemoteMachineShellConnection(node) shell.stop_couchbase() shell.disconnect() self.log.info("Stopped the couchbase server on {}".format(node)) def _start_couchbase_server(self, node): shell = RemoteMachineShellConnection(node) shell.start_couchbase() shell.disconnect() self.log.info("Started the couchbase server on {}".format(node)) def _enable_stress_cpu(self, node, stop_time): shell = RemoteMachineShellConnection(node) shell.cpu_stress(stop_time) shell.disconnect() self.log.info("cpu stressed for {0} sec on node {1}".format(stop_time, node)) def _enable_stress_ram(self, node, stop_time): shell = RemoteMachineShellConnection(node) shell.ram_stress(stop_time) shell.disconnect() self.log.info("ram stressed for {0} sec on node {1}".format(stop_time, node)) def _enable_disk_readonly(self, node): shell = RemoteMachineShellConnection(node) shell.enable_disk_readonly(self.disk_location) shell.disconnect() self.log.info("Dir {} made readonly on node {}".format(self.disk_location, node)) def _disable_disk_readonly(self, node): shell = RemoteMachineShellConnection(node) shell.disable_disk_readonly(self.disk_location) shell.disconnect() self.log.info("Dir {} made read/write on node {}".format(self.disk_location, node)) def _stop_restart_network(self, node, stop_time): shell = RemoteMachineShellConnection(node) shell.stop_network(stop_time) shell.disconnect() self.log.info("Stopped the network for {0} sec and restarted the " "network on {1}".format(stop_time, node)) def _restart_machine(self, node): shell = RemoteMachineShellConnection(node) command = "/sbin/reboot" shell.execute_command(command=command) def _stop_memcached(self, node): time.sleep(1) shell = RemoteMachineShellConnection(node) o, r = shell.stop_memcached() self.log.info("Killed memcached. {0} {1}".format(o, r)) def _start_memcached(self, node): shell = RemoteMachineShellConnection(node) o, r = shell.start_memcached() self.log.info("Started back memcached. {0} {1}".format(o, r)) shell.disconnect() def _kill_goxdcr(self, node): shell = RemoteMachineShellConnection(node) o, r = shell.kill_goxdcr() self.log.info("Killed goxdcr. {0} {1}".format(o, r)) def _block_incoming_network_from_node(self, node1, node2): shell = RemoteMachineShellConnection(node1) self.log.info("Adding {0} into iptables rules on {1}".format( node1.ip, node2.ip)) command = "iptables -A INPUT -s {0} -j DROP".format(node2.ip) shell.execute_command(command) self.start_time = time.time() def _fail_recover_disk_failure(self, node, recover_time): self._fail_disk(node) time.sleep(recover_time) self._recover_disk(node) def _fail_disk(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.unmount_partition(self.disk_location) success = True if output: for line in output: if self.disk_location in line: success = False if success: self.log.info("Unmounted disk at location : {0} on {1}".format(self.disk_location, node.ip)) self.start_time = time.time() else: self.log.info("Could not fail the disk at {0} on {1}".format(self.disk_location, node.ip)) self.state = FINISHED self.set_exception(Exception("Could not fail the disk at {0} on {1}".format(self.disk_location, node.ip))) self.set_result(False) def _recover_disk(self, node): shell = RemoteMachineShellConnection(node) o, r = shell.mount_partition_ext4(self.disk_location) for line in o: if self.disk_location in line: self.log.info("Mounted disk at location : {0} on {1}".format(self.disk_location, node.ip)) return self.set_exception(Exception("Could not mount disk at location {0} on {1}".format(self.disk_location, node.ip))) raise Exception() def _disk_full_recover_failure(self, node, recover_time): self._disk_full_failure(node) time.sleep(recover_time) self._recover_disk_full_failure(node) def _extra_files_in_log_dir(self, node, recover_time): self.add_extra_files_in_log_dir(node) time.sleep(recover_time) self.remove_extra_files_in_log_dir(node) def add_extra_files_in_log_dir(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.add_extra_files_index_log_dir(self.disk_location) if error: self.log.info(error) def remove_extra_files_in_log_dir(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.remove_extra_files_index_log_dir(self.disk_location) if error: self.log.info(error) def _dummy_file_in_log_dir(self, node, recover_time): self.add_dummy_file_in_log_dir(node) time.sleep(recover_time) self.remove_dummy_file_in_log_dir(node) def add_dummy_file_in_log_dir(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.add_dummy_file_index_log_dir(self.disk_location) if error: self.log.info(error) def shard_json_corruption(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.shard_json_corruption(self.disk_location) if error: self.log.info(error) def remove_dummy_file_in_log_dir(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.remove_dummy_file_index_log_dir(self.disk_location) if error: self.log.info(error) def _empty_file_in_log_dir(self, node, recover_time): self.add_empty_file_in_log_dir(node) time.sleep(recover_time) self.remove_dummy_file_in_log_dir(node) def add_empty_file_in_log_dir(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.add_empty_file_index_log_dir(self.disk_location) if error: self.log.info(error) def _enable_disable_disk_readonly(self, node, recover_time): self._enable_disk_readonly(node) time.sleep(recover_time) self._disable_disk_readonly(node) def _disk_full_failure(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.fill_disk_space(self.disk_location) success = False if output: for line in output: if self.disk_location in line: if "0 100% {0}".format(self.disk_location) in line: success = True if success: self.log.info("Filled up disk Space at {0} on {1}".format(self.disk_location, node.ip)) self.start_time = time.time() else: self.log.info("Could not fill the disk at {0} on {1}".format(self.disk_location, node.ip)) #self.state = FINISHED #self.set_exception(Exception("Could not fill the disk at {0} on {1}".format(self.disk_location, node.ip))) def _recover_disk_full_failure(self, node): shell = RemoteMachineShellConnection(node) delete_file = "{0}/disk-quota.ext3".format(self.disk_location) output, error = shell.execute_command("rm -f {0}".format(delete_file)) self.log.info(output) if error: self.log.info(error) def _check_for_autofailover_initiation(self, failed_over_node): rest = RestConnection(self.master) ui_logs = rest.get_logs(10) ui_logs_text = [t["text"] for t in ui_logs] ui_logs_time = [t["serverTime"] for t in ui_logs] expected_log = "Starting failing over ['ns_1@{}']".format( failed_over_node.ip) if expected_log in ui_logs_text: failed_over_time = ui_logs_time[ui_logs_text.index(expected_log)] return True, failed_over_time return False, None def _wait_for_autofailover_initiation(self, timeout): autofailover_initated = False while time.time() < timeout + self.start_time: autofailover_initated, failed_over_time = \ self._check_for_autofailover_initiation( self.current_failure_node) if autofailover_initated: end_time = self._get_mktime_from_server_time(failed_over_time) time_taken = end_time - self.start_time return autofailover_initated, time_taken return autofailover_initated, -1 def _get_mktime_from_server_time(self, server_time): time_format = "%Y-%m-%dT%H:%M:%S" server_time = server_time.split('.')[0] mk_time = time.mktime(time.strptime(server_time, time_format)) return mk_time def _rebalance(self): rest = RestConnection(self.master) nodes = rest.node_statuses() rest.rebalance(otpNodes=[node.id for node in nodes]) rebalance_progress = rest.monitorRebalance() if not rebalance_progress: self.set_result(False) self.state = FINISHED self.set_exception(Exception("Failed to rebalance after failover")) def _check_if_rebalance_in_progress(self, timeout): rest = RestConnection(self.master) end_time = time.time() + timeout while time.time() < end_time: try: rebalance_status, progress = \ rest._rebalance_status_and_progress() if rebalance_status == "running": continue elif rebalance_status is None and progress == 100: return False, -1 except RebalanceFailedException: ui_logs = rest.get_logs(10) ui_logs_text = [t["text"] for t in ui_logs] ui_logs_time = [t["serverTime"] for t in ui_logs] rebalace_failure_log = "Rebalance exited with reason" for ui_log in ui_logs_text: if rebalace_failure_log in ui_log: rebalance_failure_time = ui_logs_time[ ui_logs_text.index(ui_log)] failover_log = "Could not automatically fail over " \ "node ('ns_1@{}'). Rebalance is " \ "running.".format( self.current_failure_node.ip) if failover_log in ui_logs_text: return True, self._get_mktime_from_server_time( rebalance_failure_time) else: return False, -2 return False, -3 class AutoFailoverNodesFailureTask(Task): def __init__(self, master, servers_to_fail, failure_type, timeout, pause=0, expect_auto_failover=True, timeout_buffer=3, check_for_failover=True, failure_timers=None, disk_timeout=0, disk_location=None, disk_size=200): Task.__init__(self, "AutoFailoverNodesFailureTask") self.master = master self.servers_to_fail = servers_to_fail self.num_servers_to_fail = self.servers_to_fail.__len__() self.itr = 0 self.failure_type = failure_type self.timeout = timeout self.pause = pause self.expect_auto_failover = expect_auto_failover self.check_for_autofailover = check_for_failover self.start_time = 0 self.timeout_buffer = timeout_buffer self.current_failure_node = self.servers_to_fail[0] self.max_time_to_wait_for_failover = self.timeout + \ self.timeout_buffer + 200 self.disk_timeout = disk_timeout self.disk_location = disk_location self.disk_size = disk_size if failure_timers is None: failure_timers = [] self.failure_timers = failure_timers self.taskmanager = None self.rebalance_in_progress = False def execute(self, task_manager): self.taskmanager = task_manager rest = RestConnection(self.master) if rest._rebalance_progress_status() == "running": self.rebalance_in_progress = True while self.has_next() and not self.done(): next(self) if self.pause > 0 and self.pause > self.timeout: self.check(task_manager) if self.pause == 0 or 0 < self.pause < self.timeout: self.check(task_manager) self.state = FINISHED self.set_result(True) def check(self, task_manager): if not self.check_for_autofailover: self.state = EXECUTING return rest = RestConnection(self.master) max_timeout = self.timeout + self.timeout_buffer + self.disk_timeout if self.start_time == 0: message = "Did not inject failure in the system." rest.print_UI_logs(10) self.log.error(message) self.state = FINISHED self.set_result(False) self.set_exception(AutoFailoverException(message)) if self.rebalance_in_progress: status, stop_time = self._check_if_rebalance_in_progress(120) if not status: if stop_time == -1: message = "Rebalance already completed before failover " \ "of node" self.log.error(message) self.state = FINISHED self.set_result(False) self.set_exception(AutoFailoverException(message)) elif stop_time == -2: message = "Rebalance failed but no failed autofailover " \ "message was printed in logs" self.log.warning(message) else: message = "Rebalance not failed even after 2 minutes " \ "after node failure." self.log.error(message) rest.print_UI_logs(10) self.state = FINISHED self.set_result(False) self.set_exception(AutoFailoverException(message)) else: self.start_time = stop_time autofailover_initiated, time_taken = \ self._wait_for_autofailover_initiation( self.max_time_to_wait_for_failover) if self.expect_auto_failover: if autofailover_initiated: if time_taken < max_timeout + 1: self.log.info("Autofailover of node {0} successfully " "initiated in {1} sec".format( self.current_failure_node.ip, time_taken)) rest.print_UI_logs(10) self.state = EXECUTING else: message = "Autofailover of node {0} was initiated after " \ "the timeout period. Expected timeout: {1} " \ "Actual time taken: {2}".format( self.current_failure_node.ip, self.timeout, time_taken) self.log.error(message) rest.print_UI_logs(10) self.state = FINISHED self.set_result(False) self.set_exception(AutoFailoverException(message)) else: message = "Autofailover of node {0} was not initiated after " \ "the expected timeout period of {1}".format( self.current_failure_node.ip, self.timeout) rest.print_UI_logs(10) self.log.error(message) self.state = FINISHED self.set_result(False) self.set_exception(AutoFailoverException(message)) else: if autofailover_initiated: message = "Node {0} was autofailed over but no autofailover " \ "of the node was expected".format( self.current_failure_node.ip) rest.print_UI_logs(10) self.log.error(message) self.state = FINISHED self.set_result(False) self.set_exception(AutoFailoverException(message)) else: self.log.info("Node not autofailed over as expected") rest.print_UI_logs(10) self.state = EXECUTING def has_next(self): return self.itr < self.num_servers_to_fail def __next__(self): if self.pause != 0: time.sleep(self.pause) if self.pause > self.timeout and self.itr != 0: rest = RestConnection(self.master) status = rest.reset_autofailover() self._rebalance() if not status: self.state = FINISHED self.set_result(False) self.set_exception(Exception("Reset of autofailover " "count failed")) self.current_failure_node = self.servers_to_fail[self.itr] self.log.info("before failure time: {}".format(time.ctime(time.time()))) if self.failure_type == "enable_firewall": self._enable_firewall(self.current_failure_node) elif self.failure_type == "disable_firewall": self._disable_firewall(self.current_failure_node) elif self.failure_type == "restart_couchbase": self._restart_couchbase_server(self.current_failure_node) elif self.failure_type == "stop_couchbase": self._stop_couchbase_server(self.current_failure_node) elif self.failure_type == "start_couchbase": self._start_couchbase_server(self.current_failure_node) elif self.failure_type == "restart_network": self._stop_restart_network(self.current_failure_node, self.timeout + self.timeout_buffer + 30) elif self.failure_type == "restart_machine": self._restart_machine(self.current_failure_node) elif self.failure_type == "stop_indexer": self._stop_indexer(self.current_failure_node) elif self.failure_type == "start_indexer": self._start_indexer(self.current_failure_node) elif self.failure_type == "block_indexer_port": self._block_indexer_port(self.current_failure_node) elif self.failure_type == "resume_indexer_port": self._resume_indexer_port(self.current_failure_node) elif self.failure_type == "stop_memcached": self._stop_memcached(self.current_failure_node) elif self.failure_type == "start_memcached": self._start_memcached(self.current_failure_node) elif self.failure_type == "network_split": self._block_incoming_network_from_node(self.servers_to_fail[0], self.servers_to_fail[ self.itr + 1]) self.itr += 1 elif self.failure_type == "disk_failure": self._fail_disk(self.current_failure_node) elif self.failure_type == "disk_full": self._disk_full_failure(self.current_failure_node) elif self.failure_type == "recover_disk_failure": self._recover_disk(self.current_failure_node) elif self.failure_type == "recover_disk_full_failure": self._recover_disk_full_failure(self.current_failure_node) self.log.info("Start time = {}".format(time.ctime(self.start_time))) self.itr += 1 def _enable_firewall(self, node): node_failure_timer = self.failure_timers[self.itr] time.sleep(1) RemoteUtilHelper.enable_firewall(node) self.log.info("Enabled firewall on {}".format(node)) node_failure_timer.result() self.start_time = node_failure_timer.start_time def _disable_firewall(self, node): shell = RemoteMachineShellConnection(node) shell.disable_firewall() def _restart_couchbase_server(self, node): node_failure_timer = self.failure_timers[self.itr] time.sleep(1) shell = RemoteMachineShellConnection(node) shell.restart_couchbase() shell.disconnect() self.log.info("Restarted the couchbase server on {}".format(node)) node_failure_timer.result() self.start_time = node_failure_timer.start_time def _stop_couchbase_server(self, node): node_failure_timer = self.failure_timers[self.itr] time.sleep(1) shell = RemoteMachineShellConnection(node) shell.stop_couchbase() shell.disconnect() self.log.info("Stopped the couchbase server on {}".format(node)) node_failure_timer.result() self.start_time = node_failure_timer.start_time def _start_couchbase_server(self, node): shell = RemoteMachineShellConnection(node) shell.start_couchbase() shell.disconnect() self.log.info("Started the couchbase server on {}".format(node)) def _stop_restart_network(self, node, stop_time): node_failure_timer = self.failure_timers[self.itr] time.sleep(1) shell = RemoteMachineShellConnection(node) shell.stop_network(stop_time) shell.disconnect() self.log.info("Stopped the network for {0} sec and restarted the " "network on {1}".format(stop_time, node)) node_failure_timer.result() self.start_time = node_failure_timer.start_time def _restart_machine(self, node): node_failure_timer = self.failure_timers[self.itr] time.sleep(1) shell = RemoteMachineShellConnection(node) command = "/sbin/reboot" shell.execute_command(command=command) node_failure_timer.result() self.start_time = node_failure_timer.start_time def _block_indexer_port(self, node): shell = RemoteMachineShellConnection(node) self.log.info(f"Blocking port 9103 and 9105 on {node}") shell.execute_command("iptables -A INPUT -p tcp --destination-port 9103 -j DROP") shell.execute_command("iptables -A OUTPUT -p tcp --destination-port 9103 -j DROP") shell.execute_command("iptables -A INPUT -p tcp --destination-port 9105 -j DROP") shell.execute_command("iptables -A OUTPUT -p tcp --destination-port 9105 -j DROP") def _resume_indexer_port(self, node): shell = RemoteMachineShellConnection(node) self.log.info(f"Resuming port 9103 and 9105 on {node}") shell.execute_command("iptables -D INPUT -p tcp --destination-port 9103 -j DROP") shell.execute_command("iptables -D OUTPUT -p tcp --destination-port 9103 -j DROP") shell.execute_command("iptables -D INPUT -p tcp --destination-port 9105 -j DROP") shell.execute_command("iptables -D OUTPUT -p tcp --destination-port 9105 -j DROP") def _stop_indexer(self, node): node_failure_timer = self.failure_timers[self.itr] time.sleep(1) shell = RemoteMachineShellConnection(node) o, r = shell.stop_indexer() self.log.info("Killed indexer. {0} {1}".format(o, r)) node_failure_timer.result() self.start_time = node_failure_timer.start_time def _start_indexer(self, node): shell = RemoteMachineShellConnection(node) o, r = shell.start_indexer() self.log.info("Started back indexer. {0} {1}".format(o, r)) shell.disconnect() def _stop_memcached(self, node): node_failure_timer = self.failure_timers[self.itr] time.sleep(1) shell = RemoteMachineShellConnection(node) o, r = shell.stop_memcached() self.log.info("Killed memcached. {0} {1}".format(o, r)) node_failure_timer.result() self.start_time = node_failure_timer.start_time def _start_memcached(self, node): shell = RemoteMachineShellConnection(node) o, r = shell.start_memcached() self.log.info("Started back memcached. {0} {1}".format(o, r)) shell.disconnect() def _block_incoming_network_from_node(self, node1, node2): shell = RemoteMachineShellConnection(node1) self.log.info("Adding {0} into iptables rules on {1}".format( node1.ip, node2.ip)) command = "iptables -A INPUT -s {0} -j DROP".format(node2.ip) shell.execute_command(command) self.start_time = time.time() def _fail_disk(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.unmount_partition(self.disk_location) success = True if output: for line in output: if self.disk_location in line: success = False if success: self.log.info("Unmounted disk at location : {0} on {1}".format(self.disk_location, node.ip)) self.start_time = time.time() else: self.log.info("Could not fail the disk at {0} on {1}".format(self.disk_location, node.ip)) self.state = FINISHED self.set_exception(Exception("Could not fail the disk at {0} on {1}".format(self.disk_location, node.ip))) self.set_result(False) def _recover_disk(self, node): shell = RemoteMachineShellConnection(node) o, r = shell.mount_partition(self.disk_location) for line in o: if self.disk_location in line: self.log.info("Mounted disk at location : {0} on {1}".format(self.disk_location, node.ip)) return self.set_exception(Exception("Could not mount disk at location {0} on {1}".format(self.disk_location, node.ip))) raise Exception() def _disk_full_failure(self, node): shell = RemoteMachineShellConnection(node) output, error = shell.fill_disk_space(self.disk_location, self.disk_size) success = False if output: for line in output: if self.disk_location in line: if "0 100% {0}".format(self.disk_location) in line: success = True if success: self.log.info("Filled up disk Space at {0} on {1}".format(self.disk_location, node.ip)) self.start_time = time.time() else: self.log.info("Could not fill the disk at {0} on {1}".format(self.disk_location, node.ip)) self.state = FINISHED self.set_exception(Exception("Could not fill the disk at {0} on {1}".format(self.disk_location, node.ip))) def _recover_disk_full_failure(self, node): shell = RemoteMachineShellConnection(node) delete_file = "{0}/disk-quota.ext3".format(self.disk_location) output, error = shell.execute_command("rm -f {0}".format(delete_file)) self.log.info(output) if error: self.log.info(error) def _check_for_autofailover_initiation(self, failed_over_node): rest = RestConnection(self.master) ui_logs = rest.get_logs(10) ui_logs_text = [t["text"] for t in ui_logs] ui_logs_time = [t["serverTime"] for t in ui_logs] expected_log = "Starting failing over ['ns_1@{}']".format( failed_over_node.ip) if expected_log in ui_logs_text: failed_over_time = ui_logs_time[ui_logs_text.index(expected_log)] return True, failed_over_time return False, None def _wait_for_autofailover_initiation(self, timeout): autofailover_initated = False while time.time() < timeout + self.start_time: autofailover_initated, failed_over_time = \ self._check_for_autofailover_initiation( self.current_failure_node) if autofailover_initated: end_time = self._get_mktime_from_server_time(failed_over_time) time_taken = end_time - self.start_time return autofailover_initated, time_taken return autofailover_initated, -1 def _get_mktime_from_server_time(self, server_time): time_format = "%Y-%m-%dT%H:%M:%S" server_time = server_time.split('.')[0] mk_time = time.mktime(time.strptime(server_time, time_format)) return mk_time def _rebalance(self): rest = RestConnection(self.master) nodes = rest.node_statuses() rest.rebalance(otpNodes=[node.id for node in nodes]) rebalance_progress = rest.monitorRebalance() if not rebalance_progress: self.set_result(False) self.state = FINISHED self.set_exception(Exception("Failed to rebalance after failover")) def _check_if_rebalance_in_progress(self, timeout): rest = RestConnection(self.master) end_time = time.time() + timeout while time.time() < end_time: try: rebalance_status, progress = \ rest._rebalance_status_and_progress() if rebalance_status == "running": continue elif rebalance_status is None and progress == 100: return False, -1 except RebalanceFailedException: ui_logs = rest.get_logs(10) ui_logs_text = [t["text"] for t in ui_logs] ui_logs_time = [t["serverTime"] for t in ui_logs] rebalace_failure_log = "Rebalance exited with reason" for ui_log in ui_logs_text: if rebalace_failure_log in ui_log: rebalance_failure_time = ui_logs_time[ ui_logs_text.index(ui_log)] failover_log = "Could not automatically fail over " \ "node ('ns_1@{}'). Rebalance is " \ "running.".format( self.current_failure_node.ip) if failover_log in ui_logs_text: return True, self._get_mktime_from_server_time( rebalance_failure_time) else: return False, -2 return False, -3 class NodeDownTimerTask(Task): def __init__(self, node, port=None, timeout=300): Task.__init__(self, "NodeDownTimerTask") self.log.info("Initializing NodeDownTimerTask") self.node = node self.port = port self.timeout = timeout self.start_time = 0 def execute(self, task_manager): self.log.info("Starting execution of NodeDownTimerTask") end_task = time.time() + self.timeout while not self.done() and time.time() < end_task: if not self.port: try: self.start_time = time.time() response = os.system("ping -c 1 {} > /dev/null".format( self.node)) if response != 0: self.log.info("Injected failure in {}. Caught " "due to ping".format(self.node)) self.state = FINISHED self.set_result(True) break except Exception as e: self.log.warning("Unexpected exception caught {" "}".format(e)) self.state = FINISHED self.set_result(True) break try: self.start_time = time.time() socket.socket().connect(("{}".format(self.node), 8091)) socket.socket().close() socket.socket().connect(("{}".format(self.node), 11210)) socket.socket().close() except socket.error: self.log.info("Injected failure in {}. Caught due " "to ports".format(self.node)) self.state = FINISHED self.set_result(True) break else: try: self.start_time = time.time() socket.socket().connect(("{}".format(self.node), int(self.port))) socket.socket().close() socket.socket().connect(("{}".format(self.node), 11210)) socket.socket().close() except socket.error: self.log.info("Injected failure in {}".format(self.node)) self.state = FINISHED self.set_result(True) break if time.time() >= end_task: self.state = FINISHED self.set_result(False) self.log.info("Could not inject failure in {}".format(self.node)) def check(self, task_manager): pass class NodeMonitorsAnalyserTask(Task): def __init__(self, node, stop=False): Task.__init__(self, "NodeMonitorAnalyzerTask") self.command = "dict:to_list(node_status_analyzer:get_nodes())" self.master = node self.rest = RestConnection(self.master) self.stop = stop def execute(self, task_manager): while not self.done() and not self.stop: self.status, self.content = self.rest.diag_eval(self.command, print_log=False) self.state = CHECKING def check(self, task_manager): if self.status and self.content: self.log.info("NodeStatus: {}".format(self.content)) if not self.master.ip in self.content: self.set_result(False) self.state = FINISHED self.set_exception(Exception("Node status monitors does not " "contain the node status")) return time.sleep(1) self.state = EXECUTING else: raise Exception("Monitors not working correctly") # Runs java sdk client directly on slave class SDKLoadDocumentsTask(Task): def __init__(self, server, bucket, sdk_docloader): Task.__init__(self, "SDKLoadDocumentsTask") self.server = server if isinstance(bucket, Bucket): self.bucket = bucket.name else: self.bucket = bucket self.sdk_docloader = sdk_docloader def execute_for_collection(self, collection, start_seq_num_shift=0): import subprocess command = f"java -jar java_sdk_client/collections/target/javaclient/javaclient.jar " \ f"-i {self.server.ip} -u {self.sdk_docloader.username} -p {self.sdk_docloader.password} -b {self.bucket} " \ f"-s {self.sdk_docloader.scope} -c {collection} " \ f"-n {self.sdk_docloader.num_ops} -pc {self.sdk_docloader.percent_create} -pu {self.sdk_docloader.percent_update} " \ f"-pd {self.sdk_docloader.percent_delete} -l {self.sdk_docloader.load_pattern} " \ f"-dsn {self.sdk_docloader.start_seq_num + start_seq_num_shift} -dpx {self.sdk_docloader.key_prefix} -dt {self.sdk_docloader.json_template} " \ f"-de {self.sdk_docloader.doc_expiry} -ds {self.sdk_docloader.doc_size} -ac {self.sdk_docloader.all_collections} " \ f"-st {self.sdk_docloader.start+start_seq_num_shift} -en {self.sdk_docloader.end+start_seq_num_shift} -o {self.sdk_docloader.output} -sd {self.sdk_docloader.shuffle_docs} --secure {self.sdk_docloader.secure}" if self.sdk_docloader.es_compare: command = command + " -es true -es_host " + str(self.sdk_docloader.es_host) + " -es_port " + str( self.sdk_docloader.es_port) + \ " -es_login " + str(self.sdk_docloader.es_login) + " -es_password " + str( self.sdk_docloader.es_password) if self.sdk_docloader.op_type == "update": arr_fields_to_update = self.sdk_docloader.fields_to_update if self.sdk_docloader.fields_to_update else "" if len(arr_fields_to_update) > 0: command = command + " -fu " command = command + ",".join(arr_fields_to_update) self.log.info(command) try: proc = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) out = proc.communicate(timeout=self.sdk_docloader.timeout) if self.sdk_docloader.get_sdk_logs: self.sdk_docloader.set_sdk_results(out) self.log.info(out[0].decode("utf-8")) if proc.returncode != 0: raise Exception("Exception in java sdk client to {}:{}\n{}".format(self.server.ip, self.bucket, out)) except Exception as e: proc.terminate() self.state = FINISHED self.set_exception(e) proc.terminate() self.state = FINISHED self.set_result(True) def execute(self, task_manager): if type(self.sdk_docloader.collection) is list: start_seq_num_shift = 0 for c in self.sdk_docloader.collection: self.execute_for_collection(c, start_seq_num_shift) start_seq_num_shift = start_seq_num_shift + self.sdk_docloader.upd_del_shift else: self.execute_for_collection(self.sdk_docloader.collection) self.check(task_manager) #TODO additional sleep to let ES finish with docs indexing, should be replaced with something more intelligent. time.sleep(30) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) # Runs java sdk client on a docker container on slave class DockerSDKLoadDocumentsTask(Task): def __init__(self, server, bucket, sdk_docloader, pause_secs, timeout_secs): Task.__init__(self, "SDKLoadDocumentsTask") self.server = server if isinstance(bucket, Bucket): self.bucket = bucket.name else: self.bucket = bucket self.params = sdk_docloader self.pause_secs = pause_secs self.timeout_secs = timeout_secs from lib.collection.collections_dataloader import JavaSDKClient self.javasdkclient = JavaSDKClient(self.server, self.bucket, self.params) def execute(self, task_manager): try: self.javasdkclient.do_ops() self.state = CHECKING task_manager.schedule(self) except Exception as e: self.state = FINISHED self.set_exception(Exception("Exception while loading data to {}:{}" .format(self.server.ip, self.bucket))) finally: self.javasdkclient.cleanup() def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self) #TODO: # input params to include,exclude keywords, # populate dictionary {node:matches} in setUp() # call LogScanTask in basetestcase tearDown() and diff dict # add sensitive data patterns # pretty print matches class LogScanTask(Task): def __init__(self, server, file_prefix): Task.__init__(self, "log_scan_task") self.server = server self.log_scan_file_name = f'{self.server.ip}_{file_prefix}' from lib.log_scanner import LogScanner exclude_keywords = TestInputSingleton.input.param("exclude_keywords", None) skip_security_scan = TestInputSingleton.input.param("skip_security_scan", False) self.log_scanner = LogScanner(server=self.server, exclude_keywords=exclude_keywords, skip_security_scan=skip_security_scan) def execute(self, task_manager): try: # Scan logs corresponding to node services matches = self.log_scanner.scan() target = open(self.log_scan_file_name, 'w+') target.write(str(matches)) target.close() self.state = CHECKING task_manager.schedule(self) # catch and set all unexpected exceptions except Exception as e: self.state = FINISHED self.set_unexpected_exception(e) def check(self, task_manager): self.set_result(True) self.state = FINISHED task_manager.schedule(self)
""" This is a very first draft idea of a module system. The general idea is to NOT use Djangos ``django.setup()`` which inherently uses the ENV Variable to find the path to a settings.py and loads it. Instead we use the ``settings.configure()`` method INSTEAD of ``django.setup()`` where you can pass in arbitrary settings. From my understanding ``django.setup()`` BASICALLY does nothing else than to load the settings.py (from the ENV variable) and then calls configure with all (ALL CAPS) Variables from the settings.py file. """ import importlib import inspect import logging import os import sys from typing import Dict, Optional, List, Set, Union, Iterable logger = logging.getLogger("modules") MODULE_LOCATIONS = ["omap.modules.omap_module_registry"] _modules = [] def modules(): return _modules class ModuleConfig: pass class OmapModule(object): """ Very simple implementation of all properties of a "Module" """ def __init__( self, module_name, module_version, django_apps, module_dependencies: Optional[List[str]] = None, settings_entries: Optional[Dict] = None, constance_config: Optional[Dict] = None, pip_dependencies=None, ) -> None: self.module_name = module_name self.module_version = module_version self.django_apps = django_apps self.module_dependencies = module_dependencies self.settings_entries = settings_entries self.constance_config = constance_config self.pip_dependencies = pip_dependencies # BASE_DIR = Path(__file__).resolve().parent.parent def collect_registry(module_locations: List[str]): module_configs = {} for module in module_locations: logger.debug(f"Checking module {module}") m = importlib.import_module(module) module_definitions = [] for a, b in inspect.getmembers(m): if inspect.isclass(b) and inspect.getmodule(b) == m: if issubclass(b, ModuleConfig): logger.debug(f"Adding class {b} to module definitions") module_definitions.append(b) if len(module_definitions) == 0: logger.warning(f"No module definition found in module {module}") continue for definition in module_definitions: logger.debug( f"We found definition {definition.__name__} in module {module}" ) # Get all necessary attributes attributes = { "module_name": None, "module_version": None, "django_apps": None, "pip_dependencies": [], "module_dependencies": [], "settings_entries": {}, "constance_config": {}, } module_dict = {} for attr_name, default in attributes.items(): if not hasattr(definition, attr_name): if default is not None: module_dict[attr_name] = default continue else: raise RuntimeError(f"Missing required attribute {attr_name}") module_dict[attr_name] = getattr(definition, attr_name) logger.debug(f"Module Dict: {module_dict}") if module_dict["module_name"] in module_configs: raise RuntimeError( f"Duplicate Module Name found: {module_dict["name"]}" ) # Create Portal Module class from it module_configs[module_dict["module_name"]] = OmapModule(**module_dict) return module_configs # This is a draft for a registr. # In a real world scenario this would be loaded from some manifest or cfg files or something?! modules_registry = collect_registry(MODULE_LOCATIONS) def resolve(modules: Union[str, List[str]]) -> Iterable[OmapModule]: """ This method takes one or more module names and looks up the modules in the registry above. Then it checks if the modules have dependencies on other moduels and if so, adds them to the "context" as well. It finally returns a complete list of all modules that have to be loaded OR ends with an exception """ unresolved = [modules] if isinstance(modules, str) else modules if len(unresolved) == 0: raise AssertionError("No module given to load, terminating!") resolved = [] # resolve until all are resolved while len(unresolved) > 0: module_name = unresolved.pop() logging.info(f"Checking resolution for {module_name}") if module_name in resolved: unresolved.remove(module_name) continue logging.info(f"Resolving {module_name}") module: OmapModule = modules_registry.get(module_name) if not module: raise RuntimeError(f"Unresolvable Module {module_name}") resolved.append(module) if module.module_dependencies: logging.info(f"Found dependencies: {module.module_dependencies}") unresolved.extend(module.module_dependencies) logging.info( f"Modules to load: {[m.module_name + ":" + m.module_version for m in resolved]}" ) return resolved def install_modules(modules: Iterable[OmapModule]): def install(package): import subprocess subprocess.check_call([sys.executable, "-m", "pip", "install", package]) logging.info("Check if there are module dependencies to install...") for module in modules: module: OmapModule logging.info(f"Checking Module {module.module_name}:{module.module_version}") if module.pip_dependencies: logging.info( f"Module {module.module_name}:{module.module_version} has dependencies" ) for package in module.pip_dependencies: logging.info(f"Start Installation of package {package}") try: install(package) logging.info(f"Successfully installed {package}") except Exception: raise ModuleNotFoundError( f"Unable to install package {package} for Module {module.module_name}:{module.module_version}" ) logging.info( f"Successfully installed all dependencies for {module.module_name}:{module.module_version}" ) def configure_modules(): """ This is the central hook. It loads the name(s) of the Modules to load from the env variable OMAP_MODULES, resolves them and then configures django accordingly. So this is a somewhat "improved" version of the ``django.setup()`` function but serves the same purpose """ # Add them to the "installed" modules logging.basicConfig(level="INFO") from django.conf import settings if settings.configured: logging.info("Settings already configured, skipping...") return modules = get_resolved_modules() global _modules _modules = modules.copy() apps: Set = set() additional_settings = {} constance_config = {} # Install modules install_modules(modules) for module in modules: module: OmapModule apps.update(module.django_apps) if module.settings_entries: additional_settings.update(module.settings_entries) if module.constance_config: constance_config.update(module.constance_config) from django.conf import settings # merge constnace configs, if there are multiple ones if "CONSTANCE_CONFIG" in additional_settings: constance_config.update(additional_settings["CONSTANCE_CONFIG"]) del additional_settings["CONSTANCE_CONFIG"] base_settings = {} if os.getenv("DJANGO_SETTINGS_MODULE"): # We can use a base settings file settings_module = os.getenv("DJANGO_SETTINGS_MODULE") logging.info(f"Using '{settings_module}' as base settings") mod = importlib.import_module(settings_module) for setting in dir(mod): if setting.isupper(): setting_value = getattr(mod, setting) base_settings[setting] = setting_value # We have to be careful with the merge especially with INSTALLED_APPS merged_apps = ( base_settings.get("INSTALLED_APPS", []) + additional_settings.get("INSTALLED_APPS", []) + list(apps) ) # Same goes with CONSTANCE Config merged_constance = {**base_settings.get("CONSTANCE_CONFIG", {}), **constance_config} merged = base_settings.copy() merged.update(additional_settings) # Handle special cases merged.update({"INSTALLED_APPS": merged_apps}) merged.update({"CONSTANCE_CONFIG": merged_constance}) # TEST for dynamic urls # merged.update({"ROOT_URLCONF": "omap.modules.module_urls"}) settings.configure(**merged) # Now modify the INSTALLED_APPS for all apps that contain a urls.py file # TODO do this after the apps are ready # from django.apps import apps as django_apps # # for app in django_apps.get_app_configs(): # if not hasattr(app, "url_prefix"): # urls_path = app.module.__name__ + ".urls" # try: # mod = importlib.import_module(urls_path) # except ModuleNotFoundError: # logging.debug(f"No url module found under {urls_path}", exc_info=True) # continue # # We can/should add it # setattr(app, "url_prefix", app.name) def get_resolved_modules(module_names=None): if module_names: modules = module_names else: # Read from ENV Variable modules = os.getenv("OMAP_MODULES") if not modules: # TODO do we need this? # raise RuntimeError( # "No Modules given, please set the module to env varibale OMAP_MODULES" # ) return [] module_list = modules.split(",") modules = resolve(module_list) return modules
""" This is a very first draft idea of a module system. The general idea is to NOT use Djangos ``django.setup()`` which inherently uses the ENV Variable to find the path to a settings.py and loads it. Instead we use the ``settings.configure()`` method INSTEAD of ``django.setup()`` where you can pass in arbitrary settings. From my understanding ``django.setup()`` BASICALLY does nothing else than to load the settings.py (from the ENV variable) and then calls configure with all (ALL CAPS) Variables from the settings.py file. """ import importlib import inspect import logging import os import sys from typing import Dict, Optional, List, Set, Union, Iterable logger = logging.getLogger("modules") MODULE_LOCATIONS = ["omap.modules.omap_module_registry"] _modules = [] def modules(): return _modules class ModuleConfig: pass class OmapModule(object): """ Very simple implementation of all properties of a "Module" """ def __init__( self, module_name, module_version, django_apps, module_dependencies: Optional[List[str]] = None, settings_entries: Optional[Dict] = None, constance_config: Optional[Dict] = None, pip_dependencies=None, ) -> None: self.module_name = module_name self.module_version = module_version self.django_apps = django_apps self.module_dependencies = module_dependencies self.settings_entries = settings_entries self.constance_config = constance_config self.pip_dependencies = pip_dependencies # BASE_DIR = Path(__file__).resolve().parent.parent def collect_registry(module_locations: List[str]): module_configs = {} for module in module_locations: logger.debug(f"Checking module {module}") m = importlib.import_module(module) module_definitions = [] for a, b in inspect.getmembers(m): if inspect.isclass(b) and inspect.getmodule(b) == m: if issubclass(b, ModuleConfig): logger.debug(f"Adding class {b} to module definitions") module_definitions.append(b) if len(module_definitions) == 0: logger.warning(f"No module definition found in module {module}") continue for definition in module_definitions: logger.debug( f"We found definition {definition.__name__} in module {module}" ) # Get all necessary attributes attributes = { "module_name": None, "module_version": None, "django_apps": None, "pip_dependencies": [], "module_dependencies": [], "settings_entries": {}, "constance_config": {}, } module_dict = {} for attr_name, default in attributes.items(): if not hasattr(definition, attr_name): if default is not None: module_dict[attr_name] = default continue else: raise RuntimeError(f"Missing required attribute {attr_name}") module_dict[attr_name] = getattr(definition, attr_name) logger.debug(f"Module Dict: {module_dict}") if module_dict["module_name"] in module_configs: raise RuntimeError( f"Duplicate Module Name found: {module_dict['name']}" ) # Create Portal Module class from it module_configs[module_dict["module_name"]] = OmapModule(**module_dict) return module_configs # This is a draft for a registr. # In a real world scenario this would be loaded from some manifest or cfg files or something?! modules_registry = collect_registry(MODULE_LOCATIONS) def resolve(modules: Union[str, List[str]]) -> Iterable[OmapModule]: """ This method takes one or more module names and looks up the modules in the registry above. Then it checks if the modules have dependencies on other moduels and if so, adds them to the "context" as well. It finally returns a complete list of all modules that have to be loaded OR ends with an exception """ unresolved = [modules] if isinstance(modules, str) else modules if len(unresolved) == 0: raise AssertionError("No module given to load, terminating!") resolved = [] # resolve until all are resolved while len(unresolved) > 0: module_name = unresolved.pop() logging.info(f"Checking resolution for {module_name}") if module_name in resolved: unresolved.remove(module_name) continue logging.info(f"Resolving {module_name}") module: OmapModule = modules_registry.get(module_name) if not module: raise RuntimeError(f"Unresolvable Module {module_name}") resolved.append(module) if module.module_dependencies: logging.info(f"Found dependencies: {module.module_dependencies}") unresolved.extend(module.module_dependencies) logging.info( f"Modules to load: {[m.module_name + ':' + m.module_version for m in resolved]}" ) return resolved def install_modules(modules: Iterable[OmapModule]): def install(package): import subprocess subprocess.check_call([sys.executable, "-m", "pip", "install", package]) logging.info("Check if there are module dependencies to install...") for module in modules: module: OmapModule logging.info(f"Checking Module {module.module_name}:{module.module_version}") if module.pip_dependencies: logging.info( f"Module {module.module_name}:{module.module_version} has dependencies" ) for package in module.pip_dependencies: logging.info(f"Start Installation of package {package}") try: install(package) logging.info(f"Successfully installed {package}") except Exception: raise ModuleNotFoundError( f"Unable to install package {package} for Module {module.module_name}:{module.module_version}" ) logging.info( f"Successfully installed all dependencies for {module.module_name}:{module.module_version}" ) def configure_modules(): """ This is the central hook. It loads the name(s) of the Modules to load from the env variable OMAP_MODULES, resolves them and then configures django accordingly. So this is a somewhat "improved" version of the ``django.setup()`` function but serves the same purpose """ # Add them to the "installed" modules logging.basicConfig(level="INFO") from django.conf import settings if settings.configured: logging.info("Settings already configured, skipping...") return modules = get_resolved_modules() global _modules _modules = modules.copy() apps: Set = set() additional_settings = {} constance_config = {} # Install modules install_modules(modules) for module in modules: module: OmapModule apps.update(module.django_apps) if module.settings_entries: additional_settings.update(module.settings_entries) if module.constance_config: constance_config.update(module.constance_config) from django.conf import settings # merge constnace configs, if there are multiple ones if "CONSTANCE_CONFIG" in additional_settings: constance_config.update(additional_settings["CONSTANCE_CONFIG"]) del additional_settings["CONSTANCE_CONFIG"] base_settings = {} if os.getenv("DJANGO_SETTINGS_MODULE"): # We can use a base settings file settings_module = os.getenv("DJANGO_SETTINGS_MODULE") logging.info(f"Using '{settings_module}' as base settings") mod = importlib.import_module(settings_module) for setting in dir(mod): if setting.isupper(): setting_value = getattr(mod, setting) base_settings[setting] = setting_value # We have to be careful with the merge especially with INSTALLED_APPS merged_apps = ( base_settings.get("INSTALLED_APPS", []) + additional_settings.get("INSTALLED_APPS", []) + list(apps) ) # Same goes with CONSTANCE Config merged_constance = {**base_settings.get("CONSTANCE_CONFIG", {}), **constance_config} merged = base_settings.copy() merged.update(additional_settings) # Handle special cases merged.update({"INSTALLED_APPS": merged_apps}) merged.update({"CONSTANCE_CONFIG": merged_constance}) # TEST for dynamic urls # merged.update({"ROOT_URLCONF": "omap.modules.module_urls"}) settings.configure(**merged) # Now modify the INSTALLED_APPS for all apps that contain a urls.py file # TODO do this after the apps are ready # from django.apps import apps as django_apps # # for app in django_apps.get_app_configs(): # if not hasattr(app, "url_prefix"): # urls_path = app.module.__name__ + ".urls" # try: # mod = importlib.import_module(urls_path) # except ModuleNotFoundError: # logging.debug(f"No url module found under {urls_path}", exc_info=True) # continue # # We can/should add it # setattr(app, "url_prefix", app.name) def get_resolved_modules(module_names=None): if module_names: modules = module_names else: # Read from ENV Variable modules = os.getenv("OMAP_MODULES") if not modules: # TODO do we need this? # raise RuntimeError( # "No Modules given, please set the module to env varibale OMAP_MODULES" # ) return [] module_list = modules.split(",") modules = resolve(module_list) return modules
import json import aiohttp import discord from aiocache.decorators import cached from utils.context import BlooContext, PromptData from utils.permissions.permissions import permissions from utils.views.menu import Menu class TweakMenu(Menu): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs, timeout_function=self.on_timeout) self.jump_button = JumpButton(self.ctx.bot, len(self.pages), self) self.extra_buttons = [] def refresh_button_state(self): if self.ctx.repo: extra_buttons = [ discord.ui.Button(label='Add Repo to Sileo', emoji="<:sileo:679466569407004684>", url=f'https://sharerepo.stkc.win/v2/?pkgman=sileo&repo={self.ctx.repo}', style=discord.ButtonStyle.url, row=1), discord.ui.Button(label='Add Repo to Zebra', emoji="<:zebra:911433583032422420>", url=f'https://sharerepo.stkc.win/v2/?pkgman=zebra&repo={self.ctx.repo}', style=discord.ButtonStyle.url, row=1), discord.ui.Button(label='Other Package Managers', emoji="<:cydiasileosplit:932650041099825232>", url=f'https://sharerepo.stkc.win/?repo={self.ctx.repo}', style=discord.ButtonStyle.url, row=1) ] else: extra_buttons = [ discord.ui.Button(label='Cannot add default repo', emoji="<:sileo:679466569407004684>", url=f'https://sharerepo.stkc.win/v2/?pkgman=sileo&repo={self.ctx.repo}', disabled=True, style=discord.ButtonStyle.url, row=1), discord.ui.Button(label='Cannot add default repo', emoji="<:zebra:911433583032422420>", url=f'https://sharerepo.stkc.win/v2/?pkgman=zebra&repo={self.ctx.repo}', disabled=True, style=discord.ButtonStyle.url, row=1), discord.ui.Button(label='Cannot add default repo', emoji="<:Add:947354227171262534>", url=f'https://sharerepo.stkc.win/?repo={self.ctx.repo}', style=discord.ButtonStyle.url, disabled=True, row=1) ] if self.ctx.depiction: extra_buttons.insert(0, discord.ui.Button(label='View Depiction', emoji="<:Depiction:947358756033949786>", url=self.ctx.depiction, style=discord.ButtonStyle.url, row=1), ) if len(self.pages) > 1: extra_buttons.append(self.jump_button) for button in self.extra_buttons: self.remove_item(button) for button in extra_buttons: self.add_item(button) self.extra_buttons = extra_buttons super().refresh_button_state() async def on_timeout(self): self.jump_button.disabled = True self.stopped = True await self.refresh_response_message() self.stop() def on_interaction_check(self, interaction: discord.Interaction): return interaction.user == self.ctx.author or permissions.has(interaction.guild, interaction.user, 4) class BypassMenu(Menu): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs, timeout_function=self.on_timeout) self.extra_buttons = [] def refresh_button_state(self): app = self.ctx.app bypass = self.ctx.current_bypass extra_buttons = [] if bypass.get("guide") is not None: extra_buttons.append( discord.ui.Button(label="View Guide", style=discord.ButtonStyle.link, url=bypass.get("guide")) ) if bypass.get("repository") is not None: extra_buttons.append( discord.ui.Button(label="View Repository", style=discord.ButtonStyle.link, url=bypass.get("repository").get("uri")) ) if app.get("uri") is not None: extra_buttons.append( discord.ui.Button(label="View in App Store", emoji="<:appstore:392027597648822281>", style=discord.ButtonStyle.link, url=app.get("uri")) ) for button in self.extra_buttons: self.remove_item(button) for button in extra_buttons: self.add_item(button) self.extra_buttons = extra_buttons super().refresh_button_state() async def on_timeout(self): self.stopped = True await self.refresh_response_message() self.stop() class JumpButton(discord.ui.Button): def __init__(self, bot, max_page: int, tmb): super().__init__(style=discord.ButtonStyle.primary, emoji="⤴️") self.max_page = max_page self.bot = bot self.tmb = tmb self.row = 2 async def callback(self, interaction: discord.Interaction): if interaction.user != self.tmb.ctx.author: return ctx = await self.bot.get_application_context(interaction, cls=BlooContext) await interaction.response.defer(ephemeral=True) prompt = PromptData( value_name="page", description="What page do you want to jump to?", timeout=10, convertor=None) res = await ctx.prompt(prompt) if res is None: await ctx.send_warning("Cancelled") return try: res = int(res) except ValueError: await ctx.send_warning("Invalid page number!") return if res < 0 or res > self.max_page: await ctx.send_warning("Invalid page number!") return self.tmb.current_page = res await self.tmb.refresh_response_message() await ctx.send_success(f"Jumped to page {res}!") @cached(ttl=3600) async def get_jailbreaks_jba(): """Gets all apps on Jailbreaks.app Returns ------- dict "Apps" """ res_apps = [] async with aiohttp.ClientSession() as session: async with session.get("https://jailbreaks.app/json/apps.json") as resp: if resp.status == 200: res_apps = await resp.json() return res_apps @cached(ttl=1800) async def get_signed_status(): """Gets Jailbreaks.app's signed status""" signed = [] async with aiohttp.ClientSession() as session: async with session.get("https://jailbreaks.app/status.php") as resp: if resp.status == 200: res = await resp.text() signed = json.loads(res) return signed async def iterate_apps(query) -> dict: """Iterates through Jailbreaks.app apps, looking for a matching query Parameters ---------- query : str "App to look for" Returns ------- dict "List of apps that match the query" """ apps = await get_jailbreaks_jba() for possibleApp in apps: if possibleApp.get('name').lower() == query.lower().replace("œ", "oe"): return possibleApp class CIJMenu(Menu): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.extra_buttons = [] def refresh_button_state(self): extra_buttons = [] if self.ctx.jb_info.get("website") is not None: extra_buttons.append(discord.ui.Button(label='Website', url=self.ctx.jb_info.get( "website").get("url"), style=discord.ButtonStyle.url, row=1)) if self.ctx.jb_info.get('guide'): added = False for guide in self.ctx.jb_info.get('guide')[1:]: if self.ctx.build in guide.get("firmwares") and self.ctx.device_id in guide.get("devices"): extra_buttons.append(discord.ui.Button( label=f'{guide.get('name')} Guide', url=f"https://ios.cfw.guide{guide.get('url')}", style=discord.ButtonStyle.url, row=1)) added = True break if not added: guide = self.ctx.jb_info.get('guide')[0] extra_buttons.append(discord.ui.Button( label=f'{guide.get('name')} Guide', url=f"https://ios.cfw.guide{guide.get('url')}", style=discord.ButtonStyle.url, row=1)) if self.ctx.jb_info.get("jailbreaksmeapp") is not None: if self.ctx.jba is None or self.ctx.signed.get('status') != 'Signed': extra_buttons.append(discord.ui.Button(label='Install with Jailbreaks.app', url=f"https://api.jailbreaks.app/", style=discord.ButtonStyle.url, disabled=True, row=1)) else: extra_buttons.append(discord.ui.Button(label='Install with Jailbreaks.app', url=f"https://api.jailbreaks.app/install/{self.ctx.jba.get("name").replace(" ", "")}", style=discord.ButtonStyle.url, row=1)) for button in self.extra_buttons: self.remove_item(button) for button in extra_buttons: self.add_item(button) self.extra_buttons = extra_buttons super().refresh_button_state()
import json import aiohttp import discord from aiocache.decorators import cached from utils.context import BlooContext, PromptData from utils.permissions.permissions import permissions from utils.views.menu import Menu class TweakMenu(Menu): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs, timeout_function=self.on_timeout) self.jump_button = JumpButton(self.ctx.bot, len(self.pages), self) self.extra_buttons = [] def refresh_button_state(self): if self.ctx.repo: extra_buttons = [ discord.ui.Button(label='Add Repo to Sileo', emoji="<:sileo:679466569407004684>", url=f'https://sharerepo.stkc.win/v2/?pkgman=sileo&repo={self.ctx.repo}', style=discord.ButtonStyle.url, row=1), discord.ui.Button(label='Add Repo to Zebra', emoji="<:zebra:911433583032422420>", url=f'https://sharerepo.stkc.win/v2/?pkgman=zebra&repo={self.ctx.repo}', style=discord.ButtonStyle.url, row=1), discord.ui.Button(label='Other Package Managers', emoji="<:cydiasileosplit:932650041099825232>", url=f'https://sharerepo.stkc.win/?repo={self.ctx.repo}', style=discord.ButtonStyle.url, row=1) ] else: extra_buttons = [ discord.ui.Button(label='Cannot add default repo', emoji="<:sileo:679466569407004684>", url=f'https://sharerepo.stkc.win/v2/?pkgman=sileo&repo={self.ctx.repo}', disabled=True, style=discord.ButtonStyle.url, row=1), discord.ui.Button(label='Cannot add default repo', emoji="<:zebra:911433583032422420>", url=f'https://sharerepo.stkc.win/v2/?pkgman=zebra&repo={self.ctx.repo}', disabled=True, style=discord.ButtonStyle.url, row=1), discord.ui.Button(label='Cannot add default repo', emoji="<:Add:947354227171262534>", url=f'https://sharerepo.stkc.win/?repo={self.ctx.repo}', style=discord.ButtonStyle.url, disabled=True, row=1) ] if self.ctx.depiction: extra_buttons.insert(0, discord.ui.Button(label='View Depiction', emoji="<:Depiction:947358756033949786>", url=self.ctx.depiction, style=discord.ButtonStyle.url, row=1), ) if len(self.pages) > 1: extra_buttons.append(self.jump_button) for button in self.extra_buttons: self.remove_item(button) for button in extra_buttons: self.add_item(button) self.extra_buttons = extra_buttons super().refresh_button_state() async def on_timeout(self): self.jump_button.disabled = True self.stopped = True await self.refresh_response_message() self.stop() def on_interaction_check(self, interaction: discord.Interaction): return interaction.user == self.ctx.author or permissions.has(interaction.guild, interaction.user, 4) class BypassMenu(Menu): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs, timeout_function=self.on_timeout) self.extra_buttons = [] def refresh_button_state(self): app = self.ctx.app bypass = self.ctx.current_bypass extra_buttons = [] if bypass.get("guide") is not None: extra_buttons.append( discord.ui.Button(label="View Guide", style=discord.ButtonStyle.link, url=bypass.get("guide")) ) if bypass.get("repository") is not None: extra_buttons.append( discord.ui.Button(label="View Repository", style=discord.ButtonStyle.link, url=bypass.get("repository").get("uri")) ) if app.get("uri") is not None: extra_buttons.append( discord.ui.Button(label="View in App Store", emoji="<:appstore:392027597648822281>", style=discord.ButtonStyle.link, url=app.get("uri")) ) for button in self.extra_buttons: self.remove_item(button) for button in extra_buttons: self.add_item(button) self.extra_buttons = extra_buttons super().refresh_button_state() async def on_timeout(self): self.stopped = True await self.refresh_response_message() self.stop() class JumpButton(discord.ui.Button): def __init__(self, bot, max_page: int, tmb): super().__init__(style=discord.ButtonStyle.primary, emoji="⤴️") self.max_page = max_page self.bot = bot self.tmb = tmb self.row = 2 async def callback(self, interaction: discord.Interaction): if interaction.user != self.tmb.ctx.author: return ctx = await self.bot.get_application_context(interaction, cls=BlooContext) await interaction.response.defer(ephemeral=True) prompt = PromptData( value_name="page", description="What page do you want to jump to?", timeout=10, convertor=None) res = await ctx.prompt(prompt) if res is None: await ctx.send_warning("Cancelled") return try: res = int(res) except ValueError: await ctx.send_warning("Invalid page number!") return if res < 0 or res > self.max_page: await ctx.send_warning("Invalid page number!") return self.tmb.current_page = res await self.tmb.refresh_response_message() await ctx.send_success(f"Jumped to page {res}!") @cached(ttl=3600) async def get_jailbreaks_jba(): """Gets all apps on Jailbreaks.app Returns ------- dict "Apps" """ res_apps = [] async with aiohttp.ClientSession() as session: async with session.get("https://jailbreaks.app/json/apps.json") as resp: if resp.status == 200: res_apps = await resp.json() return res_apps @cached(ttl=1800) async def get_signed_status(): """Gets Jailbreaks.app's signed status""" signed = [] async with aiohttp.ClientSession() as session: async with session.get("https://jailbreaks.app/status.php") as resp: if resp.status == 200: res = await resp.text() signed = json.loads(res) return signed async def iterate_apps(query) -> dict: """Iterates through Jailbreaks.app apps, looking for a matching query Parameters ---------- query : str "App to look for" Returns ------- dict "List of apps that match the query" """ apps = await get_jailbreaks_jba() for possibleApp in apps: if possibleApp.get('name').lower() == query.lower().replace("œ", "oe"): return possibleApp class CIJMenu(Menu): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.extra_buttons = [] def refresh_button_state(self): extra_buttons = [] if self.ctx.jb_info.get("website") is not None: extra_buttons.append(discord.ui.Button(label='Website', url=self.ctx.jb_info.get( "website").get("url"), style=discord.ButtonStyle.url, row=1)) if self.ctx.jb_info.get('guide'): added = False for guide in self.ctx.jb_info.get('guide')[1:]: if self.ctx.build in guide.get("firmwares") and self.ctx.device_id in guide.get("devices"): extra_buttons.append(discord.ui.Button( label=f'{guide.get("name")} Guide', url=f"https://ios.cfw.guide{guide.get('url')}", style=discord.ButtonStyle.url, row=1)) added = True break if not added: guide = self.ctx.jb_info.get('guide')[0] extra_buttons.append(discord.ui.Button( label=f'{guide.get("name")} Guide', url=f"https://ios.cfw.guide{guide.get('url')}", style=discord.ButtonStyle.url, row=1)) if self.ctx.jb_info.get("jailbreaksmeapp") is not None: if self.ctx.jba is None or self.ctx.signed.get('status') != 'Signed': extra_buttons.append(discord.ui.Button(label='Install with Jailbreaks.app', url=f"https://api.jailbreaks.app/", style=discord.ButtonStyle.url, disabled=True, row=1)) else: extra_buttons.append(discord.ui.Button(label='Install with Jailbreaks.app', url=f"https://api.jailbreaks.app/install/{self.ctx.jba.get('name').replace(' ', '')}", style=discord.ButtonStyle.url, row=1)) for button in self.extra_buttons: self.remove_item(button) for button in extra_buttons: self.add_item(button) self.extra_buttons = extra_buttons super().refresh_button_state()
#!/usr/bin/env python3 # Need to run this from the directory containing this script and make_rules.py # Run this script, then check output in the generated file, then run make_rules.py import argparse import json import requests import sys import os import boto3 from slugify import slugify import common.common_lib as common_lib DEV = "dev" QA = "qa" PROD = "prod" DEV_CURATOR_URL = "https://dev-data.covid-19.global.health/api/sources" QA_CURATOR_URL = "https://qa-data.covid-19.global.health/api/sources" PROD_CURATOR_URL = "https://data.covid-19.global.health/api/sources" ENV_TO_URL = { DEV: DEV_CURATOR_URL, QA: QA_CURATOR_URL, PROD:PROD_CURATOR_URL } AWS_REGION = os.getenv("AWS_REGION", "eu-central-1") LIMIT = 100 # when we go over 100 sources we will need to update the maximum limit in the curator API SOURCE_RULE = { "rule_name": "", "target_name": "", "source_name": "", "job_name": "", "description": "" } FILE_NAME = "rules.json" JOB_DEF_ENV = "EPID_INGESTION_ENV" JOB_DEF_SOURCE_ID = "EPID_INGESTION_SOURCE_ID" parser = argparse.ArgumentParser( description="Define rules for AWS EventBridge by curator sources", usage="python define_rules.py [<environment>]" ) parser.add_argument( "environment", help="Which environment to list sources from", choices=[DEV, PROD] ) args = parser.parse_args(sys.argv[1:2]) s3_client = boto3.client("s3", AWS_REGION) auth_headers = common_lib.obtain_api_credentials(s3_client) env = args.environment url = f"{ENV_TO_URL.get(env, "")}?limit={LIMIT}" print(f"Getting source information from {env} curator API") response = requests.get(url, headers=auth_headers) if response.status_code != 200: print(f"Non-200 response from curator API: {response.status_code}") sys.exit(1) sources = response.json().get("sources") batch_client = boto3.client("batch", AWS_REGION) resp = batch_client.describe_job_definitions() job_definitions = resp.get("jobDefinitions") if not job_definitions: print(f"No job definitions found in response from Batch: {resp}") sys.exit(1) source_id_to_job_def_name = {} for job_def in job_definitions: props = job_def.get("containerProperties", {}) job_def_env = props.get("environment", {}) for kv in job_def_env: print(f"key-val: {kv}") if kv.get("name", "") == JOB_DEF_SOURCE_ID: val = kv.get("value") if not val: continue source_id_to_job_def_name[val] = job_def.get("jobDefinitionName") break rules = [] for source in sources: source_name = source.get("name") source_id = source.get("_id") source_rule = SOURCE_RULE.copy() job_def_name = source_id_to_job_def_name.get(source_id) if not job_def_name: print(f"No job definition found using source ID {source_id}") continue source_rule["rule_name"] = f"{job_def_name}" source_rule["target_name"] = job_def_name source_rule["source_name"] = source_name source_rule["job_name"] = job_def_name source_rule["description"] = f"Scheduled Batch ingestion rule for source: {source_name} with ID: {source_id} for environment: {env}" rules.append(source_rule) print(f"Writing source information to {FILE_NAME}") with open(FILE_NAME, "w") as f: json.dump(rules, f, indent=4) print("Done")
#!/usr/bin/env python3 # Need to run this from the directory containing this script and make_rules.py # Run this script, then check output in the generated file, then run make_rules.py import argparse import json import requests import sys import os import boto3 from slugify import slugify import common.common_lib as common_lib DEV = "dev" QA = "qa" PROD = "prod" DEV_CURATOR_URL = "https://dev-data.covid-19.global.health/api/sources" QA_CURATOR_URL = "https://qa-data.covid-19.global.health/api/sources" PROD_CURATOR_URL = "https://data.covid-19.global.health/api/sources" ENV_TO_URL = { DEV: DEV_CURATOR_URL, QA: QA_CURATOR_URL, PROD:PROD_CURATOR_URL } AWS_REGION = os.getenv("AWS_REGION", "eu-central-1") LIMIT = 100 # when we go over 100 sources we will need to update the maximum limit in the curator API SOURCE_RULE = { "rule_name": "", "target_name": "", "source_name": "", "job_name": "", "description": "" } FILE_NAME = "rules.json" JOB_DEF_ENV = "EPID_INGESTION_ENV" JOB_DEF_SOURCE_ID = "EPID_INGESTION_SOURCE_ID" parser = argparse.ArgumentParser( description="Define rules for AWS EventBridge by curator sources", usage="python define_rules.py [<environment>]" ) parser.add_argument( "environment", help="Which environment to list sources from", choices=[DEV, PROD] ) args = parser.parse_args(sys.argv[1:2]) s3_client = boto3.client("s3", AWS_REGION) auth_headers = common_lib.obtain_api_credentials(s3_client) env = args.environment url = f"{ENV_TO_URL.get(env, '')}?limit={LIMIT}" print(f"Getting source information from {env} curator API") response = requests.get(url, headers=auth_headers) if response.status_code != 200: print(f"Non-200 response from curator API: {response.status_code}") sys.exit(1) sources = response.json().get("sources") batch_client = boto3.client("batch", AWS_REGION) resp = batch_client.describe_job_definitions() job_definitions = resp.get("jobDefinitions") if not job_definitions: print(f"No job definitions found in response from Batch: {resp}") sys.exit(1) source_id_to_job_def_name = {} for job_def in job_definitions: props = job_def.get("containerProperties", {}) job_def_env = props.get("environment", {}) for kv in job_def_env: print(f"key-val: {kv}") if kv.get("name", "") == JOB_DEF_SOURCE_ID: val = kv.get("value") if not val: continue source_id_to_job_def_name[val] = job_def.get("jobDefinitionName") break rules = [] for source in sources: source_name = source.get("name") source_id = source.get("_id") source_rule = SOURCE_RULE.copy() job_def_name = source_id_to_job_def_name.get(source_id) if not job_def_name: print(f"No job definition found using source ID {source_id}") continue source_rule["rule_name"] = f"{job_def_name}" source_rule["target_name"] = job_def_name source_rule["source_name"] = source_name source_rule["job_name"] = job_def_name source_rule["description"] = f"Scheduled Batch ingestion rule for source: {source_name} with ID: {source_id} for environment: {env}" rules.append(source_rule) print(f"Writing source information to {FILE_NAME}") with open(FILE_NAME, "w") as f: json.dump(rules, f, indent=4) print("Done")
#!/usr/bin/env python3 # This file is a part of toml++ and is subject to the the terms of the MIT license. # Copyright (c) Mark Gillard <mark.gillard@outlook.com.au> # See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text. # SPDX-License-Identifier: MIT import sys import utils import io import re import json import yaml import math import dateutil.parser from pathlib import Path from datetime import datetime, date, time def sanitize(s): s = re.sub(r'[ _:;\/-]+', '_', s, 0, re.I | re.M) if s in ('bool', 'float', 'int', 'double', 'auto'): s = s + '_' return s def python_value_to_tomlpp(val): if isinstance(val, str): if re.fullmatch(r'^[+-]?[0-9]+[eE][+-]?[0-9]+$', val, re.M): return str(float(val)) else: return 'R"({})"sv'.format(val) elif isinstance(val, bool): return 'true' if val else 'false' elif isinstance(val, float): if math.isinf(val): return f'{'-' if val < 0.0 else ''}std::numeric_limits<double>::infinity()' elif math.isnan(val): return 'std::numeric_limits<double>::quiet_NaN()' else: return str(val) elif isinstance(val, int): if val == 9223372036854775807: return 'INT64_MAX' elif val == -9223372036854775808: return 'INT64_MIN' else: return str(val) elif isinstance(val, (TomlPPArray, TomlPPTable)): return str(val) elif isinstance(val, datetime): offset = None if val.tzinfo is not None: offset = val.tzinfo.utcoffset(val) mins = offset.total_seconds() / 60 offset = (int(mins / 60), int(mins % 60)) return 'toml::date_time{{ {{ {}, {}, {} }}, {{ {}, {}, {}, {}u }}{} }}'.format( val.year, val.month, val.day, val.hour, val.minute, val.second, val.microsecond*1000, '' if offset is None else ', {{ {}, {} }}'.format(offset[0], offset[1]) ) elif isinstance(val, date): return 'toml::date{{ {}, {}, {} }}'.format( val.year, val.month, val.day ) elif isinstance(val, time): return 'toml::time{{ {}, {}, {}, {} }}'.format( val.hour, val.minute, val.second, val.microsecond*1000 ) else: raise ValueError(str(type(val))) class TomlPPArray: def __init__(self, init_data=None): self.values = init_data if init_data else list() def render(self, indent = '', indent_declaration = False): s = '' if indent_declaration: s += indent if len(self.values) == 0: s += 'toml::array{}' else: s += 'toml::array{' for val in self.values: s += '\n' + indent + '\t' if isinstance(val, TomlPPArray) and len(self.values) == 1: s += 'toml::inserter{' if isinstance(val, (TomlPPTable, TomlPPArray)) and len(val) > 0: s += val.render(indent + '\t') else: s += python_value_to_tomlpp(val) if isinstance(val, TomlPPArray) and len(self.values) == 1: s += '}' s += ',' s += '\n' + indent + '}' return s def __str__(self): return self.render() def __len__(self): return len(self.values) class TomlPPTable: def __init__(self, init_data=None): self.values = init_data if init_data else dict() def render(self, indent = '', indent_declaration = False): s = '' if indent_declaration: s += indent if len(self.values) == 0: s += 'toml::table{}' else: s += 'toml::table{{' for key, val in self.values.items(): s += '\n' + indent + '\t{ ' if isinstance(val, (TomlPPTable, TomlPPArray)) and len(val) > 0: s += '\n' + indent + '\t\t{},'.format(python_value_to_tomlpp(str(key))) #s += '\n' + val.render(indent + '\t\t') s += ' ' + val.render(indent + '\t\t') s += '\n' + indent + '\t' else: s += '{}, {} '.format(python_value_to_tomlpp(str(key)), python_value_to_tomlpp(val)) s += '},' #else: #s += '}\n' s += '\n' + indent + '}}' return s def __str__(self): return self.render() def __len__(self): return len(self.values) def json_to_python(val): if isinstance(val, dict): if len(val) == 2 and "type" in val and "value" in val: val_type = val["type"] if val_type == "integer": return int(val["value"]) elif val_type == "float": return float(val["value"]) elif val_type == "string": return str(val["value"]) elif val_type == "bool": return True if val["value"].lower() == "true" else False elif val_type == "array": return json_to_python(val["value"]) elif val_type in ("datetime", "date", "time", "datetime-local"): dt_val = dateutil.parser.parse(val["value"]) if val_type == "date": return dt_val.date() elif val_type == "time": return dt_val.time() else: return dt_val else: raise ValueError(val_type) else: vals = dict() for k,v in val.items(): vals[k] = json_to_python(v) return vals elif isinstance(val, list): vals = list() for v in val: vals.append(json_to_python(v)) return vals else: raise ValueError(str(type(val))) def python_to_tomlpp(node): if isinstance(node, dict): table = TomlPPTable() for key, val in node.items(): table.values[key] = python_to_tomlpp(val) return table elif isinstance(node, (set, list, tuple)): array = TomlPPArray() for val in node: array.values.append(python_to_tomlpp(val)) return array else: return node class TomlTest: def __init__(self, file_path, is_valid_case): self.__name = file_path.stem self.__identifier = sanitize(self.__name) self.__data = utils.read_all_text_from_file(file_path, logger=True).strip() self.condition = '' self.requires_unicode = False if is_valid_case: self.__expected = True path_base = str(Path(file_path.parent, file_path.stem)) yaml_file = Path(path_base + r'.yaml') if yaml_file.exists(): self.__expected = python_to_tomlpp(yaml.load( utils.read_all_text_from_file(yaml_file, logger=True), Loader=yaml.FullLoader )) else: json_file = Path(path_base + r'.json') if json_file.exists(): self.__expected = python_to_tomlpp(json_to_python(json.loads( utils.read_all_text_from_file(json_file, logger=True), ))) else: self.__expected = False def name(self): return self.__name def identifier(self): return self.__identifier def data(self): return self.__data def expected(self): return self.__expected def __str__(self): return 'static constexpr auto {} = R"({})"sv;'.format( self.__identifier, self.__data, ) def load_tests(source_folder, is_valid_set, ignore_list): source_folder = source_folder.resolve() utils.assert_existing_directory(source_folder) files = utils.get_all_files(source_folder, all="*.toml") if ignore_list: files = [f for f in files if f.stem not in ignore_list] return [TomlTest(f, is_valid_set) for f in files] def set_condition(tests, condition, names): for test in tests: if test.name() in names: test.condition = condition def load_valid_inputs(tests, extern_root): tests['valid']['burntsushi'] = load_tests(Path(extern_root, 'toml-test', 'tests', 'valid'), True, ( # newline/escape handling tests. these get broken by I/O (I test them separately) 'string-escapes', # bugged: https://github.com/BurntSushi/toml-test/issues/58 'datetime' )) tests['valid']['iarna'] = load_tests(Path(extern_root, 'toml-spec-tests', 'values'), True, ( # these are stress-tests for 'large' datasets. I test these separately. Having them inline in C++ code is insane. 'qa-array-inline-1000', 'qa-array-inline-nested-1000', 'qa-key-literal-40kb', 'qa-key-string-40kb', 'qa-scalar-literal-40kb', 'qa-scalar-literal-multiline-40kb', 'qa-scalar-string-40kb', 'qa-scalar-string-multiline-40kb', 'qa-table-inline-1000', 'qa-table-inline-nested-1000', # newline/escape handling tests. these get broken by I/O (I test them separately) 'spec-newline-1', 'spec-newline-2', 'spec-newline-3', 'spec-string-escape-1', 'spec-string-escape-2', 'spec-string-escape-3', 'spec-string-escape-4', 'spec-string-escape-5', 'spec-string-escape-6', 'spec-string-escape-7', 'spec-string-escape-8', 'spec-string-escape-9', # bugged: https://github.com/iarna/toml-spec-tests/issues/3 'spec-date-time-6', 'spec-date-time-local-2', 'spec-time-2', # breaks gcc: 'spec-string-basic-multiline-4', )) def load_invalid_inputs(tests, extern_root): tests['invalid']['burntsushi'] = load_tests(Path(extern_root, 'toml-test', 'tests', 'invalid'), False, ( # false negatives after TOML 0.4.0 'array-mixed-types-arrays-and-ints', 'array-mixed-types-ints-and-floats', 'array-mixed-types-strings-and-ints' )) set_condition(tests['invalid']['burntsushi'], '!TOML_LANG_UNRELEASED', ( 'datetime-malformed-no-secs', 'inline-table-linebreak', 'multi-line-inline-table', 'string-byte-escapes' )) tests['invalid']['iarna'] = load_tests(Path(extern_root, 'toml-spec-tests', 'errors'), False, ( # I test these explicitly in the other test files (they get broken by I/O) 'comment-control-1', 'comment-control-2', 'comment-control-3', 'comment-control-4', 'string-basic-control-1', 'string-basic-control-2', 'string-basic-control-3', 'string-basic-control-4', 'string-basic-multiline-control-1', 'string-basic-multiline-control-2', 'string-basic-multiline-control-3', 'string-basic-multiline-control-4', 'string-literal-control-1', 'string-literal-control-2', 'string-literal-control-3', 'string-literal-control-4', 'string-literal-multiline-control-1', 'string-literal-multiline-control-2', 'string-literal-multiline-control-3', 'string-literal-multiline-control-4' )) set_condition(tests['invalid']['iarna'], '!TOML_LANG_UNRELEASED', ( 'inline-table-trailing-comma', )) def requires_unicode(s): for c in s: if ord(c) > 127: return True return False def write_test_file(name, test_cases): conditions = set() for test in test_cases: conditions.add(test.condition) test_file_path = Path(utils.entry_script_dir(), '..', 'tests', rf'conformance_{sanitize(name.strip())}.cpp').resolve() print(rf'Writing to {test_file_path}') with open(test_file_path, 'w', encoding='utf-8', newline='\n') as test_file: write = lambda txt: print(txt, file=test_file) # preamble write('// This file is a part of toml++ and is subject to the the terms of the MIT license.') write('// Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>') write('// See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.') write('// SPDX-License-Identifier: MIT') write('//-----') write('// this file was generated by generate_conformance_tests.py - do not modify it directly') write('') write('#include "tests.h"') write('using namespace toml::impl;') write('') # test data write('TOML_DISABLE_WARNINGS; // unused variable spam') write('') write('namespace') write('{') for test in test_cases: s = f'\t{test}' test.requires_unicode = requires_unicode(s) if test.requires_unicode: write('\t#if UNICODE_LITERALS_OK') write(s) write('\t#endif // UNICODE_LITERALS_OK') else: write(s) write('}') write('') write('TOML_ENABLE_WARNINGS;') write('') # tests write(f'TEST_CASE("conformance - {name}")') write('{') for condition in conditions: if condition != '': write('') write(f'\t#if {condition}'); for test in test_cases: if test.condition != condition: continue expected = test.expected() if isinstance(expected, bool): if expected: write(f'\tparsing_should_succeed(FILE_LINE_ARGS, {test.identifier()});') else: write(f'\tparsing_should_fail(FILE_LINE_ARGS, {test.identifier()});') else: s = expected.render('\t\t') if not test.requires_unicode: test.requires_unicode = requires_unicode(s) if test.requires_unicode: write('\t#if UNICODE_LITERALS_OK') write(f'\tparsing_should_succeed(FILE_LINE_ARGS, {test.identifier()}, [](toml::table&& tbl)') write('\t{') write(f'\t\tauto expected = {s};') write('\t\tREQUIRE(tbl == expected);') write('\t});') if test.requires_unicode: write('\t#endif // UNICODE_LITERALS_OK') write('') if condition != '': write(f'\t#endif // {condition}'); write('}') write('') def main(): extern_root = Path(utils.entry_script_dir(), '..', 'external').resolve() utils.assert_existing_directory(extern_root) assert extern_root.exists() tests = { 'valid': dict(), 'invalid': dict() } load_valid_inputs(tests, extern_root) load_invalid_inputs(tests, extern_root) for test_type, test_groups in tests.items(): for test_group, test_cases in test_groups.items(): write_test_file('{}/{}'.format(test_group, test_type), test_cases ) if __name__ == '__main__': utils.run(main, verbose=True)
#!/usr/bin/env python3 # This file is a part of toml++ and is subject to the the terms of the MIT license. # Copyright (c) Mark Gillard <mark.gillard@outlook.com.au> # See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text. # SPDX-License-Identifier: MIT import sys import utils import io import re import json import yaml import math import dateutil.parser from pathlib import Path from datetime import datetime, date, time def sanitize(s): s = re.sub(r'[ _:;\/-]+', '_', s, 0, re.I | re.M) if s in ('bool', 'float', 'int', 'double', 'auto'): s = s + '_' return s def python_value_to_tomlpp(val): if isinstance(val, str): if re.fullmatch(r'^[+-]?[0-9]+[eE][+-]?[0-9]+$', val, re.M): return str(float(val)) else: return 'R"({})"sv'.format(val) elif isinstance(val, bool): return 'true' if val else 'false' elif isinstance(val, float): if math.isinf(val): return f'{"-" if val < 0.0 else ""}std::numeric_limits<double>::infinity()' elif math.isnan(val): return 'std::numeric_limits<double>::quiet_NaN()' else: return str(val) elif isinstance(val, int): if val == 9223372036854775807: return 'INT64_MAX' elif val == -9223372036854775808: return 'INT64_MIN' else: return str(val) elif isinstance(val, (TomlPPArray, TomlPPTable)): return str(val) elif isinstance(val, datetime): offset = None if val.tzinfo is not None: offset = val.tzinfo.utcoffset(val) mins = offset.total_seconds() / 60 offset = (int(mins / 60), int(mins % 60)) return 'toml::date_time{{ {{ {}, {}, {} }}, {{ {}, {}, {}, {}u }}{} }}'.format( val.year, val.month, val.day, val.hour, val.minute, val.second, val.microsecond*1000, '' if offset is None else ', {{ {}, {} }}'.format(offset[0], offset[1]) ) elif isinstance(val, date): return 'toml::date{{ {}, {}, {} }}'.format( val.year, val.month, val.day ) elif isinstance(val, time): return 'toml::time{{ {}, {}, {}, {} }}'.format( val.hour, val.minute, val.second, val.microsecond*1000 ) else: raise ValueError(str(type(val))) class TomlPPArray: def __init__(self, init_data=None): self.values = init_data if init_data else list() def render(self, indent = '', indent_declaration = False): s = '' if indent_declaration: s += indent if len(self.values) == 0: s += 'toml::array{}' else: s += 'toml::array{' for val in self.values: s += '\n' + indent + '\t' if isinstance(val, TomlPPArray) and len(self.values) == 1: s += 'toml::inserter{' if isinstance(val, (TomlPPTable, TomlPPArray)) and len(val) > 0: s += val.render(indent + '\t') else: s += python_value_to_tomlpp(val) if isinstance(val, TomlPPArray) and len(self.values) == 1: s += '}' s += ',' s += '\n' + indent + '}' return s def __str__(self): return self.render() def __len__(self): return len(self.values) class TomlPPTable: def __init__(self, init_data=None): self.values = init_data if init_data else dict() def render(self, indent = '', indent_declaration = False): s = '' if indent_declaration: s += indent if len(self.values) == 0: s += 'toml::table{}' else: s += 'toml::table{{' for key, val in self.values.items(): s += '\n' + indent + '\t{ ' if isinstance(val, (TomlPPTable, TomlPPArray)) and len(val) > 0: s += '\n' + indent + '\t\t{},'.format(python_value_to_tomlpp(str(key))) #s += '\n' + val.render(indent + '\t\t') s += ' ' + val.render(indent + '\t\t') s += '\n' + indent + '\t' else: s += '{}, {} '.format(python_value_to_tomlpp(str(key)), python_value_to_tomlpp(val)) s += '},' #else: #s += '}\n' s += '\n' + indent + '}}' return s def __str__(self): return self.render() def __len__(self): return len(self.values) def json_to_python(val): if isinstance(val, dict): if len(val) == 2 and "type" in val and "value" in val: val_type = val["type"] if val_type == "integer": return int(val["value"]) elif val_type == "float": return float(val["value"]) elif val_type == "string": return str(val["value"]) elif val_type == "bool": return True if val["value"].lower() == "true" else False elif val_type == "array": return json_to_python(val["value"]) elif val_type in ("datetime", "date", "time", "datetime-local"): dt_val = dateutil.parser.parse(val["value"]) if val_type == "date": return dt_val.date() elif val_type == "time": return dt_val.time() else: return dt_val else: raise ValueError(val_type) else: vals = dict() for k,v in val.items(): vals[k] = json_to_python(v) return vals elif isinstance(val, list): vals = list() for v in val: vals.append(json_to_python(v)) return vals else: raise ValueError(str(type(val))) def python_to_tomlpp(node): if isinstance(node, dict): table = TomlPPTable() for key, val in node.items(): table.values[key] = python_to_tomlpp(val) return table elif isinstance(node, (set, list, tuple)): array = TomlPPArray() for val in node: array.values.append(python_to_tomlpp(val)) return array else: return node class TomlTest: def __init__(self, file_path, is_valid_case): self.__name = file_path.stem self.__identifier = sanitize(self.__name) self.__data = utils.read_all_text_from_file(file_path, logger=True).strip() self.condition = '' self.requires_unicode = False if is_valid_case: self.__expected = True path_base = str(Path(file_path.parent, file_path.stem)) yaml_file = Path(path_base + r'.yaml') if yaml_file.exists(): self.__expected = python_to_tomlpp(yaml.load( utils.read_all_text_from_file(yaml_file, logger=True), Loader=yaml.FullLoader )) else: json_file = Path(path_base + r'.json') if json_file.exists(): self.__expected = python_to_tomlpp(json_to_python(json.loads( utils.read_all_text_from_file(json_file, logger=True), ))) else: self.__expected = False def name(self): return self.__name def identifier(self): return self.__identifier def data(self): return self.__data def expected(self): return self.__expected def __str__(self): return 'static constexpr auto {} = R"({})"sv;'.format( self.__identifier, self.__data, ) def load_tests(source_folder, is_valid_set, ignore_list): source_folder = source_folder.resolve() utils.assert_existing_directory(source_folder) files = utils.get_all_files(source_folder, all="*.toml") if ignore_list: files = [f for f in files if f.stem not in ignore_list] return [TomlTest(f, is_valid_set) for f in files] def set_condition(tests, condition, names): for test in tests: if test.name() in names: test.condition = condition def load_valid_inputs(tests, extern_root): tests['valid']['burntsushi'] = load_tests(Path(extern_root, 'toml-test', 'tests', 'valid'), True, ( # newline/escape handling tests. these get broken by I/O (I test them separately) 'string-escapes', # bugged: https://github.com/BurntSushi/toml-test/issues/58 'datetime' )) tests['valid']['iarna'] = load_tests(Path(extern_root, 'toml-spec-tests', 'values'), True, ( # these are stress-tests for 'large' datasets. I test these separately. Having them inline in C++ code is insane. 'qa-array-inline-1000', 'qa-array-inline-nested-1000', 'qa-key-literal-40kb', 'qa-key-string-40kb', 'qa-scalar-literal-40kb', 'qa-scalar-literal-multiline-40kb', 'qa-scalar-string-40kb', 'qa-scalar-string-multiline-40kb', 'qa-table-inline-1000', 'qa-table-inline-nested-1000', # newline/escape handling tests. these get broken by I/O (I test them separately) 'spec-newline-1', 'spec-newline-2', 'spec-newline-3', 'spec-string-escape-1', 'spec-string-escape-2', 'spec-string-escape-3', 'spec-string-escape-4', 'spec-string-escape-5', 'spec-string-escape-6', 'spec-string-escape-7', 'spec-string-escape-8', 'spec-string-escape-9', # bugged: https://github.com/iarna/toml-spec-tests/issues/3 'spec-date-time-6', 'spec-date-time-local-2', 'spec-time-2', # breaks gcc: 'spec-string-basic-multiline-4', )) def load_invalid_inputs(tests, extern_root): tests['invalid']['burntsushi'] = load_tests(Path(extern_root, 'toml-test', 'tests', 'invalid'), False, ( # false negatives after TOML 0.4.0 'array-mixed-types-arrays-and-ints', 'array-mixed-types-ints-and-floats', 'array-mixed-types-strings-and-ints' )) set_condition(tests['invalid']['burntsushi'], '!TOML_LANG_UNRELEASED', ( 'datetime-malformed-no-secs', 'inline-table-linebreak', 'multi-line-inline-table', 'string-byte-escapes' )) tests['invalid']['iarna'] = load_tests(Path(extern_root, 'toml-spec-tests', 'errors'), False, ( # I test these explicitly in the other test files (they get broken by I/O) 'comment-control-1', 'comment-control-2', 'comment-control-3', 'comment-control-4', 'string-basic-control-1', 'string-basic-control-2', 'string-basic-control-3', 'string-basic-control-4', 'string-basic-multiline-control-1', 'string-basic-multiline-control-2', 'string-basic-multiline-control-3', 'string-basic-multiline-control-4', 'string-literal-control-1', 'string-literal-control-2', 'string-literal-control-3', 'string-literal-control-4', 'string-literal-multiline-control-1', 'string-literal-multiline-control-2', 'string-literal-multiline-control-3', 'string-literal-multiline-control-4' )) set_condition(tests['invalid']['iarna'], '!TOML_LANG_UNRELEASED', ( 'inline-table-trailing-comma', )) def requires_unicode(s): for c in s: if ord(c) > 127: return True return False def write_test_file(name, test_cases): conditions = set() for test in test_cases: conditions.add(test.condition) test_file_path = Path(utils.entry_script_dir(), '..', 'tests', rf'conformance_{sanitize(name.strip())}.cpp').resolve() print(rf'Writing to {test_file_path}') with open(test_file_path, 'w', encoding='utf-8', newline='\n') as test_file: write = lambda txt: print(txt, file=test_file) # preamble write('// This file is a part of toml++ and is subject to the the terms of the MIT license.') write('// Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>') write('// See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.') write('// SPDX-License-Identifier: MIT') write('//-----') write('// this file was generated by generate_conformance_tests.py - do not modify it directly') write('') write('#include "tests.h"') write('using namespace toml::impl;') write('') # test data write('TOML_DISABLE_WARNINGS; // unused variable spam') write('') write('namespace') write('{') for test in test_cases: s = f'\t{test}' test.requires_unicode = requires_unicode(s) if test.requires_unicode: write('\t#if UNICODE_LITERALS_OK') write(s) write('\t#endif // UNICODE_LITERALS_OK') else: write(s) write('}') write('') write('TOML_ENABLE_WARNINGS;') write('') # tests write(f'TEST_CASE("conformance - {name}")') write('{') for condition in conditions: if condition != '': write('') write(f'\t#if {condition}'); for test in test_cases: if test.condition != condition: continue expected = test.expected() if isinstance(expected, bool): if expected: write(f'\tparsing_should_succeed(FILE_LINE_ARGS, {test.identifier()});') else: write(f'\tparsing_should_fail(FILE_LINE_ARGS, {test.identifier()});') else: s = expected.render('\t\t') if not test.requires_unicode: test.requires_unicode = requires_unicode(s) if test.requires_unicode: write('\t#if UNICODE_LITERALS_OK') write(f'\tparsing_should_succeed(FILE_LINE_ARGS, {test.identifier()}, [](toml::table&& tbl)') write('\t{') write(f'\t\tauto expected = {s};') write('\t\tREQUIRE(tbl == expected);') write('\t});') if test.requires_unicode: write('\t#endif // UNICODE_LITERALS_OK') write('') if condition != '': write(f'\t#endif // {condition}'); write('}') write('') def main(): extern_root = Path(utils.entry_script_dir(), '..', 'external').resolve() utils.assert_existing_directory(extern_root) assert extern_root.exists() tests = { 'valid': dict(), 'invalid': dict() } load_valid_inputs(tests, extern_root) load_invalid_inputs(tests, extern_root) for test_type, test_groups in tests.items(): for test_group, test_cases in test_groups.items(): write_test_file('{}/{}'.format(test_group, test_type), test_cases ) if __name__ == '__main__': utils.run(main, verbose=True)
# -*- coding: utf-8 -*- from ThymeBoost.trend_models.trend_base_class import TrendBaseModel import numpy as np import pandas as pd class EwmModel(TrendBaseModel): model = 'ewm' def __init__(self): self.model_params = None self.fitted = None def __str__(self): return f'{self.model}({self.kwargs['ewm_alpha']})' def fit(self, y, **kwargs): """ Fit the trend component in the boosting loop for a ewm model using alpha. Parameters ---------- time_series : TYPE DESCRIPTION. **kwargs : TYPE DESCRIPTION. Returns ------- None. """ self.kwargs = kwargs alpha = kwargs['ewm_alpha'] bias = kwargs['bias'] y = pd.Series(y - bias) self.fitted = np.array(y.ewm(alpha=alpha).mean()) + bias last_fitted_values = self.fitted[-1] self.model_params = last_fitted_values return self.fitted def predict(self, forecast_horizon, model_params): return np.tile(model_params, forecast_horizon)
# -*- coding: utf-8 -*- from ThymeBoost.trend_models.trend_base_class import TrendBaseModel import numpy as np import pandas as pd class EwmModel(TrendBaseModel): model = 'ewm' def __init__(self): self.model_params = None self.fitted = None def __str__(self): return f'{self.model}({self.kwargs["ewm_alpha"]})' def fit(self, y, **kwargs): """ Fit the trend component in the boosting loop for a ewm model using alpha. Parameters ---------- time_series : TYPE DESCRIPTION. **kwargs : TYPE DESCRIPTION. Returns ------- None. """ self.kwargs = kwargs alpha = kwargs['ewm_alpha'] bias = kwargs['bias'] y = pd.Series(y - bias) self.fitted = np.array(y.ewm(alpha=alpha).mean()) + bias last_fitted_values = self.fitted[-1] self.model_params = last_fitted_values return self.fitted def predict(self, forecast_horizon, model_params): return np.tile(model_params, forecast_horizon)
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. import json import re from datetime import datetime from typing import Any, Dict, List, Optional, Pattern, Tuple, TYPE_CHECKING from urllib import parse from apispec import APISpec from apispec.ext.marshmallow import MarshmallowPlugin from flask_babel import gettext as __ from marshmallow import fields, Schema from sqlalchemy.engine.url import make_url, URL from typing_extensions import TypedDict from superset.db_engine_specs.postgres import PostgresBaseEngineSpec from superset.errors import ErrorLevel, SupersetError, SupersetErrorType from superset.models.sql_lab import Query from superset.utils import core as utils if TYPE_CHECKING: from superset.models.core import Database # Regular expressions to catch custom errors OBJECT_DOES_NOT_EXIST_REGEX = re.compile( r"Object (?P<object>.*?) does not exist or not authorized." ) SYNTAX_ERROR_REGEX = re.compile( "syntax error line (?P<line>.+?) at position (?P<position>.+?) " "unexpected '(?P<syntax_error>.+?)'." ) class SnowflakeParametersSchema(Schema): username = fields.Str(required=True) password = fields.Str(required=True) account = fields.Str(required=True) database = fields.Str(required=True) role = fields.Str(required=True) warehouse = fields.Str(required=True) class SnowflakeParametersType(TypedDict): username: str password: str account: str database: str role: str warehouse: str class SnowflakeEngineSpec(PostgresBaseEngineSpec): engine = "snowflake" engine_name = "Snowflake" force_column_alias_quotes = True max_column_name_length = 256 parameters_schema = SnowflakeParametersSchema() default_driver = "snowflake" sqlalchemy_uri_placeholder = "snowflake://" _time_grain_expressions = { None: "{col}", "PT1S": "DATE_TRUNC('SECOND', {col})", "PT1M": "DATE_TRUNC('MINUTE', {col})", "PT5M": "DATEADD(MINUTE, FLOOR(DATE_PART(MINUTE, {col}) / 5) * 5, \ DATE_TRUNC('HOUR', {col}))", "PT10M": "DATEADD(MINUTE, FLOOR(DATE_PART(MINUTE, {col}) / 10) * 10, \ DATE_TRUNC('HOUR', {col}))", "PT15M": "DATEADD(MINUTE, FLOOR(DATE_PART(MINUTE, {col}) / 15) * 15, \ DATE_TRUNC('HOUR', {col}))", "PT30M": "DATEADD(MINUTE, FLOOR(DATE_PART(MINUTE, {col}) / 30) * 30, \ DATE_TRUNC('HOUR', {col}))", "PT1H": "DATE_TRUNC('HOUR', {col})", "P1D": "DATE_TRUNC('DAY', {col})", "P1W": "DATE_TRUNC('WEEK', {col})", "P1M": "DATE_TRUNC('MONTH', {col})", "P3M": "DATE_TRUNC('QUARTER', {col})", "P1Y": "DATE_TRUNC('YEAR', {col})", } custom_errors: Dict[Pattern[str], Tuple[str, SupersetErrorType, Dict[str, Any]]] = { OBJECT_DOES_NOT_EXIST_REGEX: ( __("%(object)s does not exist in this database."), SupersetErrorType.OBJECT_DOES_NOT_EXIST_ERROR, {}, ), SYNTAX_ERROR_REGEX: ( __( "Please check your query for syntax errors at or " 'near "%(syntax_error)s". Then, try running your query again.' ), SupersetErrorType.SYNTAX_ERROR, {}, ), } @classmethod def adjust_database_uri( cls, uri: URL, selected_schema: Optional[str] = None ) -> None: database = uri.database if "/" in uri.database: database = uri.database.split("/")[0] if selected_schema: selected_schema = parse.quote(selected_schema, safe="") uri.database = database + "/" + selected_schema @classmethod def epoch_to_dttm(cls) -> str: return "DATEADD(S, {col}, '1970-01-01')" @classmethod def epoch_ms_to_dttm(cls) -> str: return "DATEADD(MS, {col}, '1970-01-01')" @classmethod def convert_dttm(cls, target_type: str, dttm: datetime) -> Optional[str]: tt = target_type.upper() if tt == utils.TemporalType.DATE: return f"TO_DATE('{dttm.date().isoformat()}')" if tt == utils.TemporalType.DATETIME: return f"""CAST('{dttm.isoformat(timespec="microseconds")}' AS DATETIME)""" if tt == utils.TemporalType.TIMESTAMP: return f"""TO_TIMESTAMP('{dttm.isoformat(timespec="microseconds")}')""" return None @staticmethod def mutate_db_for_connection_test(database: "Database") -> None: """ By default, snowflake doesn't validate if the user/role has access to the chosen database. :param database: instance to be mutated """ extra = json.loads(database.extra or "{}") engine_params = extra.get("engine_params", {}) connect_args = engine_params.get("connect_args", {}) connect_args["validate_default_parameters"] = True engine_params["connect_args"] = connect_args extra["engine_params"] = engine_params database.extra = json.dumps(extra) @classmethod def get_cancel_query_id(cls, cursor: Any, query: Query) -> Optional[str]: """ Get Snowflake session ID that will be used to cancel all other running queries in the same session. :param cursor: Cursor instance in which the query will be executed :param query: Query instance :return: Snowflake Session ID """ cursor.execute("SELECT CURRENT_SESSION()") row = cursor.fetchone() return row[0] @classmethod def cancel_query(cls, cursor: Any, query: Query, cancel_query_id: str) -> bool: """ Cancel query in the underlying database. :param cursor: New cursor instance to the db of the query :param query: Query instance :param cancel_query_id: Snowflake Session ID :return: True if query cancelled successfully, False otherwise """ try: cursor.execute(f"SELECT SYSTEM$CANCEL_ALL_QUERIES({cancel_query_id})") except Exception: # pylint: disable=broad-except return False return True @classmethod def build_sqlalchemy_uri( cls, parameters: SnowflakeParametersType, encrypted_extra: Optional[ # pylint: disable=unused-argument Dict[str, Any] ] = None, ) -> str: return str( URL( "snowflake", username=parameters.get("username"), password=parameters.get("password"), host=parameters.get("account"), database=parameters.get("database"), query={ "role": parameters.get("role"), "warehouse": parameters.get("warehouse"), }, ) ) @classmethod def get_parameters_from_uri( cls, uri: str, encrypted_extra: Optional[ # pylint: disable=unused-argument Dict[str, str] ] = None, ) -> Any: url = make_url(uri) query = dict(url.query.items()) return { "username": url.username, "password": url.password, "account": url.host, "database": url.database, "role": query.get("role"), "warehouse": query.get("warehouse"), } @classmethod def validate_parameters( cls, parameters: SnowflakeParametersType ) -> List[SupersetError]: errors: List[SupersetError] = [] required = { "warehouse", "username", "database", "account", "role", "password", } present = {key for key in parameters if parameters.get(key, ())} missing = sorted(required - present) if missing: errors.append( SupersetError( message=f'One or more parameters are missing: {', '.join(missing)}', error_type=SupersetErrorType.CONNECTION_MISSING_PARAMETERS_ERROR, level=ErrorLevel.WARNING, extra={"missing": missing}, ), ) return errors @classmethod def parameters_json_schema(cls) -> Any: """ Return configuration parameters as OpenAPI. """ if not cls.parameters_schema: return None ma_plugin = MarshmallowPlugin() spec = APISpec( title="Database Parameters", version="1.0.0", openapi_version="3.0.0", plugins=[ma_plugin], ) spec.components.schema(cls.__name__, schema=cls.parameters_schema) return spec.to_dict()["components"]["schemas"][cls.__name__]
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. import json import re from datetime import datetime from typing import Any, Dict, List, Optional, Pattern, Tuple, TYPE_CHECKING from urllib import parse from apispec import APISpec from apispec.ext.marshmallow import MarshmallowPlugin from flask_babel import gettext as __ from marshmallow import fields, Schema from sqlalchemy.engine.url import make_url, URL from typing_extensions import TypedDict from superset.db_engine_specs.postgres import PostgresBaseEngineSpec from superset.errors import ErrorLevel, SupersetError, SupersetErrorType from superset.models.sql_lab import Query from superset.utils import core as utils if TYPE_CHECKING: from superset.models.core import Database # Regular expressions to catch custom errors OBJECT_DOES_NOT_EXIST_REGEX = re.compile( r"Object (?P<object>.*?) does not exist or not authorized." ) SYNTAX_ERROR_REGEX = re.compile( "syntax error line (?P<line>.+?) at position (?P<position>.+?) " "unexpected '(?P<syntax_error>.+?)'." ) class SnowflakeParametersSchema(Schema): username = fields.Str(required=True) password = fields.Str(required=True) account = fields.Str(required=True) database = fields.Str(required=True) role = fields.Str(required=True) warehouse = fields.Str(required=True) class SnowflakeParametersType(TypedDict): username: str password: str account: str database: str role: str warehouse: str class SnowflakeEngineSpec(PostgresBaseEngineSpec): engine = "snowflake" engine_name = "Snowflake" force_column_alias_quotes = True max_column_name_length = 256 parameters_schema = SnowflakeParametersSchema() default_driver = "snowflake" sqlalchemy_uri_placeholder = "snowflake://" _time_grain_expressions = { None: "{col}", "PT1S": "DATE_TRUNC('SECOND', {col})", "PT1M": "DATE_TRUNC('MINUTE', {col})", "PT5M": "DATEADD(MINUTE, FLOOR(DATE_PART(MINUTE, {col}) / 5) * 5, \ DATE_TRUNC('HOUR', {col}))", "PT10M": "DATEADD(MINUTE, FLOOR(DATE_PART(MINUTE, {col}) / 10) * 10, \ DATE_TRUNC('HOUR', {col}))", "PT15M": "DATEADD(MINUTE, FLOOR(DATE_PART(MINUTE, {col}) / 15) * 15, \ DATE_TRUNC('HOUR', {col}))", "PT30M": "DATEADD(MINUTE, FLOOR(DATE_PART(MINUTE, {col}) / 30) * 30, \ DATE_TRUNC('HOUR', {col}))", "PT1H": "DATE_TRUNC('HOUR', {col})", "P1D": "DATE_TRUNC('DAY', {col})", "P1W": "DATE_TRUNC('WEEK', {col})", "P1M": "DATE_TRUNC('MONTH', {col})", "P3M": "DATE_TRUNC('QUARTER', {col})", "P1Y": "DATE_TRUNC('YEAR', {col})", } custom_errors: Dict[Pattern[str], Tuple[str, SupersetErrorType, Dict[str, Any]]] = { OBJECT_DOES_NOT_EXIST_REGEX: ( __("%(object)s does not exist in this database."), SupersetErrorType.OBJECT_DOES_NOT_EXIST_ERROR, {}, ), SYNTAX_ERROR_REGEX: ( __( "Please check your query for syntax errors at or " 'near "%(syntax_error)s". Then, try running your query again.' ), SupersetErrorType.SYNTAX_ERROR, {}, ), } @classmethod def adjust_database_uri( cls, uri: URL, selected_schema: Optional[str] = None ) -> None: database = uri.database if "/" in uri.database: database = uri.database.split("/")[0] if selected_schema: selected_schema = parse.quote(selected_schema, safe="") uri.database = database + "/" + selected_schema @classmethod def epoch_to_dttm(cls) -> str: return "DATEADD(S, {col}, '1970-01-01')" @classmethod def epoch_ms_to_dttm(cls) -> str: return "DATEADD(MS, {col}, '1970-01-01')" @classmethod def convert_dttm(cls, target_type: str, dttm: datetime) -> Optional[str]: tt = target_type.upper() if tt == utils.TemporalType.DATE: return f"TO_DATE('{dttm.date().isoformat()}')" if tt == utils.TemporalType.DATETIME: return f"""CAST('{dttm.isoformat(timespec="microseconds")}' AS DATETIME)""" if tt == utils.TemporalType.TIMESTAMP: return f"""TO_TIMESTAMP('{dttm.isoformat(timespec="microseconds")}')""" return None @staticmethod def mutate_db_for_connection_test(database: "Database") -> None: """ By default, snowflake doesn't validate if the user/role has access to the chosen database. :param database: instance to be mutated """ extra = json.loads(database.extra or "{}") engine_params = extra.get("engine_params", {}) connect_args = engine_params.get("connect_args", {}) connect_args["validate_default_parameters"] = True engine_params["connect_args"] = connect_args extra["engine_params"] = engine_params database.extra = json.dumps(extra) @classmethod def get_cancel_query_id(cls, cursor: Any, query: Query) -> Optional[str]: """ Get Snowflake session ID that will be used to cancel all other running queries in the same session. :param cursor: Cursor instance in which the query will be executed :param query: Query instance :return: Snowflake Session ID """ cursor.execute("SELECT CURRENT_SESSION()") row = cursor.fetchone() return row[0] @classmethod def cancel_query(cls, cursor: Any, query: Query, cancel_query_id: str) -> bool: """ Cancel query in the underlying database. :param cursor: New cursor instance to the db of the query :param query: Query instance :param cancel_query_id: Snowflake Session ID :return: True if query cancelled successfully, False otherwise """ try: cursor.execute(f"SELECT SYSTEM$CANCEL_ALL_QUERIES({cancel_query_id})") except Exception: # pylint: disable=broad-except return False return True @classmethod def build_sqlalchemy_uri( cls, parameters: SnowflakeParametersType, encrypted_extra: Optional[ # pylint: disable=unused-argument Dict[str, Any] ] = None, ) -> str: return str( URL( "snowflake", username=parameters.get("username"), password=parameters.get("password"), host=parameters.get("account"), database=parameters.get("database"), query={ "role": parameters.get("role"), "warehouse": parameters.get("warehouse"), }, ) ) @classmethod def get_parameters_from_uri( cls, uri: str, encrypted_extra: Optional[ # pylint: disable=unused-argument Dict[str, str] ] = None, ) -> Any: url = make_url(uri) query = dict(url.query.items()) return { "username": url.username, "password": url.password, "account": url.host, "database": url.database, "role": query.get("role"), "warehouse": query.get("warehouse"), } @classmethod def validate_parameters( cls, parameters: SnowflakeParametersType ) -> List[SupersetError]: errors: List[SupersetError] = [] required = { "warehouse", "username", "database", "account", "role", "password", } present = {key for key in parameters if parameters.get(key, ())} missing = sorted(required - present) if missing: errors.append( SupersetError( message=f'One or more parameters are missing: {", ".join(missing)}', error_type=SupersetErrorType.CONNECTION_MISSING_PARAMETERS_ERROR, level=ErrorLevel.WARNING, extra={"missing": missing}, ), ) return errors @classmethod def parameters_json_schema(cls) -> Any: """ Return configuration parameters as OpenAPI. """ if not cls.parameters_schema: return None ma_plugin = MarshmallowPlugin() spec = APISpec( title="Database Parameters", version="1.0.0", openapi_version="3.0.0", plugins=[ma_plugin], ) spec.components.schema(cls.__name__, schema=cls.parameters_schema) return spec.to_dict()["components"]["schemas"][cls.__name__]
import peewee as pw import pytest from muffin_peewee import Plugin as Peewee, JSONField @pytest.fixture(scope='module') def aiolib(): return 'asyncio', {'use_uvloop': False} @pytest.fixture(scope='session', autouse=True) def setup_logging(): import logging logger = logging.getLogger('peewee') logger.setLevel(logging.DEBUG) @pytest.fixture async def db(app): db = Peewee(app, connection='sqlite:///:memory:', auto_connection=False) async with db: async with db.connection(): yield db @pytest.fixture async def Resource(db): @db.manager.register class Resource(pw.Model): active = pw.BooleanField(default=False) name = pw.CharField(null=False) count = pw.IntegerField(null=True) config = JSONField(default={}) assert Resource._manager await db.manager.create_tables(Resource) return Resource @pytest.fixture async def ResourceEndpoint(Resource, api): from muffin_rest.peewee import PWRESTHandler @api.route class ResourceEndpoint(PWRESTHandler): class Meta: filters = 'active', 'name', ('oid', {'field': 'id'}), limit = 10 model = Resource sorting = ('id', {'default': 'desc'}), 'name', Resource.count @PWRESTHandler.route('/resource/action') async def action(self, request, resource=None): """Description for the action.""" resources = await self.meta.manager.fetchall(self.collection) return await self.dump(request, resources) return ResourceEndpoint @pytest.fixture async def resource(Resource, db): return await db.create(Resource, name='test') def test_imports(): from muffin_rest import PWRESTHandler, PWFilter, PWFilters, PWSort, PWSorting assert PWRESTHandler assert PWFilter assert PWFilters assert PWSort assert PWSorting async def test_base(api, ResourceEndpoint, Resource): assert ResourceEndpoint assert ResourceEndpoint.meta.name == 'resource' assert ResourceEndpoint.meta.manager # Schema assert ResourceEndpoint.meta.Schema assert ResourceEndpoint.meta.Schema._declared_fields ff = ResourceEndpoint.meta.Schema._declared_fields['active'] assert ff.load_default is False # Sorting assert ResourceEndpoint.meta.sorting assert list(ResourceEndpoint.meta.sorting.mutations.keys()) == ['id', 'name', 'count'] assert ResourceEndpoint.meta.sorting.default == [Resource.id.desc()] assert api.router.plain['/resource'] assert api.router.dynamic[0].pattern.pattern == '^/resource/(?P<id>[^/]+)$' async def test_get(client, ResourceEndpoint, resource): res = await client.get('/api/resource') assert res.status_code == 200 json = await res.json() assert json assert json[0]['config'] == {} assert json[0]['count'] is None assert json[0]['id'] == '1' assert json[0]['name'] == 'test' res = await client.get('/api/resource/1') assert res.status_code == 200 assert await res.json() == { 'active': False, 'config': {}, 'count': None, 'id': '1', 'name': 'test', } res = await client.get('/api/resource/unknown') assert res.status_code == 404 assert await res.json() == {'error': True, 'message': 'Resource not found'} res = await client.get('/api/resource/action?custom=123') assert res.status_code == 200 json = await res.json() assert json async def test_create(client, ResourceEndpoint): res = await client.post('/api/resource', json={'active': True}) assert res.status_code == 400 json = await res.json() assert json['errors'] assert 'name' in json['errors'] res = await client.post('/api/resource', data={'name': 'test2', 'active': True, 'unknown': 22}) assert res.status_code == 200 json = await res.json() assert json['id'] == '1' assert json['name'] == 'test2' assert json['active'] async def test_edit(client, resource, ResourceEndpoint): res = await client.put('/api/resource/1', data={'name': 'new'}) assert res.status_code == 200 json = await res.json() assert json['name'] == 'new' assert json['id'] == '1' async def test_delete(client, resource, ResourceEndpoint, Resource, db): res = await client.delete('/api/resource/1') assert res.status_code == 200 json = await res.json() assert not json assert not await db.fetchone(Resource.select().where(Resource.id == 1)) async def test_sort(client, ResourceEndpoint, Resource, db): await db.create(Resource, name='test2', count=2) await db.create(Resource, name='test3', count=3) await db.create(Resource, name='test4', count=1) # Default sort res = await client.get('/api/resource') assert res.status_code == 200 json = await res.json() assert json[0]['id'] == '3' assert json[1]['id'] == '2' res = await client.get('/api/resource?sort=-count') assert res.status_code == 200 json = await res.json() assert json[0]['id'] == '2' assert json[1]['id'] == '1' async def test_filters(client, ResourceEndpoint, Resource, db): await db.create(Resource, name='test2', count=2) await db.create(Resource, name='test3', count=3) await db.create(Resource, name='test4', count=1) res = await client.get('/api/resource?where={"name":"test"}') assert res.status_code == 200 json = await res.json() assert len(json) == 0 res = await client.get('/api/resource?where={"name": {"$in": ["test3", "test2"]}}') assert res.status_code == 200 json = await res.json() assert len(json) == 2 res = await client.get('/api/resource?where={"name": {"$starts": "test"}}') assert res.status_code == 200 json = await res.json() assert len(json) == 3 res = await client.get('/api/resource?where={"name": {"$ends": "3"}}') assert res.status_code == 200 json = await res.json() assert len(json) == 1 res = await client.get('/api/resource?where={"oid": {"$between": ["2", "3"]}}') assert res.status_code == 200 json = await res.json() assert len(json) == 2 res = await client.get('/api/resource?where={"oid": {"$gt": "2"}}') assert res.status_code == 200 json = await res.json() assert len(json) == 1 async def test_paginate(client, ResourceEndpoint, Resource, db): for n in range(12): await db.create(Resource, name=f"test{n}") res = await client.get('/api/resource') assert res.status_code == 200 json = await res.json() assert len(json) == 10 res = await client.get('/api/resource?limit=5') assert res.status_code == 200 assert res.headers['x-total'] == '12' assert res.headers['x-limit'] == '5' assert res.headers['x-offset'] == '0' json = await res.json() assert len(json) == 5 res = await client.get('/api/resource?limit=5&offset=9') assert res.status_code == 200 assert res.headers['x-total'] == '12' assert res.headers['x-limit'] == '5' assert res.headers['x-offset'] == '9' json = await res.json() assert len(json) == 3 async def test_batch_ops(client, ResourceEndpoint, db, Resource): # Batch operations (only POST/DELETE are supported for now) res = await client.post('/api/resource', json=[ {'name': 'test3', 'active': True}, {'name': 'test4', 'active': True}, {'name': 'test6', 'active': True}, ]) assert res.status_code == 200 json = await res.json() assert len(json) == 3 assert json[0]['id'] == '1' assert json[1]['id'] == '2' assert json[2]['id'] == '3' res = await client.delete('/api/resource', json=['1', '2', '3']) assert res.status_code == 200 assert not await db.count(Resource.select().where(Resource.id << ('11', '12', '13'))) async def test_openapi(client, ResourceEndpoint): res = await client.get('/api/openapi.json') assert res.status_code == 200 json = await res.json() assert json async def test_endpoint_inheritance(Resource): from muffin_rest.peewee import PWRESTHandler class ResourceEndpoint(PWRESTHandler): class Meta: model = Resource assert ResourceEndpoint.meta.name == 'resource' class ChildEndpoint(ResourceEndpoint): class Meta: name = 'child' assert ChildEndpoint.meta.name == 'child' async def test_aiomodels(client, db, api): events = [] class TestModel(db.Model): data = pw.CharField() async def save(self, **kwargs): events.append('custom-save') return await super().save(**kwargs) async def delete_instance(self, **kwargs): events.append('custom-delete') return await super().delete_instance(**kwargs) await db.create_tables(TestModel) from muffin_rest.peewee import PWRESTHandler @api.route class Test(PWRESTHandler): class Meta: model = TestModel res = await client.post('/api/testmodel', json={'data': 'test'}) assert res.status_code == 200 json = await res.json() assert json['id'] assert events assert 'custom-save' in events res = await client.delete(f"/api/testmodel/{json["id"]}") assert res.status_code == 200 assert 'custom-delete' in events
import peewee as pw import pytest from muffin_peewee import Plugin as Peewee, JSONField @pytest.fixture(scope='module') def aiolib(): return 'asyncio', {'use_uvloop': False} @pytest.fixture(scope='session', autouse=True) def setup_logging(): import logging logger = logging.getLogger('peewee') logger.setLevel(logging.DEBUG) @pytest.fixture async def db(app): db = Peewee(app, connection='sqlite:///:memory:', auto_connection=False) async with db: async with db.connection(): yield db @pytest.fixture async def Resource(db): @db.manager.register class Resource(pw.Model): active = pw.BooleanField(default=False) name = pw.CharField(null=False) count = pw.IntegerField(null=True) config = JSONField(default={}) assert Resource._manager await db.manager.create_tables(Resource) return Resource @pytest.fixture async def ResourceEndpoint(Resource, api): from muffin_rest.peewee import PWRESTHandler @api.route class ResourceEndpoint(PWRESTHandler): class Meta: filters = 'active', 'name', ('oid', {'field': 'id'}), limit = 10 model = Resource sorting = ('id', {'default': 'desc'}), 'name', Resource.count @PWRESTHandler.route('/resource/action') async def action(self, request, resource=None): """Description for the action.""" resources = await self.meta.manager.fetchall(self.collection) return await self.dump(request, resources) return ResourceEndpoint @pytest.fixture async def resource(Resource, db): return await db.create(Resource, name='test') def test_imports(): from muffin_rest import PWRESTHandler, PWFilter, PWFilters, PWSort, PWSorting assert PWRESTHandler assert PWFilter assert PWFilters assert PWSort assert PWSorting async def test_base(api, ResourceEndpoint, Resource): assert ResourceEndpoint assert ResourceEndpoint.meta.name == 'resource' assert ResourceEndpoint.meta.manager # Schema assert ResourceEndpoint.meta.Schema assert ResourceEndpoint.meta.Schema._declared_fields ff = ResourceEndpoint.meta.Schema._declared_fields['active'] assert ff.load_default is False # Sorting assert ResourceEndpoint.meta.sorting assert list(ResourceEndpoint.meta.sorting.mutations.keys()) == ['id', 'name', 'count'] assert ResourceEndpoint.meta.sorting.default == [Resource.id.desc()] assert api.router.plain['/resource'] assert api.router.dynamic[0].pattern.pattern == '^/resource/(?P<id>[^/]+)$' async def test_get(client, ResourceEndpoint, resource): res = await client.get('/api/resource') assert res.status_code == 200 json = await res.json() assert json assert json[0]['config'] == {} assert json[0]['count'] is None assert json[0]['id'] == '1' assert json[0]['name'] == 'test' res = await client.get('/api/resource/1') assert res.status_code == 200 assert await res.json() == { 'active': False, 'config': {}, 'count': None, 'id': '1', 'name': 'test', } res = await client.get('/api/resource/unknown') assert res.status_code == 404 assert await res.json() == {'error': True, 'message': 'Resource not found'} res = await client.get('/api/resource/action?custom=123') assert res.status_code == 200 json = await res.json() assert json async def test_create(client, ResourceEndpoint): res = await client.post('/api/resource', json={'active': True}) assert res.status_code == 400 json = await res.json() assert json['errors'] assert 'name' in json['errors'] res = await client.post('/api/resource', data={'name': 'test2', 'active': True, 'unknown': 22}) assert res.status_code == 200 json = await res.json() assert json['id'] == '1' assert json['name'] == 'test2' assert json['active'] async def test_edit(client, resource, ResourceEndpoint): res = await client.put('/api/resource/1', data={'name': 'new'}) assert res.status_code == 200 json = await res.json() assert json['name'] == 'new' assert json['id'] == '1' async def test_delete(client, resource, ResourceEndpoint, Resource, db): res = await client.delete('/api/resource/1') assert res.status_code == 200 json = await res.json() assert not json assert not await db.fetchone(Resource.select().where(Resource.id == 1)) async def test_sort(client, ResourceEndpoint, Resource, db): await db.create(Resource, name='test2', count=2) await db.create(Resource, name='test3', count=3) await db.create(Resource, name='test4', count=1) # Default sort res = await client.get('/api/resource') assert res.status_code == 200 json = await res.json() assert json[0]['id'] == '3' assert json[1]['id'] == '2' res = await client.get('/api/resource?sort=-count') assert res.status_code == 200 json = await res.json() assert json[0]['id'] == '2' assert json[1]['id'] == '1' async def test_filters(client, ResourceEndpoint, Resource, db): await db.create(Resource, name='test2', count=2) await db.create(Resource, name='test3', count=3) await db.create(Resource, name='test4', count=1) res = await client.get('/api/resource?where={"name":"test"}') assert res.status_code == 200 json = await res.json() assert len(json) == 0 res = await client.get('/api/resource?where={"name": {"$in": ["test3", "test2"]}}') assert res.status_code == 200 json = await res.json() assert len(json) == 2 res = await client.get('/api/resource?where={"name": {"$starts": "test"}}') assert res.status_code == 200 json = await res.json() assert len(json) == 3 res = await client.get('/api/resource?where={"name": {"$ends": "3"}}') assert res.status_code == 200 json = await res.json() assert len(json) == 1 res = await client.get('/api/resource?where={"oid": {"$between": ["2", "3"]}}') assert res.status_code == 200 json = await res.json() assert len(json) == 2 res = await client.get('/api/resource?where={"oid": {"$gt": "2"}}') assert res.status_code == 200 json = await res.json() assert len(json) == 1 async def test_paginate(client, ResourceEndpoint, Resource, db): for n in range(12): await db.create(Resource, name=f"test{n}") res = await client.get('/api/resource') assert res.status_code == 200 json = await res.json() assert len(json) == 10 res = await client.get('/api/resource?limit=5') assert res.status_code == 200 assert res.headers['x-total'] == '12' assert res.headers['x-limit'] == '5' assert res.headers['x-offset'] == '0' json = await res.json() assert len(json) == 5 res = await client.get('/api/resource?limit=5&offset=9') assert res.status_code == 200 assert res.headers['x-total'] == '12' assert res.headers['x-limit'] == '5' assert res.headers['x-offset'] == '9' json = await res.json() assert len(json) == 3 async def test_batch_ops(client, ResourceEndpoint, db, Resource): # Batch operations (only POST/DELETE are supported for now) res = await client.post('/api/resource', json=[ {'name': 'test3', 'active': True}, {'name': 'test4', 'active': True}, {'name': 'test6', 'active': True}, ]) assert res.status_code == 200 json = await res.json() assert len(json) == 3 assert json[0]['id'] == '1' assert json[1]['id'] == '2' assert json[2]['id'] == '3' res = await client.delete('/api/resource', json=['1', '2', '3']) assert res.status_code == 200 assert not await db.count(Resource.select().where(Resource.id << ('11', '12', '13'))) async def test_openapi(client, ResourceEndpoint): res = await client.get('/api/openapi.json') assert res.status_code == 200 json = await res.json() assert json async def test_endpoint_inheritance(Resource): from muffin_rest.peewee import PWRESTHandler class ResourceEndpoint(PWRESTHandler): class Meta: model = Resource assert ResourceEndpoint.meta.name == 'resource' class ChildEndpoint(ResourceEndpoint): class Meta: name = 'child' assert ChildEndpoint.meta.name == 'child' async def test_aiomodels(client, db, api): events = [] class TestModel(db.Model): data = pw.CharField() async def save(self, **kwargs): events.append('custom-save') return await super().save(**kwargs) async def delete_instance(self, **kwargs): events.append('custom-delete') return await super().delete_instance(**kwargs) await db.create_tables(TestModel) from muffin_rest.peewee import PWRESTHandler @api.route class Test(PWRESTHandler): class Meta: model = TestModel res = await client.post('/api/testmodel', json={'data': 'test'}) assert res.status_code == 200 json = await res.json() assert json['id'] assert events assert 'custom-save' in events res = await client.delete(f"/api/testmodel/{json['id']}") assert res.status_code == 200 assert 'custom-delete' in events
# # This source file is part of the EdgeDB open source project. # # Copyright 2016-present MagicStack Inc. and the EdgeDB authors. # # 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. # """Database structure and objects supporting EdgeDB metadata.""" from __future__ import annotations from typing import * import re import textwrap from edb import _edgeql_rust from edb.common import context as parser_context from edb.common import debug from edb.common import exceptions from edb.common import uuidgen from edb.edgeql import qltypes from edb.edgeql import quote as qlquote from edb.schema import casts as s_casts from edb.schema import constraints as s_constr from edb.schema import links as s_links from edb.schema import name as s_name from edb.schema import objects as s_obj from edb.schema import objtypes as s_objtypes from edb.schema import pointers as s_pointers from edb.schema import properties as s_props from edb.schema import scalars as s_scalars from edb.schema import schema as s_schema from edb.schema import sources as s_sources from edb.schema import types as s_types from edb.server import defines from edb.server import compiler as edbcompiler from edb.server import bootstrap as edbbootstrap from edb.server import pgcluster from . import common from . import dbops from . import types if TYPE_CHECKING: import asyncpg q = common.qname qi = common.quote_ident ql = common.quote_literal qt = common.quote_type DATABASE_ID_NAMESPACE = uuidgen.UUID('0e6fed66-204b-11e9-8666-cffd58a5240b') CONFIG_ID_NAMESPACE = uuidgen.UUID('a48b38fa-349b-11e9-a6be-4f337f82f5ad') CONFIG_ID = uuidgen.UUID('172097a4-39f4-11e9-b189-9321eb2f4b97') class DBConfigTable(dbops.Table): def __init__(self) -> None: super().__init__(name=('edgedb', '_db_config')) self.add_columns([ dbops.Column(name='name', type='text'), dbops.Column(name='value', type='jsonb'), ]) self.add_constraint( dbops.UniqueConstraint( table_name=('edgedb', '_db_config'), columns=['name'], ), ) class ExpressionType(dbops.CompositeType): def __init__(self) -> None: super().__init__(name=('edgedb', 'expression_t')) self.add_columns([ dbops.Column(name='text', type='text'), dbops.Column(name='refs', type='uuid[]'), ]) class BigintDomain(dbops.Domain): """Bigint: a variant of numeric that enforces zero digits after the dot. We're using an explicit scale check as opposed to simply specifying the numeric bounds, because using bounds severly restricts the range of the numeric type (1000 vs 131072 digits). """ def __init__(self) -> None: super().__init__( name=('edgedb', 'bigint_t'), base='numeric', constraints=( dbops.DomainCheckConstraint( domain_name=('edgedb', 'bigint_t'), expr=("scale(VALUE) = 0 AND VALUE != 'NaN'"), ), ), ) class TimestampTzDomain(dbops.Domain): """Timestamptz clamped to years 0001-9999. The default timestamp range of (4713 BC - 294276 AD) has problems: Postgres isn't ISO compliant with years out of the 0-9999 range and language compatibility is questionable. """ def __init__(self) -> None: super().__init__( name=('edgedb', 'timestamptz_t'), base='timestamptz', constraints=( dbops.DomainCheckConstraint( domain_name=('edgedb', 'timestamptz_t'), expr=("EXTRACT(years from VALUE) BETWEEN 1 AND 9999"), ), ), ) class TimestampDomain(dbops.Domain): """Timestamp clamped to years 0001-9999. The default timestamp range of (4713 BC - 294276 AD) has problems: Postgres isn't ISO compliant with years out of the 0-9999 range and language compatibility is questionable. """ def __init__(self) -> None: super().__init__( name=('edgedb', 'timestamp_t'), base='timestamp', constraints=( dbops.DomainCheckConstraint( domain_name=('edgedb', 'timestamp_t'), expr=("EXTRACT(years from VALUE) BETWEEN 1 AND 9999"), ), ), ) class DateDomain(dbops.Domain): """Date clamped to years 0001-9999. The default timestamp range of (4713 BC - 294276 AD) has problems: Postgres isn't ISO compliant with years out of the 0-9999 range and language compatibility is questionable. """ def __init__(self) -> None: super().__init__( name=('edgedb', 'date_t'), base='date', constraints=( dbops.DomainCheckConstraint( domain_name=('edgedb', 'date_t'), expr=("EXTRACT(years from VALUE) BETWEEN 1 AND 9999"), ), ), ) class DurationDomain(dbops.Domain): def __init__(self) -> None: super().__init__( name=('edgedb', 'duration_t'), base='interval', constraints=( dbops.DomainCheckConstraint( domain_name=('edgedb', 'duration_t'), expr=r''' EXTRACT(months from VALUE) = 0 AND EXTRACT(years from VALUE) = 0 AND EXTRACT(days from VALUE) = 0 ''', ), ), ) class RelativeDurationDomain(dbops.Domain): def __init__(self) -> None: super().__init__( name=('edgedb', 'relative_duration_t'), base='interval', constraints=( dbops.DomainCheckConstraint( domain_name=('edgedb', 'relative_duration_t'), expr="true", ), ), ) class AlterCurrentDatabaseSetString(dbops.Function): """Alter a PostgreSQL configuration parameter of the current database.""" text = ''' BEGIN EXECUTE 'ALTER DATABASE ' || quote_ident(current_database()) || ' SET ' || quote_ident(parameter) || ' = ' || coalesce(quote_literal(value), 'DEFAULT'); RETURN value; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_alter_current_database_set'), args=[('parameter', ('text',)), ('value', ('text',))], returns=('text',), volatility='volatile', language='plpgsql', text=self.text, ) class AlterCurrentDatabaseSetStringArray(dbops.Function): """Alter a PostgreSQL configuration parameter of the current database.""" text = ''' BEGIN EXECUTE 'ALTER DATABASE ' || quote_ident(current_database()) || ' SET ' || quote_ident(parameter) || ' = ' || coalesce( (SELECT array_to_string(array_agg(quote_literal(q.v)), ',') FROM unnest(value) AS q(v) ), 'DEFAULT' ); RETURN value; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_alter_current_database_set'), args=[ ('parameter', ('text',)), ('value', ('text[]',)), ], returns=('text[]',), volatility='volatile', language='plpgsql', text=self.text, ) class AlterCurrentDatabaseSetNonArray(dbops.Function): """Alter a PostgreSQL configuration parameter of the current database.""" text = ''' BEGIN EXECUTE 'ALTER DATABASE ' || quote_ident(current_database()) || ' SET ' || quote_ident(parameter) || ' = ' || coalesce(value::text, 'DEFAULT'); RETURN value; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_alter_current_database_set'), args=[ ('parameter', ('text',)), ('value', ('anynonarray',)), ], returns=('anynonarray',), volatility='volatile', language='plpgsql', text=self.text, ) class AlterCurrentDatabaseSetArray(dbops.Function): """Alter a PostgreSQL configuration parameter of the current database.""" text = ''' BEGIN EXECUTE 'ALTER DATABASE ' || quote_ident(current_database()) || ' SET ' || quote_ident(parameter) || ' = ' || coalesce( (SELECT array_to_string(array_agg(q.v::text), ',') FROM unnest(value) AS q(v) ), 'DEFAULT' ); RETURN value; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_alter_current_database_set'), args=[ ('parameter', ('text',)), ('value', ('anyarray',)), ], returns=('anyarray',), volatility='volatile', language='plpgsql', text=self.text, ) class StrToBigint(dbops.Function): """Parse bigint from text.""" text = r''' SELECT (CASE WHEN scale(v.column1) = 0 THEN v.column1 ELSE edgedb.raise( NULL::numeric, 'invalid_text_representation', msg => ( 'invalid syntax for edgedb.bigint_t: ' || quote_literal(val) ) ) END)::edgedb.bigint_t FROM (VALUES ( val::numeric )) AS v ; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'str_to_bigint'), args=[('val', ('text',))], returns=('edgedb', 'bigint_t'), # Stable because it's raising exceptions. volatility='stable', text=self.text) class StrToDecimal(dbops.Function): """Parse decimal from text.""" text = r''' SELECT (CASE WHEN v.column1 != 'NaN' THEN v.column1 ELSE edgedb.raise( NULL::numeric, 'invalid_text_representation', msg => ( 'invalid syntax for numeric: ' || quote_literal(val) ) ) END) FROM (VALUES ( val::numeric )) AS v ; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'str_to_decimal'), args=[('val', ('text',))], returns=('numeric',), # Stable because it's raising exceptions. volatility='stable', text=self.text, ) class StrToInt64NoInline(dbops.Function): """String-to-int64 cast with noinline guard. Adding a LIMIT clause to the function statement makes it uninlinable due to the Postgres inlining heuristic looking for simple SELECT expressions only (i.e. no clauses.) This might need to change in the future if the heuristic changes. """ text = r''' SELECT "val"::bigint LIMIT 1 ; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'str_to_int64_noinline'), args=[('val', ('text',))], returns=('bigint',), volatility='stable', text=self.text, ) class StrToInt32NoInline(dbops.Function): """String-to-int32 cast with noinline guard.""" text = r''' SELECT "val"::int LIMIT 1 ; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'str_to_int32_noinline'), args=[('val', ('text',))], returns=('int',), volatility='stable', text=self.text, ) class StrToInt16NoInline(dbops.Function): """String-to-int16 cast with noinline guard.""" text = r''' SELECT "val"::smallint LIMIT 1 ; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'str_to_int16_noinline'), args=[('val', ('text',))], returns=('smallint',), volatility='stable', text=self.text, ) class StrToFloat64NoInline(dbops.Function): """String-to-float64 cast with noinline guard.""" text = r''' SELECT "val"::float8 LIMIT 1 ; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'str_to_float64_noinline'), args=[('val', ('text',))], returns=('float8',), volatility='stable', text=self.text, ) class StrToFloat32NoInline(dbops.Function): """String-to-float32 cast with noinline guard.""" text = r''' SELECT "val"::float4 LIMIT 1 ; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'str_to_float32_noinline'), args=[('val', ('text',))], returns=('float4',), volatility='stable', text=self.text, ) class GetBackendCapabilitiesFunction(dbops.Function): text = f''' SELECT (json ->> 'capabilities')::bigint FROM edgedbinstdata.instdata WHERE key = 'backend_instance_params' ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_backend_capabilities'), args=[], returns=('bigint',), language='sql', volatility='stable', text=self.text, ) class GetBackendTenantIDFunction(dbops.Function): text = f''' SELECT (json ->> 'tenant_id')::text FROM edgedbinstdata.instdata WHERE key = 'backend_instance_params' ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_backend_tenant_id'), args=[], returns=('text',), language='sql', volatility='stable', text=self.text, ) class GetDatabaseBackendNameFunction(dbops.Function): text = f''' SELECT edgedb.get_backend_tenant_id() || '_' || "db_name" ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_database_backend_name'), args=[('db_name', ('text',))], returns=('text',), language='sql', volatility='stable', text=self.text, ) class GetRoleBackendNameFunction(dbops.Function): text = f''' SELECT edgedb.get_backend_tenant_id() || '_' || "role_name" ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_role_backend_name'), args=[('role_name', ('text',))], returns=('text',), language='sql', volatility='stable', text=self.text, ) class GetUserSequenceBackendNameFunction(dbops.Function): text = f""" SELECT 'edgedbpub', "sequence_type_id"::text || '_sequence' """ def __init__(self) -> None: super().__init__( name=('edgedb', 'get_user_sequence_backend_name'), args=[('sequence_type_id', ('uuid',))], returns=('record',), language='sql', volatility='stable', text=self.text, ) class GetSequenceBackendNameFunction(dbops.Function): text = f''' SELECT (CASE WHEN edgedb.get_name_module(st.name) = any(edgedb.get_std_modules()) THEN 'edgedbstd' ELSE 'edgedbpub' END), "sequence_type_id"::text || '_sequence' FROM edgedb."_SchemaScalarType" AS st WHERE st.id = "sequence_type_id" ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_sequence_backend_name'), args=[('sequence_type_id', ('uuid',))], returns=('record',), language='sql', volatility='stable', text=self.text, ) class GetStdModulesFunction(dbops.Function): text = f''' SELECT ARRAY[{",".join(ql(str(m)) for m in s_schema.STD_MODULES)}] ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_std_modules'), args=[], returns=('text[]',), language='sql', volatility='immutable', text=self.text, ) class GetObjectMetadata(dbops.Function): """Return EdgeDB metadata associated with a backend object.""" text = ''' SELECT CASE WHEN substr(d, 1, char_length({prefix})) = {prefix} THEN substr(d, char_length({prefix}) + 1)::jsonb ELSE '{{}}'::jsonb END FROM obj_description("objoid", "objclass") AS d '''.format( prefix=f'E{ql(defines.EDGEDB_VISIBLE_METADATA_PREFIX)}', ) def __init__(self) -> None: super().__init__( name=('edgedb', 'obj_metadata'), args=[('objoid', ('oid',)), ('objclass', ('text',))], returns=('jsonb',), volatility='stable', text=self.text) class GetColumnMetadata(dbops.Function): """Return EdgeDB metadata associated with a backend object.""" text = ''' SELECT CASE WHEN substr(d, 1, char_length({prefix})) = {prefix} THEN substr(d, char_length({prefix}) + 1)::jsonb ELSE '{{}}'::jsonb END FROM col_description("tableoid", "column") AS d '''.format( prefix=f'E{ql(defines.EDGEDB_VISIBLE_METADATA_PREFIX)}', ) def __init__(self) -> None: super().__init__( name=('edgedb', 'col_metadata'), args=[('tableoid', ('oid',)), ('column', ('integer',))], returns=('jsonb',), volatility='stable', text=self.text) class GetSharedObjectMetadata(dbops.Function): """Return EdgeDB metadata associated with a backend object.""" text = ''' SELECT CASE WHEN substr(d, 1, char_length({prefix})) = {prefix} THEN substr(d, char_length({prefix}) + 1)::jsonb ELSE '{{}}'::jsonb END FROM shobj_description("objoid", "objclass") AS d '''.format( prefix=f'E{ql(defines.EDGEDB_VISIBLE_METADATA_PREFIX)}', ) def __init__(self) -> None: super().__init__( name=('edgedb', 'shobj_metadata'), args=[('objoid', ('oid',)), ('objclass', ('text',))], returns=('jsonb',), volatility='stable', text=self.text) class GetDatabaseMetadataFunction(dbops.Function): """Return EdgeDB metadata associated with a given database.""" text = ''' SELECT edgedb.shobj_metadata( (SELECT oid FROM pg_database WHERE datname = edgedb.get_database_backend_name("dbname") ), 'pg_database' ) ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_database_metadata'), args=[('dbname', ('text',))], returns=('jsonb',), volatility='stable', text=self.text, ) class GetCurrentDatabaseFunction(dbops.Function): text = f''' SELECT substr( current_database(), char_length(edgedb.get_backend_tenant_id()) + 2 ) ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_current_database'), args=[], returns=('text',), language='sql', volatility='stable', text=self.text, ) class RaiseExceptionFunction(dbops.Function): text = ''' BEGIN RAISE EXCEPTION USING ERRCODE = "exc", MESSAGE = "msg", DETAIL = COALESCE("detail", ''), HINT = COALESCE("hint", ''), COLUMN = COALESCE("column", ''), CONSTRAINT = COALESCE("constraint", ''), DATATYPE = COALESCE("datatype", ''), TABLE = COALESCE("table", ''), SCHEMA = COALESCE("schema", ''); RETURN "rtype"; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'raise'), args=[ ('rtype', ('anyelement',)), ('exc', ('text',), "'raise_exception'"), ('msg', ('text',), "''"), ('detail', ('text',), "''"), ('hint', ('text',), "''"), ('column', ('text',), "''"), ('constraint', ('text',), "''"), ('datatype', ('text',), "''"), ('table', ('text',), "''"), ('schema', ('text',), "''"), ], returns=('anyelement',), # NOTE: The main reason why we don't want this function to be # immutable is that immutable functions can be # pre-evaluated by the query planner once if they have # constant arguments. This means that using this function # as the second argument in a COALESCE will raise an # exception regardless of whether the first argument is # NULL or not. volatility='stable', language='plpgsql', text=self.text, ) class RaiseExceptionOnNullFunction(dbops.Function): """Return the passed value or raise an exception if it's NULL.""" text = ''' SELECT coalesce( val, edgedb.raise( val, exc, msg => msg, detail => detail, hint => hint, "column" => "column", "constraint" => "constraint", "datatype" => "datatype", "table" => "table", "schema" => "schema" ) ) ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'raise_on_null'), args=[ ('val', ('anyelement',)), ('exc', ('text',)), ('msg', ('text',)), ('detail', ('text',), "''"), ('hint', ('text',), "''"), ('column', ('text',), "''"), ('constraint', ('text',), "''"), ('datatype', ('text',), "''"), ('table', ('text',), "''"), ('schema', ('text',), "''"), ], returns=('anyelement',), # Same volatility as raise() volatility='stable', text=self.text, ) class RaiseExceptionOnNotNullFunction(dbops.Function): """Return the passed value or raise an exception if it's NOT NULL.""" text = ''' SELECT CASE WHEN val IS NULL THEN val ELSE edgedb.raise( val, exc, msg => msg, detail => detail, hint => hint, "column" => "column", "constraint" => "constraint", "datatype" => "datatype", "table" => "table", "schema" => "schema" ) END ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'raise_on_not_null'), args=[ ('val', ('anyelement',)), ('exc', ('text',)), ('msg', ('text',)), ('detail', ('text',), "''"), ('hint', ('text',), "''"), ('column', ('text',), "''"), ('constraint', ('text',), "''"), ('datatype', ('text',), "''"), ('table', ('text',), "''"), ('schema', ('text',), "''"), ], returns=('anyelement',), # Same volatility as raise() volatility='stable', text=self.text, ) class RaiseExceptionOnEmptyStringFunction(dbops.Function): """Return the passed string or raise an exception if it's empty.""" text = ''' SELECT CASE WHEN edgedb._length(val) = 0 THEN edgedb.raise(val, exc, msg => msg, detail => detail) ELSE val END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'raise_on_empty'), args=[ ('val', ('anyelement',)), ('exc', ('text',)), ('msg', ('text',)), ('detail', ('text',), "''"), ], returns=('anyelement',), # Same volatility as raise() volatility='stable', text=self.text, ) class AssertJSONTypeFunction(dbops.Function): """Assert that the JSON type matches what is expected.""" text = ''' SELECT CASE WHEN array_position(typenames, jsonb_typeof(val)) IS NULL THEN edgedb.raise( NULL::jsonb, 'wrong_object_type', msg => coalesce( msg, ( 'expected json ' || array_to_string(typenames, ' or ') || '; got json ' || coalesce(jsonb_typeof(val), 'UNKNOWN') ) ), detail => detail ) ELSE val END ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'jsonb_assert_type'), args=[ ('val', ('jsonb',)), ('typenames', ('text[]',)), ('msg', ('text',), 'NULL'), ('detail', ('text',), "''"), ], returns=('jsonb',), # Max volatility of raise() and array_to_string() (stable) volatility='stable', text=self.text, ) class ExtractJSONScalarFunction(dbops.Function): """Convert a given JSON scalar value into a text value.""" text = ''' SELECT (to_jsonb(ARRAY[ edgedb.jsonb_assert_type( coalesce(val, 'null'::jsonb), ARRAY[json_typename, 'null'], msg => msg, detail => detail ) ])->>0) ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'jsonb_extract_scalar'), args=[ ('val', ('jsonb',)), ('json_typename', ('text',)), ('msg', ('text',), 'NULL'), ('detail', ('text',), "''"), ], returns=('text',), volatility='stable', text=self.text, ) class GetSchemaObjectNameFunction(dbops.Function): text = ''' SELECT coalesce( (SELECT name FROM edgedb."_SchemaObject" WHERE id = type::uuid), edgedb.raise( NULL::text, msg => 'resolve_type_name: unknown type: "' || type || '"' ) ) ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_get_schema_object_name'), args=[('type', ('uuid',))], returns=('text',), # Max volatility of raise() and a SELECT from a # table (stable). volatility='stable', text=self.text, strict=True, ) class IssubclassFunction(dbops.Function): text = ''' SELECT clsid = any(classes) OR ( SELECT classes && q.ancestors FROM (SELECT array_agg(o.target) AS ancestors FROM edgedb."_SchemaInheritingObject__ancestors" o WHERE o.source = clsid ) AS q ); ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'issubclass'), args=[('clsid', 'uuid'), ('classes', 'uuid[]')], returns='bool', volatility='stable', text=self.__class__.text) class IssubclassFunction2(dbops.Function): text = ''' SELECT clsid = pclsid OR ( SELECT pclsid IN ( SELECT o.target FROM edgedb."_SchemaInheritingObject__ancestors" o WHERE o.source = clsid ) ); ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'issubclass'), args=[('clsid', 'uuid'), ('pclsid', 'uuid')], returns='bool', volatility='stable', text=self.__class__.text) class NormalizeNameFunction(dbops.Function): text = ''' SELECT CASE WHEN strpos(name, '@') = 0 THEN name ELSE CASE WHEN strpos(name, '::') = 0 THEN replace(split_part(name, '@', 1), '|', '::') ELSE replace( split_part( -- "reverse" calls are to emulate "rsplit" reverse(split_part(reverse(name), '::', 1)), '@', 1), '|', '::') END END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'shortname_from_fullname'), args=[('name', 'text')], returns='text', volatility='immutable', language='sql', text=self.__class__.text) class GetNameModuleFunction(dbops.Function): text = ''' SELECT reverse(split_part(reverse("name"), '::', 1)) ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_name_module'), args=[('name', 'text')], returns='text', volatility='immutable', language='sql', text=self.__class__.text) class NullIfArrayNullsFunction(dbops.Function): """Check if array contains NULLs and if so, return NULL.""" def __init__(self) -> None: super().__init__( name=('edgedb', '_nullif_array_nulls'), args=[('a', 'anyarray')], returns='anyarray', volatility='stable', language='sql', text=''' SELECT CASE WHEN array_position(a, NULL) IS NULL THEN a ELSE NULL END ''') class IndexDescType(dbops.CompositeType): """Introspected index description.""" def __init__(self) -> None: super().__init__(name=('edgedb', 'intro_index_desc_t')) self.add_columns([ dbops.Column(name='table_name', type='text[]'), dbops.Column(name='name', type='text'), dbops.Column(name='is_unique', type='bool'), dbops.Column(name='predicate', type='text'), dbops.Column(name='expression', type='text'), dbops.Column(name='columns', type='text[]'), dbops.Column(name='metadata', type='jsonb'), ]) class IntrospectIndexesFunction(dbops.Function): """Return set of indexes for each table.""" text = ''' SELECT i.table_name, i.index_name, i.index_is_unique, i.index_predicate, i.index_expression, i.index_columns, i.index_metadata FROM (SELECT * FROM (SELECT ARRAY[ns.nspname::text, c.relname::text] AS table_name, ic.relname::text AS index_name, i.indisunique AS index_is_unique, pg_get_expr(i.indpred, i.indrelid)::text AS index_predicate, pg_get_expr(i.indexprs, i.indrelid)::text AS index_expression, (SELECT array_agg(ia.attname::text ORDER BY ia.attnum) FROM pg_attribute AS ia WHERE ia.attrelid = i.indexrelid AND (ia.attnum IS NULL OR ia.attnum >= 1) ) AS index_columns, edgedb.obj_metadata(i.indexrelid, 'pg_class') AS index_metadata FROM pg_class AS c INNER JOIN pg_namespace AS ns ON ns.oid = c.relnamespace INNER JOIN pg_index AS i ON i.indrelid = c.oid INNER JOIN pg_class AS ic ON i.indexrelid = ic.oid WHERE ($1::text IS NULL OR ns.nspname LIKE $1::text) AND ($2::text IS NULL OR c.relname LIKE $2::text) AND ($3::text[] IS NULL OR ns.nspname || '.' || ic.relname = any($3::text[])) AND ($4::text IS NULL OR ic.relname LIKE $4::text) ) AS q WHERE (NOT $5::bool OR (index_metadata IS NOT NULL AND (index_metadata->>'ddl:inherit')::bool)) AND ( $6 OR ( index_metadata IS NULL OR NOT coalesce( (index_metadata->>'ddl:inherited')::bool, false) ) ) ) AS i ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'introspect_indexes'), args=[ ('schema_pattern', 'text', 'NULL'), ('table_pattern', 'text', 'NULL'), ('table_list', 'text[]', 'NULL'), ('index_pattern', 'text', 'NULL'), ('inheritable_only', 'bool', 'FALSE'), ('include_inherited', 'bool', 'FALSE'), ], returns=('edgedb', 'intro_index_desc_t'), set_returning=True, volatility='stable', language='sql', text=self.__class__.text) class TriggerDescType(dbops.CompositeType): """Introspected trigger description.""" def __init__(self) -> None: super().__init__(name=('edgedb', 'intro_trigger_desc_t')) self.add_columns([ dbops.Column(name='table_name', type='text[]'), dbops.Column(name='name', type='text'), dbops.Column(name='proc', type='text[]'), dbops.Column(name='is_constraint', type='bool'), dbops.Column(name='granularity', type='text'), dbops.Column(name='deferred', type='bool'), dbops.Column(name='timing', type='text'), dbops.Column(name='events', type='text[]'), dbops.Column(name='definition', type='text'), dbops.Column(name='condition', type='text'), dbops.Column(name='metadata', type='jsonb'), ]) class IntrospectTriggersFunction(dbops.Function): """Return a set of triggers for each table.""" text = ''' SELECT table_name, trg_name, trg_proc, trg_constraint, trg_granularity, trg_deferred, trg_timing, trg_events, trg_definition, NULL::text, trg_metadata FROM (SELECT * FROM (SELECT ARRAY[ns.nspname::text, tc.relname::text] AS table_name, t.oid::int AS trg_id, t.tgname::text AS trg_name, (SELECT ARRAY[nsp.nspname::text, p.proname::text] FROM pg_proc AS p INNER JOIN pg_namespace AS nsp ON nsp.oid = p.pronamespace WHERE t.tgfoid = p.oid ) AS trg_proc, t.tgconstraint != 0 AS trg_constraint, (CASE WHEN (t.tgtype & (1 << 0)) != 0 THEN 'row' ELSE 'statement' END) AS trg_granularity, t.tginitdeferred AS trg_deferred, (CASE WHEN (t.tgtype & (1 << 1)) != 0 THEN 'before' WHEN (t.tgtype & (1 << 6)) != 0 THEN 'instead' ELSE 'after' END) AS trg_timing, array_remove(ARRAY[ (CASE WHEN (t.tgtype & (1 << 2)) != 0 THEN 'insert' ELSE NULL END), (CASE WHEN (t.tgtype & (1 << 3)) != 0 THEN 'delete' ELSE NULL END), (CASE WHEN (t.tgtype & (1 << 4)) != 0 THEN 'update' ELSE NULL END), (CASE WHEN (t.tgtype & (1 << 5)) != 0 THEN 'truncate' ELSE NULL END) ]::text[], NULL) AS trg_events, pg_get_triggerdef(t.oid)::text AS trg_definition, edgedb.obj_metadata(t.oid, 'pg_trigger') AS trg_metadata FROM pg_trigger AS t INNER JOIN pg_class AS tc ON t.tgrelid = tc.oid INNER JOIN pg_namespace AS ns ON ns.oid = tc.relnamespace WHERE ($1::text IS NULL OR ns.nspname LIKE $1::text) AND ($2::text IS NULL OR tc.relname LIKE $2::text) AND ($3::text[] IS NULL OR ns.nspname || '.' || tc.relname = any($3::text[])) AND ($4::text IS NULL OR t.tgname LIKE $4::text) ) AS q WHERE (NOT $5::bool OR (trg_metadata IS NOT NULL AND (trg_metadata->>'ddl:inherit')::bool)) AND ( $6 OR ( trg_metadata IS NULL OR NOT coalesce( (trg_metadata->>'ddl:inherited')::bool, false) ) ) ) AS t ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'introspect_triggers'), args=[ ('schema_pattern', 'text', 'NULL'), ('table_pattern', 'text', 'NULL'), ('table_list', 'text[]', 'NULL'), ('trigger_pattern', 'text', 'NULL'), ('inheritable_only', 'bool', 'FALSE'), ('include_inherited', 'bool', 'FALSE'), ], returns=('edgedb', 'intro_trigger_desc_t'), set_returning=True, volatility='stable', language='sql', text=self.__class__.text) class TableInheritanceDescType(dbops.CompositeType): """Introspected table inheritance descriptor.""" def __init__(self) -> None: super().__init__(name=('edgedb', 'intro_tab_inh_t')) self.add_columns([ dbops.Column(name='name', type='text[]'), dbops.Column(name='depth', type='int'), dbops.Column(name='pos', type='int'), ]) class GetTableDescendantsFunction(dbops.Function): """Return a set of table descendants.""" text = ''' SELECT * FROM (WITH RECURSIVE inheritance(oid, name, ns, depth, path) AS ( SELECT c.oid, c.relname, ns.nspname, 0, ARRAY[c.relname] FROM pg_class c INNER JOIN pg_namespace ns ON c.relnamespace = ns.oid WHERE ($1::text IS NULL OR ns.nspname LIKE $1::text) AND ($2::text IS NULL OR c.relname LIKE $2::text) UNION ALL SELECT c.oid, c.relname, ns.nspname, i.depth + 1, i.path || c.relname FROM pg_class c, inheritance i, pg_inherits pgi, pg_namespace ns WHERE i.oid = pgi.inhparent AND c.oid = pgi.inhrelid AND ns.oid = c.relnamespace AND ($3::int IS NULL OR i.depth < $3::int) ) SELECT DISTINCT ON (ns, name) ARRAY[ns::text, name::text], depth, 0 FROM inheritance) q WHERE depth > 0 ORDER BY depth ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_table_descendants'), args=[ ('schema_name', 'text'), ('table_name', 'text'), ('max_depth', 'int', 'NULL'), ], returns=('edgedb', 'intro_tab_inh_t'), set_returning=True, volatility='stable', language='sql', text=self.__class__.text) class ParseTriggerConditionFunction(dbops.Function): """Return a set of table descendants.""" text = ''' DECLARE when_off integer; pos integer; brackets integer; chr text; def_len integer; BEGIN def_len := char_length(definition); when_off := strpos(definition, 'WHEN ('); IF when_off IS NULL OR when_off = 0 THEN RETURN NULL; ELSE pos := when_off + 6; brackets := 1; WHILE brackets > 0 AND pos < def_len LOOP chr := substr(definition, pos, 1); IF chr = ')' THEN brackets := brackets - 1; ELSIF chr = '(' THEN brackets := brackets + 1; END IF; pos := pos + 1; END LOOP; IF brackets != 0 THEN RAISE EXCEPTION 'cannot parse trigger condition: %', definition; END IF; RETURN substr( definition, when_off + 6, pos - (when_off + 6) - 1 ); END IF; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_parse_trigger_condition'), args=[ ('definition', 'text'), ], returns='text', volatility='stable', language='plpgsql', text=self.__class__.text) class NormalizeArrayIndexFunction(dbops.Function): """Convert an EdgeQL index to SQL index.""" text = ''' SELECT ( CASE WHEN index < 0 THEN length + index + 1 ELSE index + 1 END )::int ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_normalize_array_index'), args=[('index', ('bigint',)), ('length', ('int',))], returns=('int',), volatility='immutable', strict=True, text=self.text) class ArrayIndexWithBoundsFunction(dbops.Function): """Get an array element or raise an out-of-bounds exception.""" text = ''' SELECT edgedb.raise_on_null( val[edgedb._normalize_array_index(index, array_upper(val, 1))], 'array_subscript_error', msg => 'array index ' || index::text || ' is out of bounds', detail => detail ) ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_index'), args=[('val', ('anyarray',)), ('index', ('bigint',)), ('detail', ('text',))], returns=('anyelement',), # Same volatility as raise() volatility='stable', strict=True, text=self.text, ) class ArraySliceFunction(dbops.Function): """Get an array slice.""" text = ''' SELECT CASE WHEN start IS NULL THEN val[:edgedb._normalize_array_index( stop, array_upper(val, 1)) - 1] WHEN stop IS NULL THEN val[edgedb._normalize_array_index( start, array_upper(val, 1)):] ELSE val[edgedb._normalize_array_index( start, array_upper(val, 1)): edgedb._normalize_array_index( stop, array_upper(val, 1)) - 1] END ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_slice'), args=[('val', ('anyarray',)), ('start', ('bigint',)), ('stop', ('bigint',))], returns=('anyarray',), volatility='immutable', text=self.text, ) class StringIndexWithBoundsFunction(dbops.Function): """Get a string character or raise an out-of-bounds exception.""" text = ''' SELECT edgedb.raise_on_empty( substr( "val", edgedb._normalize_array_index("index", char_length("val")), 1 ), 'invalid_parameter_value', 'string index ' || "index"::text || ' is out of bounds', "detail" ) ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_index'), args=[ ('val', ('text',)), ('index', ('bigint',)), ('detail', ('text',)), ], returns=('text',), # Same volatility as raise_on_empty volatility='stable', strict=True, text=self.text, ) class BytesIndexWithBoundsFunction(dbops.Function): """Get a bytes character or raise an out-of-bounds exception.""" text = ''' SELECT edgedb.raise_on_empty( substr( "val", edgedb._normalize_array_index("index", length("val")), 1 ), 'invalid_parameter_value', 'byte string index ' || "index"::text || ' is out of bounds', "detail" ) ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_index'), args=[ ('val', ('bytea',)), ('index', ('bigint',)), ('detail', ('text',)), ], returns=('bytea',), # Same volatility as raise_on_empty volatility='stable', strict=True, text=self.text, ) class SubstrProxyFunction(dbops.Function): """Same as substr, but interpret negative length as 0 instead.""" text = r''' SELECT CASE WHEN length < 0 THEN '' ELSE substr(val, start::int, length) END ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_substr'), args=[('val', ('anyelement',)), ('start', ('bigint',)), ('length', ('int',))], returns=('anyelement',), volatility='immutable', strict=True, text=self.text) class LengthStringProxyFunction(dbops.Function): """Same as substr, but interpret negative length as 0 instead.""" text = r''' SELECT char_length(val) ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_length'), args=[('val', ('text',))], returns=('int',), volatility='immutable', strict=True, text=self.text) class LengthBytesProxyFunction(dbops.Function): """Same as substr, but interpret negative length as 0 instead.""" text = r''' SELECT length(val) ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_length'), args=[('val', ('bytea',))], returns=('int',), volatility='immutable', strict=True, text=self.text) class StringSliceImplFunction(dbops.Function): """Get a string slice.""" text = r''' SELECT CASE WHEN start IS NULL THEN edgedb._substr( val, 1, edgedb._normalize_array_index( stop, edgedb._length(val)) - 1 ) WHEN stop IS NULL THEN substr( val, edgedb._normalize_array_index( start, edgedb._length(val)) ) ELSE edgedb._substr( val, edgedb._normalize_array_index( start, edgedb._length(val)), edgedb._normalize_array_index( stop, edgedb._length(val)) - edgedb._normalize_array_index( start, edgedb._length(val)) ) END ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_str_slice'), args=[ ('val', ('anyelement',)), ('start', ('bigint',)), ('stop', ('bigint',)) ], returns=('anyelement',), volatility='immutable', text=self.text) class StringSliceFunction(dbops.Function): """Get a string slice.""" text = r''' SELECT edgedb._str_slice(val, start, stop) ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_slice'), args=[ ('val', ('text',)), ('start', ('bigint',)), ('stop', ('bigint',)) ], returns=('text',), volatility='immutable', text=self.text) class BytesSliceFunction(dbops.Function): """Get a string slice.""" text = r''' SELECT edgedb._str_slice(val, start, stop) ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_slice'), args=[ ('val', ('bytea',)), ('start', ('bigint',)), ('stop', ('bigint',)) ], returns=('bytea',), volatility='immutable', text=self.text) class JSONIndexByTextFunction(dbops.Function): """Get a JSON element by text index or raise an exception.""" text = r''' SELECT CASE jsonb_typeof(val) WHEN 'object' THEN ( edgedb.raise_on_null( val -> index, 'invalid_parameter_value', msg => ( 'json index ' || quote_literal(index) || ' is out of bounds' ), detail => detail ) ) WHEN 'array' THEN ( edgedb.raise( NULL::jsonb, 'wrong_object_type', msg => ( 'cannot index json ' || jsonb_typeof(val) || ' by ' || pg_typeof(index)::text ), detail => detail ) ) ELSE edgedb.raise( NULL::jsonb, 'wrong_object_type', msg => ( 'cannot index json ' || coalesce(jsonb_typeof(val), 'UNKNOWN') ), detail => detail ) END ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_index'), args=[ ('val', ('jsonb',)), ('index', ('text',)), ('detail', ('text',), "''"), ], returns=('jsonb',), # Same volatility as exception helpers volatility='stable', strict=True, text=self.text, ) class JSONIndexByIntFunction(dbops.Function): """Get a JSON element by int index or raise an exception.""" text = r''' SELECT CASE jsonb_typeof(val) WHEN 'object' THEN ( edgedb.raise( NULL::jsonb, 'wrong_object_type', msg => ( 'cannot index json ' || jsonb_typeof(val) || ' by ' || pg_typeof(index)::text ), detail => detail ) ) WHEN 'array' THEN ( edgedb.raise_on_null( val -> index::int, 'invalid_parameter_value', msg => 'json index ' || index::text || ' is out of bounds', detail => detail ) ) ELSE edgedb.raise( NULL::jsonb, 'wrong_object_type', msg => ( 'cannot index json ' || coalesce(jsonb_typeof(val), 'UNKNOWN') ), detail => detail ) END ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_index'), args=[ ('val', ('jsonb',)), ('index', ('bigint',)), ('detail', ('text',), "''"), ], returns=('jsonb',), # Min volatility of exception helpers and pg_typeof (stable). volatility='stable', strict=True, text=self.text, ) class JSONSliceFunction(dbops.Function): """Get a JSON array slice.""" text = r''' SELECT to_jsonb(_slice( ( SELECT array_agg(value) FROM jsonb_array_elements( edgedb.jsonb_assert_type(val, ARRAY['array'])) ), start, stop )) ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_slice'), args=[('val', ('jsonb',)), ('start', ('bigint',)), ('stop', ('bigint',))], returns=('jsonb',), # Same volatility as to_jsonb (stable) volatility='stable', text=self.text) # We need custom casting functions for various datetime scalars in # order to enforce correctness w.r.t. local vs time-zone-aware # datetime. Postgres does a lot of magic and guessing for time zones # and generally will accept text with or without time zone for any # particular flavor of timestamp. In order to guarantee that we can # detect time-zones we restrict the inputs to ISO8601 format. # # See issue #740. class DatetimeInFunction(dbops.Function): """Cast text into timestamptz using ISO8601 spec.""" text = r''' SELECT CASE WHEN val !~ ( '^\s*(' || '(\d{4}-\d{2}-\d{2}|\d{8})' || '[ tT]' || '(\d{2}(:\d{2}(:\d{2}(\.\d+)?)?)?|\d{2,6}(\.\d+)?)' || '([zZ]|[-+](\d{2,4}|\d{2}:\d{2}))' || ')\s*$' ) THEN edgedb.raise( NULL::edgedb.timestamptz_t, 'invalid_datetime_format', msg => ( 'invalid input syntax for type timestamptz: ' || quote_literal(val) ), detail => ( '{"hint":"Please use ISO8601 format. Example: ' || '2010-12-27T23:59:59-07:00 Alternatively ' || '\"to_datetime\" function provides custom ' || 'formatting options."}' ) ) ELSE val::edgedb.timestamptz_t END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'datetime_in'), args=[('val', ('text',))], returns=('edgedb', 'timestamptz_t'), # Same volatility as raise() (stable) volatility='stable', text=self.text) class DurationInFunction(dbops.Function): """Cast text into duration, ensuring there is no days or months units""" text = r''' SELECT CASE WHEN EXTRACT(MONTH FROM v.column1) != 0 OR EXTRACT(YEAR FROM v.column1) != 0 OR EXTRACT(DAY FROM v.column1) != 0 THEN edgedb.raise( NULL::edgedb.duration_t, 'invalid_datetime_format', msg => ( 'invalid input syntax for type std::duration: ' || quote_literal(val) ), detail => ( '{"hint":"Units bigger than days cannot be used ' || 'for std::duration."}' ) ) ELSE v.column1::edgedb.duration_t END FROM (VALUES ( val::interval )) AS v ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'duration_in'), args=[('val', ('text',))], returns=('edgedb', 'duration_t'), # Same volatility as raise() (stable) volatility='stable', text=self.text, ) class LocalDatetimeInFunction(dbops.Function): """Cast text into timestamp using ISO8601 spec.""" text = r''' SELECT CASE WHEN val !~ ( '^\s*(' || '(\d{4}-\d{2}-\d{2}|\d{8})' || '[ tT]' || '(\d{2}(:\d{2}(:\d{2}(\.\d+)?)?)?|\d{2,6}(\.\d+)?)' || ')\s*$' ) THEN edgedb.raise( NULL::edgedb.timestamp_t, 'invalid_datetime_format', msg => ( 'invalid input syntax for type timestamp: ' || quote_literal(val) ), detail => ( '{"hint":"Please use ISO8601 format. Example ' || '2010-04-18T09:27:00 Alternatively ' || '\"to_local_datetime\" function provides custom ' || 'formatting options."}' ) ) ELSE val::edgedb.timestamp_t END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'local_datetime_in'), args=[('val', ('text',))], returns=('edgedb', 'timestamp_t'), # Same volatility as raise() (stable) volatility='stable', text=self.text) class LocalDateInFunction(dbops.Function): """Cast text into date using ISO8601 spec.""" text = r''' SELECT CASE WHEN val !~ ( '^\s*(' || '(\d{4}-\d{2}-\d{2}|\d{8})' || ')\s*$' ) THEN edgedb.raise( NULL::edgedb.date_t, 'invalid_datetime_format', msg => ( 'invalid input syntax for type date: ' || quote_literal(val) ), detail => ( '{"hint":"Please use ISO8601 format. Example ' || '2010-04-18 Alternatively ' || '\"to_local_date\" function provides custom ' || 'formatting options."}' ) ) ELSE val::edgedb.date_t END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'local_date_in'), args=[('val', ('text',))], returns=('edgedb', 'date_t'), # Same volatility as raise() (stable) volatility='stable', text=self.text) class LocalTimeInFunction(dbops.Function): """Cast text into time using ISO8601 spec.""" text = r''' SELECT CASE WHEN val !~ ( '^\s*(' || '(\d{2}(:\d{2}(:\d{2}(\.\d+)?)?)?|\d{2,6}(\.\d+)?)' || ')\s*$' ) THEN edgedb.raise( NULL::time, 'invalid_datetime_format', msg => ( 'invalid input syntax for type time: ' || quote_literal(val) ), detail => ( '{"hint":"Please use ISO8601 format. Examples: ' || '18:43:27 or 18:43 Alternatively ' || '\"to_local_time\" function provides custom ' || 'formatting options."}' ) ) ELSE val::time END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'local_time_in'), args=[('val', ('text',))], returns=('time',), # Same volatility as raise() (stable) volatility='stable', text=self.text, ) class ToTimestampTZCheck(dbops.Function): """Checks if the original text has time zone or not.""" # What are we trying to mitigate? # We're trying to detect that when we're casting to datetime the # time zone is in fact present in the input. It is a problem if # it's not since then one gets assigned implicitly based on the # server settings. # # It is insufficient to rely on the presence of TZH in the format # string, since `to_timestamp` will happily ignore the missing # time-zone in the input anyway. So in order to tell whether the # input string contained a time zone that was in fact parsed we # employ the following trick: # # If the time zone is in the input then it is unambiguous and the # parsed value will not depend on the current server time zone. # However, if the time zone was omitted, then the parsed value # will default to the server time zone. This implies that if # changing the server time zone for the same input string affects # the parsed value, the input string itself didn't contain a time # zone. text = r''' DECLARE result timestamptz; chk timestamptz; msg text; BEGIN result := to_timestamp(val, fmt); PERFORM set_config('TimeZone', 'America/Toronto', true); chk := to_timestamp(val, fmt); -- We're deliberately not doing any save/restore because -- the server MUST be in UTC. In fact, this check relies -- on it. PERFORM set_config('TimeZone', 'UTC', true); IF hastz THEN msg := 'missing required'; ELSE msg := 'unexpected'; END IF; IF (result = chk) != hastz THEN RAISE EXCEPTION USING ERRCODE = 'invalid_datetime_format', MESSAGE = msg || ' time zone in input ' || quote_literal(val), DETAIL = ''; END IF; RETURN result::edgedb.timestamptz_t; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_to_timestamptz_check'), args=[('val', ('text',)), ('fmt', ('text',)), ('hastz', ('bool',))], returns=('edgedb', 'timestamptz_t'), # We're relying on changing settings, so it's volatile. volatility='volatile', language='plpgsql', text=self.text) class ToDatetimeFunction(dbops.Function): """Convert text into timestamptz using a formatting spec.""" # NOTE that if only the TZM (minutes) are mentioned it is not # enough for a valid time zone definition text = r''' SELECT CASE WHEN fmt !~ ( '^(' || '("([^"\\]|\\.)*")|' || '([^"]+)' || ')*(TZH).*$' ) THEN edgedb.raise( NULL::edgedb.timestamptz_t, 'invalid_datetime_format', msg => ( 'missing required time zone in format: ' || quote_literal(fmt) ), detail => ( $h${"hint":"Use one or both of the following: $h$ || $h$'TZH', 'TZM'"}$h$ ) ) ELSE edgedb._to_timestamptz_check(val, fmt, true) END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'to_datetime'), args=[('val', ('text',)), ('fmt', ('text',))], returns=('edgedb', 'timestamptz_t'), # Same as _to_timestamptz_check. volatility='volatile', text=self.text) class ToLocalDatetimeFunction(dbops.Function): """Convert text into timestamp using a formatting spec.""" # NOTE time zone should not be mentioned at all. text = r''' SELECT CASE WHEN fmt ~ ( '^(' || '("([^"\\]|\\.)*")|' || '([^"]+)' || ')*(TZH|TZM).*$' ) THEN edgedb.raise( NULL::edgedb.timestamp_t, 'invalid_datetime_format', msg => ( 'unexpected time zone in format: ' || quote_literal(fmt) ) ) ELSE edgedb._to_timestamptz_check(val, fmt, false) ::edgedb.timestamp_t END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'to_local_datetime'), args=[('val', ('text',)), ('fmt', ('text',))], returns=('edgedb', 'timestamp_t'), # Same as _to_timestamptz_check. volatility='volatile', text=self.text) class StrToBool(dbops.Function): """Parse bool from text.""" # We first try to match case-insensitive "true|false" at all. On # null, we raise an exception. But otherwise we know that we have # an array of matches. The first element matching "true" and # second - "false". So the boolean value is then "true" if the # second array element is NULL and false otherwise. text = r''' SELECT ( coalesce( regexp_match(val, '^\s*(?:(true)|(false))\s*$', 'i')::text[], edgedb.raise( NULL::text[], 'invalid_text_representation', msg => 'invalid syntax for bool: ' || quote_literal(val) ) ) )[2] IS NULL; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'str_to_bool'), args=[('val', ('text',))], returns=('bool',), # Stable because it's raising exceptions. volatility='stable', text=self.text) class QuoteLiteralFunction(dbops.Function): """Encode string as edgeql literal quoted string""" text = r''' SELECT concat('\'', replace( replace(val, '\\', '\\\\'), '\'', '\\\''), '\'') ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'quote_literal'), args=[('val', ('text',))], returns=('str',), volatility='immutable', text=self.text) class QuoteIdentFunction(dbops.Function): """Quote ident function.""" # TODO do not quote valid identifiers unless they are reserved text = r''' SELECT concat('`', replace(val, '`', '``'), '`') ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'quote_ident'), args=[('val', ('text',))], returns=('text',), volatility='immutable', text=self.text, ) class QuoteNameFunction(dbops.Function): text = r""" SELECT string_agg(edgedb.quote_ident(np), '::') FROM unnest(string_to_array("name", '::')) AS np """ def __init__(self) -> None: super().__init__( name=('edgedb', 'quote_name'), args=[('name', ('text',))], returns=('text',), volatility='immutable', text=self.text, ) class DescribeRolesAsDDLFunctionForwardDecl(dbops.Function): """Forward declaration for _describe_roles_as_ddl""" def __init__(self) -> None: super().__init__( name=('edgedb', '_describe_roles_as_ddl'), args=[], returns=('text'), # Stable because it's raising exceptions. volatility='stable', text='SELECT NULL::text', ) class DescribeRolesAsDDLFunction(dbops.Function): """Describe roles as DDL""" def __init__(self, schema: s_schema.Schema) -> None: role_obj = schema.get("sys::Role", type=s_objtypes.ObjectType) roles = inhviewname(schema, role_obj) member_of = role_obj.getptr(schema, s_name.UnqualName('member_of')) members = inhviewname(schema, member_of) name_col = ptr_col_name(schema, role_obj, 'name') pass_col = ptr_col_name(schema, role_obj, 'password') qi_superuser = qlquote.quote_ident(defines.EDGEDB_SUPERUSER) text = f""" WITH RECURSIVE dependencies AS ( SELECT r.id AS id, m.target AS parent FROM {q(*roles)} r LEFT OUTER JOIN {q(*members)} m ON r.id = m.source ), roles_with_depths(id, depth) AS ( SELECT id, 0 FROM dependencies WHERE parent IS NULL UNION ALL SELECT dependencies.id, roles_with_depths.depth + 1 FROM dependencies INNER JOIN roles_with_depths ON dependencies.parent = roles_with_depths.id ), ordered_roles AS ( SELECT id, max(depth) FROM roles_with_depths GROUP BY id ORDER BY max(depth) ASC ) SELECT coalesce(string_agg( CASE WHEN role.{qi(name_col)} = { ql(defines.EDGEDB_SUPERUSER) } THEN NULLIF(concat( 'ALTER ROLE { qi_superuser } {{', NULLIF((SELECT concat( ' EXTENDING ', string_agg( edgedb.quote_ident(parent.{qi(name_col)}), ', ' ), ';' ) FROM {q(*members)} member INNER JOIN {q(*roles)} parent ON parent.id = member.target WHERE member.source = role.id ), ' EXTENDING ;'), CASE WHEN role.{qi(pass_col)} IS NOT NULL THEN concat(' SET password_hash := ', quote_literal(role.{qi(pass_col)}), ';') ELSE '' END, '}};' ), 'ALTER ROLE { qi_superuser } {{}};') ELSE concat( 'CREATE SUPERUSER ROLE ', edgedb.quote_ident(role.{qi(name_col)}), NULLIF((SELECT concat(' EXTENDING ', string_agg( edgedb.quote_ident(parent.{qi(name_col)}), ', ' ) ) FROM {q(*members)} member INNER JOIN {q(*roles)} parent ON parent.id = member.target WHERE member.source = role.id ), ' EXTENDING '), CASE WHEN role.{qi(pass_col)} IS NOT NULL THEN concat(' {{ SET password_hash := ', quote_literal(role.{qi(pass_col)}), '}};') ELSE ';' END ) END, '\n' ), '') str FROM ordered_roles JOIN {q(*roles)} role ON role.id = ordered_roles.id """ super().__init__( name=('edgedb', '_describe_roles_as_ddl'), args=[], returns=('text'), # Stable because it's raising exceptions. volatility='stable', text=text) class DescribeSystemConfigAsDDLFunctionForwardDecl(dbops.Function): def __init__(self) -> None: super().__init__( name=('edgedb', '_describe_system_config_as_ddl'), args=[], returns=('text'), volatility='stable', text='SELECT NULL::text', ) class DescribeDatabaseConfigAsDDLFunctionForwardDecl(dbops.Function): def __init__(self) -> None: super().__init__( name=('edgedb', '_describe_database_config_as_ddl'), args=[], returns=('text'), volatility='stable', text='SELECT NULL::text', ) class DumpSequencesFunction(dbops.Function): text = r""" SELECT string_agg( 'SELECT std::sequence_reset(' || 'INTROSPECT ' || edgedb.quote_name(seq.name) || (CASE WHEN seq_st.is_called THEN ', ' || seq_st.last_value::text ELSE '' END) || ');', E'\n' ) FROM (SELECT id, name FROM edgedb."_SchemaScalarType" WHERE id = any("seqs") ) AS seq, LATERAL ( SELECT COALESCE(last_value, start_value)::text AS last_value, last_value IS NOT NULL AS is_called FROM pg_sequences, LATERAL ROWS FROM ( edgedb.get_sequence_backend_name(seq.id) ) AS seq_name(schema text, name text) WHERE (pg_sequences.schemaname, pg_sequences.sequencename) = (seq_name.schema, seq_name.name) ) AS seq_st """ def __init__(self) -> None: super().__init__( name=('edgedb', '_dump_sequences'), args=[('seqs', ('uuid[]',))], returns=('text',), # Volatile because sequence state is volatile volatility='volatile', text=self.text, ) class SysConfigSourceType(dbops.Enum): def __init__(self) -> None: super().__init__( name=('edgedb', '_sys_config_source_t'), values=[ 'default', 'postgres default', 'postgres environment variable', 'postgres configuration file', 'postgres command line', 'postgres global', 'system override', 'database', 'postgres client', 'postgres override', 'postgres interactive', 'postgres test', 'session', ] ) class SysConfigScopeType(dbops.Enum): def __init__(self) -> None: super().__init__( name=('edgedb', '_sys_config_scope_t'), values=[ 'SYSTEM', 'DATABASE', 'SESSION', ] ) class SysConfigValueType(dbops.CompositeType): """Type of values returned by _read_sys_config.""" def __init__(self) -> None: super().__init__(name=('edgedb', '_sys_config_val_t')) self.add_columns([ dbops.Column(name='name', type='text'), dbops.Column(name='value', type='jsonb'), dbops.Column(name='source', type='edgedb._sys_config_source_t'), dbops.Column(name='scope', type='edgedb._sys_config_scope_t'), ]) class SysConfigFullFunction(dbops.Function): # This is a function because "_edgecon_state" is a temporary table # and therefore cannot be used in a view. text = f''' BEGIN RETURN QUERY EXECUTE $$ WITH config_spec AS ( SELECT s.key AS name, s.value->'default' AS default, (s.value->>'internal')::bool AS internal, (s.value->>'system')::bool AS system, (s.value->>'typeid')::uuid AS typeid, (s.value->>'typemod') AS typemod, (s.value->>'backend_setting') AS backend_setting FROM jsonb_each( (SELECT json FROM edgedbinstdata.instdata WHERE key = 'configspec') ) AS s ), config_defaults AS ( SELECT s.name AS name, s.default AS value, 'default' AS source FROM config_spec s ), config_sys AS ( SELECT s.key AS name, s.value AS value, 'system override' AS source FROM jsonb_each( edgedb.get_database_metadata( {ql(defines.EDGEDB_SYSTEM_DB)} ) -> 'sysconfig' ) AS s ), config_db AS ( SELECT s.name AS name, s.value AS value, 'database' AS source FROM edgedb._db_config s ), config_sess AS ( SELECT s.name AS name, s.value AS value, 'session' AS source FROM _edgecon_state s WHERE s.type = 'C' ), pg_db_setting AS ( SELECT nameval.name, to_jsonb(nameval.value) AS value, 'database' AS source FROM (SELECT setconfig FROM pg_db_role_setting WHERE setdatabase = ( SELECT oid FROM pg_database WHERE datname = current_database() ) AND setrole = 0 ) AS cfg_array, LATERAL unnest(cfg_array.setconfig) AS cfg_set(s), LATERAL ( SELECT split_part(cfg_set.s, '=', 1) AS name, split_part(cfg_set.s, '=', 2) AS value ) AS nameval, LATERAL ( SELECT config_spec.name FROM config_spec WHERE nameval.name = config_spec.backend_setting ) AS spec ), pg_conf_settings AS ( SELECT spec.name, to_jsonb(setting) AS value, 'postgres configuration file' AS source FROM pg_file_settings, LATERAL ( SELECT config_spec.name FROM config_spec WHERE pg_file_settings.name = config_spec.backend_setting ) AS spec WHERE sourcefile != (( SELECT setting FROM pg_settings WHERE name = 'data_directory' ) || '/postgresql.auto.conf') AND applied ), pg_auto_conf_settings AS ( SELECT spec.name, to_jsonb(setting) AS value, 'system override' AS source FROM pg_file_settings, LATERAL ( SELECT config_spec.name FROM config_spec WHERE pg_file_settings.name = config_spec.backend_setting ) AS spec WHERE sourcefile = (( SELECT setting FROM pg_settings WHERE name = 'data_directory' ) || '/postgresql.auto.conf') AND applied ), pg_config AS ( SELECT spec.name, to_jsonb( CASE WHEN u.v[1] IS NOT NULL THEN (settings.setting::int * (u.v[1])::int)::text || u.v[2] ELSE settings.setting || COALESCE(settings.unit, '') END ) AS value, source AS source FROM ( SELECT pg_settings.name AS name, pg_settings.unit AS unit, pg_settings.setting AS setting, (CASE WHEN pg_settings.source IN ('session', 'database') THEN pg_settings.source ELSE 'postgres ' || pg_settings.source END) AS source FROM pg_settings ) AS settings, LATERAL ( SELECT regexp_match(settings.unit, '(\\d+)(\\w+)') AS v ) AS u, LATERAL ( SELECT config_spec.name FROM config_spec WHERE settings.name = config_spec.backend_setting ) AS spec ) SELECT q.name, q.value, q.source, (CASE WHEN q.source < 'database'::edgedb._sys_config_source_t THEN 'SYSTEM' WHEN q.source = 'database'::edgedb._sys_config_source_t THEN 'DATABASE' ELSE 'SESSION' END)::edgedb._sys_config_scope_t AS scope FROM (SELECT u.name, u.value, u.source::edgedb._sys_config_source_t, row_number() OVER ( PARTITION BY u.name ORDER BY u.source::edgedb._sys_config_source_t DESC ) AS n FROM (SELECT * FROM ( SELECT * FROM config_defaults UNION ALL SELECT * FROM config_sys UNION ALL SELECT * FROM config_db UNION ALL SELECT * FROM config_sess UNION ALL SELECT * FROM pg_db_setting UNION ALL SELECT * FROM pg_conf_settings UNION ALL SELECT * FROM pg_auto_conf_settings UNION ALL SELECT * FROM pg_config ) AS q WHERE ($1 IS NULL OR q.source::edgedb._sys_config_source_t = any($1)) AND ($2 IS NULL OR q.source::edgedb._sys_config_source_t <= $2) ) AS u ) AS q WHERE q.n = 1; $$ USING source_filter, max_source; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_read_sys_config_full'), args=[ ( 'source_filter', ('edgedb', '_sys_config_source_t[]',), 'NULL', ), ( 'max_source', ('edgedb', '_sys_config_source_t'), 'NULL', ), ], returns=('edgedb', '_sys_config_val_t'), set_returning=True, language='plpgsql', volatility='volatile', text=self.text, ) class SysConfigNoFileAccessFunction(dbops.Function): text = f''' BEGIN RETURN QUERY EXECUTE $$ WITH config_spec AS ( SELECT s.key AS name, s.value->'default' AS default, (s.value->>'internal')::bool AS internal, (s.value->>'system')::bool AS system, (s.value->>'typeid')::uuid AS typeid, (s.value->>'typemod') AS typemod, (s.value->>'backend_setting') AS backend_setting FROM jsonb_each( (SELECT json FROM edgedbinstdata.instdata WHERE key = 'configspec') ) AS s ), config_defaults AS ( SELECT s.name AS name, s.default AS value, 'default' AS source FROM config_spec s ), config_sys AS ( SELECT s.key AS name, s.value AS value, 'system override' AS source FROM jsonb_each( edgedb.get_database_metadata( {ql(defines.EDGEDB_SYSTEM_DB)} ) -> 'sysconfig' ) AS s ), config_db AS ( SELECT s.name AS name, s.value AS value, 'database' AS source FROM edgedb._db_config s ), config_sess AS ( SELECT s.name AS name, s.value AS value, 'session' AS source FROM _edgecon_state s WHERE s.type = 'C' ), pg_db_setting AS ( SELECT nameval.name, to_jsonb(nameval.value) AS value, 'database' AS source FROM (SELECT setconfig FROM pg_db_role_setting WHERE setdatabase = ( SELECT oid FROM pg_database WHERE datname = current_database() ) AND setrole = 0 ) AS cfg_array, LATERAL unnest(cfg_array.setconfig) AS cfg_set(s), LATERAL ( SELECT split_part(cfg_set.s, '=', 1) AS name, split_part(cfg_set.s, '=', 2) AS value ) AS nameval, LATERAL ( SELECT config_spec.name FROM config_spec WHERE nameval.name = config_spec.backend_setting ) AS spec ), pg_config AS ( SELECT spec.name, to_jsonb( CASE WHEN u.v[1] IS NOT NULL THEN (settings.setting::int * (u.v[1])::int)::text || u.v[2] ELSE settings.setting || COALESCE(settings.unit, '') END ) AS value, source AS source FROM ( SELECT pg_settings.name AS name, pg_settings.unit AS unit, pg_settings.setting AS setting, (CASE WHEN pg_settings.source IN ('session', 'database') THEN pg_settings.source ELSE 'postgres ' || pg_settings.source END) AS source FROM pg_settings ) AS settings, LATERAL ( SELECT regexp_match(settings.unit, '(\\d+)(\\w+)') AS v ) AS u, LATERAL ( SELECT config_spec.name FROM config_spec WHERE settings.name = config_spec.backend_setting ) AS spec ) SELECT q.name, q.value, q.source, (CASE WHEN q.source < 'database'::edgedb._sys_config_source_t THEN 'SYSTEM' WHEN q.source = 'database'::edgedb._sys_config_source_t THEN 'DATABASE' ELSE 'SESSION' END)::edgedb._sys_config_scope_t AS scope FROM (SELECT u.name, u.value, u.source::edgedb._sys_config_source_t, row_number() OVER ( PARTITION BY u.name ORDER BY u.source::edgedb._sys_config_source_t DESC ) AS n FROM (SELECT * FROM ( SELECT * FROM config_defaults UNION ALL SELECT * FROM config_sys UNION ALL SELECT * FROM config_db UNION ALL SELECT * FROM config_sess UNION ALL SELECT * FROM pg_db_setting UNION ALL SELECT * FROM pg_config ) AS q WHERE ($1 IS NULL OR q.source::edgedb._sys_config_source_t = any($1)) AND ($2 IS NULL OR q.source::edgedb._sys_config_source_t <= $2) ) AS u ) AS q WHERE q.n = 1; $$ USING source_filter, max_source; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_read_sys_config_no_file_access'), args=[ ( 'source_filter', ('edgedb', '_sys_config_source_t[]',), 'NULL', ), ( 'max_source', ('edgedb', '_sys_config_source_t'), 'NULL', ), ], returns=('edgedb', '_sys_config_val_t'), set_returning=True, language='plpgsql', volatility='volatile', text=self.text, ) class SysConfigFunction(dbops.Function): text = f''' DECLARE backend_caps bigint; BEGIN backend_caps := edgedb.get_backend_capabilities(); IF (backend_caps & {int(pgcluster.BackendCapabilities.CONFIGFILE_ACCESS)}) != 0 THEN RETURN QUERY SELECT * FROM edgedb._read_sys_config_full(source_filter, max_source); ELSE RETURN QUERY SELECT * FROM edgedb._read_sys_config_no_file_access(source_filter, max_source); END IF; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_read_sys_config'), args=[ ( 'source_filter', ('edgedb', '_sys_config_source_t[]',), 'NULL', ), ( 'max_source', ('edgedb', '_sys_config_source_t'), 'NULL', ), ], returns=('edgedb', '_sys_config_val_t'), set_returning=True, language='plpgsql', volatility='volatile', text=self.text, ) class SysVersionFunction(dbops.Function): text = f''' BEGIN RETURN ( SELECT value FROM _edgecon_state WHERE name = 'server_version' AND type = 'R' ); END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_sys_version'), args=[], returns=('jsonb',), language='plpgsql', volatility='stable', text=self.text, ) class SysGetTransactionIsolation(dbops.Function): "Get transaction isolation value as text compatible with EdgeDB's enum." text = r''' SELECT CASE setting WHEN 'repeatable read' THEN 'RepeatableRead' WHEN 'serializable' THEN 'Serializable' ELSE ( SELECT edgedb.raise( NULL::text, msg => ( 'unknown transaction isolation level "' || setting || '"' ) ) ) END FROM pg_settings WHERE name = 'transaction_isolation' ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_get_transaction_isolation'), args=[], returns=('text',), # This function only reads from a table. volatility='stable', text=self.text) class GetCachedReflection(dbops.Function): "Return a list of existing schema reflection helpers." text = ''' SELECT substring(proname, '__rh_#"%#"', '#') AS eql_hash, proargnames AS argnames FROM pg_proc INNER JOIN pg_namespace ON (pronamespace = pg_namespace.oid) WHERE proname LIKE '\\_\\_rh\\_%' ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_get_cached_reflection'), args=[], returns=('record',), set_returning=True, # This function only reads from a table. volatility='stable', text=self.text, ) class GetBaseScalarTypeMap(dbops.Function): """Return a map of base EdgeDB scalar type ids to Postgres type names.""" text = f''' VALUES {", ".join( f"""( {ql(str(k))}::uuid, { ql(f'{v[0]}.{v[1]}') if len(v) == 2 else ql(f'pg_catalog.{v[0]}') } )""" for k, v in types.base_type_name_map.items())} ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_get_base_scalar_type_map'), args=[], returns=('record',), set_returning=True, volatility='immutable', text=self.text, ) class GetPgTypeForEdgeDBTypeFunction(dbops.Function): """Return Postgres OID representing a given EdgeDB type.""" text = f''' SELECT coalesce( ( SELECT tn::regtype::oid FROM edgedb._get_base_scalar_type_map() AS m(tid uuid, tn text) WHERE m.tid = "typeid" ), ( SELECT typ.oid FROM pg_catalog.pg_type typ WHERE typ.typname = "typeid"::text || '_domain' OR typ.typname = "typeid"::text || '_t' ), ( SELECT typ.typarray FROM pg_catalog.pg_type typ WHERE typ.typname = "elemid"::text || '_domain' OR typ.typname = "elemid"::text || '_t' OR typ.oid = ( SELECT tn::regtype::oid FROM edgedb._get_base_scalar_type_map() AS m(tid uuid, tn text) WHERE tid = elemid ) ), edgedb.raise( NULL::bigint, 'invalid_parameter_value', msg => ( format( 'cannot determine OID of EdgeDB type %L', typeid::text ) ) ) )::bigint ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_pg_type_for_edgedb_type'), args=[ ('typeid', ('uuid',)), ('elemid', ('uuid',)), ], returns=('bigint',), volatility='stable', text=self.text, ) async def bootstrap(conn: asyncpg.Connection) -> None: commands = dbops.CommandGroup() commands.add_commands([ dbops.CreateSchema(name='edgedb'), dbops.CreateSchema(name='edgedbss'), dbops.CreateSchema(name='edgedbpub'), dbops.CreateSchema(name='edgedbstd'), dbops.CreateCompositeType(ExpressionType()), dbops.CreateTable(DBConfigTable()), dbops.CreateFunction(QuoteIdentFunction()), dbops.CreateFunction(QuoteNameFunction()), dbops.CreateFunction(AlterCurrentDatabaseSetString()), dbops.CreateFunction(AlterCurrentDatabaseSetStringArray()), dbops.CreateFunction(AlterCurrentDatabaseSetNonArray()), dbops.CreateFunction(AlterCurrentDatabaseSetArray()), dbops.CreateFunction(GetBackendCapabilitiesFunction()), dbops.CreateFunction(GetBackendTenantIDFunction()), dbops.CreateFunction(GetDatabaseBackendNameFunction()), dbops.CreateFunction(GetRoleBackendNameFunction()), dbops.CreateFunction(GetUserSequenceBackendNameFunction()), dbops.CreateFunction(GetStdModulesFunction()), dbops.CreateFunction(GetObjectMetadata()), dbops.CreateFunction(GetColumnMetadata()), dbops.CreateFunction(GetSharedObjectMetadata()), dbops.CreateFunction(GetDatabaseMetadataFunction()), dbops.CreateFunction(GetCurrentDatabaseFunction()), dbops.CreateFunction(RaiseExceptionFunction()), dbops.CreateFunction(RaiseExceptionOnNullFunction()), dbops.CreateFunction(RaiseExceptionOnNotNullFunction()), dbops.CreateFunction(RaiseExceptionOnEmptyStringFunction()), dbops.CreateFunction(AssertJSONTypeFunction()), dbops.CreateFunction(ExtractJSONScalarFunction()), dbops.CreateFunction(NormalizeNameFunction()), dbops.CreateFunction(GetNameModuleFunction()), dbops.CreateFunction(NullIfArrayNullsFunction()), dbops.CreateCompositeType(IndexDescType()), dbops.CreateFunction(IntrospectIndexesFunction()), dbops.CreateCompositeType(TriggerDescType()), dbops.CreateFunction(IntrospectTriggersFunction()), dbops.CreateCompositeType(TableInheritanceDescType()), dbops.CreateDomain(BigintDomain()), dbops.CreateDomain(TimestampTzDomain()), dbops.CreateDomain(TimestampDomain()), dbops.CreateDomain(DateDomain()), dbops.CreateDomain(DurationDomain()), dbops.CreateDomain(RelativeDurationDomain()), dbops.CreateFunction(StrToBigint()), dbops.CreateFunction(StrToDecimal()), dbops.CreateFunction(StrToInt64NoInline()), dbops.CreateFunction(StrToInt32NoInline()), dbops.CreateFunction(StrToInt16NoInline()), dbops.CreateFunction(StrToFloat64NoInline()), dbops.CreateFunction(StrToFloat32NoInline()), dbops.CreateFunction(GetTableDescendantsFunction()), dbops.CreateFunction(ParseTriggerConditionFunction()), dbops.CreateFunction(NormalizeArrayIndexFunction()), dbops.CreateFunction(ArrayIndexWithBoundsFunction()), dbops.CreateFunction(ArraySliceFunction()), dbops.CreateFunction(StringIndexWithBoundsFunction()), dbops.CreateFunction(LengthStringProxyFunction()), dbops.CreateFunction(LengthBytesProxyFunction()), dbops.CreateFunction(SubstrProxyFunction()), dbops.CreateFunction(StringSliceImplFunction()), dbops.CreateFunction(StringSliceFunction()), dbops.CreateFunction(BytesSliceFunction()), dbops.CreateFunction(JSONIndexByTextFunction()), dbops.CreateFunction(JSONIndexByIntFunction()), dbops.CreateFunction(JSONSliceFunction()), dbops.CreateFunction(DatetimeInFunction()), dbops.CreateFunction(DurationInFunction()), dbops.CreateFunction(LocalDatetimeInFunction()), dbops.CreateFunction(LocalDateInFunction()), dbops.CreateFunction(LocalTimeInFunction()), dbops.CreateFunction(ToTimestampTZCheck()), dbops.CreateFunction(ToDatetimeFunction()), dbops.CreateFunction(ToLocalDatetimeFunction()), dbops.CreateFunction(StrToBool()), dbops.CreateFunction(BytesIndexWithBoundsFunction()), dbops.CreateEnum(SysConfigSourceType()), dbops.CreateEnum(SysConfigScopeType()), dbops.CreateCompositeType(SysConfigValueType()), dbops.CreateFunction(SysConfigFullFunction()), dbops.CreateFunction(SysConfigNoFileAccessFunction()), dbops.CreateFunction(SysConfigFunction()), dbops.CreateFunction(SysVersionFunction()), dbops.CreateFunction(SysGetTransactionIsolation()), dbops.CreateFunction(GetCachedReflection()), dbops.CreateFunction(GetBaseScalarTypeMap()), dbops.CreateFunction(GetPgTypeForEdgeDBTypeFunction()), dbops.CreateFunction(DescribeSystemConfigAsDDLFunctionForwardDecl()), dbops.CreateFunction(DescribeDatabaseConfigAsDDLFunctionForwardDecl()), dbops.CreateFunction(DescribeRolesAsDDLFunctionForwardDecl()), ]) block = dbops.PLTopBlock() commands.generate(block) await _execute_block(conn, block) async def create_pg_extensions(conn: asyncpg.Connection) -> None: commands = dbops.CommandGroup() commands.add_commands([ dbops.CreateSchema(name='edgedbext'), dbops.CreateExtension( dbops.Extension(name='uuid-ossp', schema='edgedbext'), ), ]) block = dbops.PLTopBlock() commands.generate(block) await _execute_block(conn, block) classref_attr_aliases = { 'links': 'pointers', 'link_properties': 'pointers' } def tabname(schema: s_schema.Schema, obj: s_obj.Object) -> Tuple[str, str]: return ( 'edgedbss', common.get_backend_name( schema, obj, aspect='table', catenate=False, )[1], ) def inhviewname(schema: s_schema.Schema, obj: s_obj.Object) -> Tuple[str, str]: return ( 'edgedbss', common.get_backend_name( schema, obj, aspect='inhview', catenate=False, )[1], ) def ptr_col_name( schema: s_schema.Schema, obj: s_sources.Source, propname: str, ) -> str: prop = obj.getptr(schema, s_name.UnqualName(propname)) psi = types.get_pointer_storage_info(prop, schema=schema) return psi.column_name # type: ignore[no-any-return] def _generate_database_views(schema: s_schema.Schema) -> List[dbops.View]: Database = schema.get('sys::Database', type=s_objtypes.ObjectType) annos = Database.getptr( schema, s_name.UnqualName('annotations'), type=s_links.Link) int_annos = Database.getptr( schema, s_name.UnqualName('annotations__internal'), type=s_links.Link) view_query = f''' SELECT ((d.description)->>'id')::uuid AS {qi(ptr_col_name(schema, Database, 'id'))}, (SELECT id FROM edgedb."_SchemaObjectType" WHERE name = 'sys::Database') AS {qi(ptr_col_name(schema, Database, '__type__'))}, (datname IN ( edgedb.get_database_backend_name( {ql(defines.EDGEDB_TEMPLATE_DB)}), edgedb.get_database_backend_name( {ql(defines.EDGEDB_SYSTEM_DB)}) )) AS {qi(ptr_col_name(schema, Database, 'internal'))}, (d.description)->>'name' AS {qi(ptr_col_name(schema, Database, 'name'))}, (d.description)->>'name' AS {qi(ptr_col_name(schema, Database, 'name__internal'))}, ARRAY[]::text[] AS {qi(ptr_col_name(schema, Database, 'computed_fields'))}, ((d.description)->>'builtin')::bool AS {qi(ptr_col_name(schema, Database, 'builtin'))} FROM pg_database dat CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(dat.oid, 'pg_database') AS description ) AS d WHERE (d.description)->>'id' IS NOT NULL AND (d.description)->>'tenant_id' = edgedb.get_backend_tenant_id() ''' annos_link_query = f''' SELECT ((d.description)->>'id')::uuid AS {qi(ptr_col_name(schema, annos, 'source'))}, (annotations->>'id')::uuid AS {qi(ptr_col_name(schema, annos, 'target'))}, (annotations->>'value')::text AS {qi(ptr_col_name(schema, annos, 'value'))}, (annotations->>'owned')::bool AS {qi(ptr_col_name(schema, annos, 'owned'))} FROM pg_database dat CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(dat.oid, 'pg_database') AS description ) AS d CROSS JOIN LATERAL ROWS FROM ( jsonb_array_elements((d.description)->'annotations') ) AS annotations ''' int_annos_link_query = f''' SELECT ((d.description)->>'id')::uuid AS {qi(ptr_col_name(schema, int_annos, 'source'))}, (annotations->>'id')::uuid AS {qi(ptr_col_name(schema, int_annos, 'target'))}, (annotations->>'owned')::bool AS {qi(ptr_col_name(schema, int_annos, 'owned'))} FROM pg_database dat CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(dat.oid, 'pg_database') AS description ) AS d CROSS JOIN LATERAL ROWS FROM ( jsonb_array_elements( (d.description)->'annotations__internal' ) ) AS annotations ''' objects = { Database: view_query, annos: annos_link_query, int_annos: int_annos_link_query, } views = [] for obj, query in objects.items(): tabview = dbops.View(name=tabname(schema, obj), query=query) inhview = dbops.View(name=inhviewname(schema, obj), query=query) views.append(tabview) views.append(inhview) return views def _generate_extension_views(schema: s_schema.Schema) -> List[dbops.View]: ExtPkg = schema.get('sys::ExtensionPackage', type=s_objtypes.ObjectType) annos = ExtPkg.getptr( schema, s_name.UnqualName('annotations'), type=s_links.Link) int_annos = ExtPkg.getptr( schema, s_name.UnqualName('annotations__internal'), type=s_links.Link) ver = ExtPkg.getptr( schema, s_name.UnqualName('version'), type=s_props.Property) ver_t = common.get_backend_name( schema, ver.get_target(schema), catenate=False, ) view_query = f''' SELECT (e.value->>'id')::uuid AS {qi(ptr_col_name(schema, ExtPkg, 'id'))}, (SELECT id FROM edgedb."_SchemaObjectType" WHERE name = 'sys::ExtensionPackage') AS {qi(ptr_col_name(schema, ExtPkg, '__type__'))}, (e.value->>'name') AS {qi(ptr_col_name(schema, ExtPkg, 'name'))}, (e.value->>'name__internal') AS {qi(ptr_col_name(schema, ExtPkg, 'name__internal'))}, ( (e.value->'version'->>'major')::int, (e.value->'version'->>'minor')::int, (e.value->'version'->>'stage')::text, (e.value->'version'->>'stage_no')::int, COALESCE( (SELECT array_agg(q.v::text) FROM jsonb_array_elements( e.value->'version'->'local' ) AS q(v)), ARRAY[]::text[] ) )::{qt(ver_t)} AS {qi(ptr_col_name(schema, ExtPkg, 'version'))}, (e.value->>'script') AS {qi(ptr_col_name(schema, ExtPkg, 'script'))}, ARRAY[]::text[] AS {qi(ptr_col_name(schema, ExtPkg, 'computed_fields'))}, (e.value->>'builtin')::bool AS {qi(ptr_col_name(schema, ExtPkg, 'builtin'))}, (e.value->>'internal')::bool AS {qi(ptr_col_name(schema, ExtPkg, 'internal'))} FROM jsonb_each( edgedb.get_database_metadata( {ql(defines.EDGEDB_TEMPLATE_DB)} ) -> 'ExtensionPackage' ) AS e ''' annos_link_query = f''' SELECT (e.value->>'id')::uuid AS {qi(ptr_col_name(schema, annos, 'source'))}, (annotations->>'id')::uuid AS {qi(ptr_col_name(schema, annos, 'target'))}, (annotations->>'value')::text AS {qi(ptr_col_name(schema, annos, 'value'))}, (annotations->>'is_owned')::bool AS {qi(ptr_col_name(schema, annos, 'owned'))} FROM jsonb_each( edgedb.get_database_metadata( {ql(defines.EDGEDB_TEMPLATE_DB)} ) -> 'ExtensionPackage' ) AS e CROSS JOIN LATERAL ROWS FROM ( jsonb_array_elements(e.value->'annotations') ) AS annotations ''' int_annos_link_query = f''' SELECT (e.value->>'id')::uuid AS {qi(ptr_col_name(schema, int_annos, 'source'))}, (annotations->>'id')::uuid AS {qi(ptr_col_name(schema, int_annos, 'target'))}, (annotations->>'is_owned')::bool AS {qi(ptr_col_name(schema, int_annos, 'owned'))} FROM jsonb_each( edgedb.get_database_metadata( {ql(defines.EDGEDB_TEMPLATE_DB)} ) -> 'ExtensionPackage' ) AS e CROSS JOIN LATERAL ROWS FROM ( jsonb_array_elements(e.value->'annotations__internal') ) AS annotations ''' objects = { ExtPkg: view_query, annos: annos_link_query, int_annos: int_annos_link_query, } views = [] for obj, query in objects.items(): tabview = dbops.View(name=tabname(schema, obj), query=query) inhview = dbops.View(name=inhviewname(schema, obj), query=query) views.append(tabview) views.append(inhview) return views def _generate_role_views(schema: s_schema.Schema) -> List[dbops.View]: Role = schema.get('sys::Role', type=s_objtypes.ObjectType) member_of = Role.getptr( schema, s_name.UnqualName('member_of'), type=s_links.Link) bases = Role.getptr( schema, s_name.UnqualName('bases'), type=s_links.Link) ancestors = Role.getptr( schema, s_name.UnqualName('ancestors'), type=s_links.Link) annos = Role.getptr( schema, s_name.UnqualName('annotations'), type=s_links.Link) int_annos = Role.getptr( schema, s_name.UnqualName('annotations__internal'), type=s_links.Link) superuser = f''' a.rolsuper OR EXISTS ( SELECT FROM pg_auth_members m INNER JOIN pg_catalog.pg_roles g ON (m.roleid = g.oid) WHERE m.member = a.oid AND g.rolname = {ql(defines.EDGEDB_SUPERGROUP)} ) ''' view_query = f''' SELECT ((d.description)->>'id')::uuid AS {qi(ptr_col_name(schema, Role, 'id'))}, (SELECT id FROM edgedb."_SchemaObjectType" WHERE name = 'sys::Role') AS {qi(ptr_col_name(schema, Role, '__type__'))}, (d.description)->>'name' AS {qi(ptr_col_name(schema, Role, 'name'))}, (d.description)->>'name' AS {qi(ptr_col_name(schema, Role, 'name__internal'))}, {superuser} AS {qi(ptr_col_name(schema, Role, 'superuser'))}, False AS {qi(ptr_col_name(schema, Role, 'abstract'))}, False AS {qi(ptr_col_name(schema, Role, 'final'))}, False AS {qi(ptr_col_name(schema, Role, 'is_derived'))}, ARRAY[]::text[] AS {qi(ptr_col_name(schema, Role, 'inherited_fields'))}, ARRAY[]::text[] AS {qi(ptr_col_name(schema, Role, 'computed_fields'))}, ((d.description)->>'builtin')::bool AS {qi(ptr_col_name(schema, Role, 'builtin'))}, False AS {qi(ptr_col_name(schema, Role, 'internal'))}, (d.description)->>'password_hash' AS {qi(ptr_col_name(schema, Role, 'password'))} FROM pg_catalog.pg_roles AS a CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(a.oid, 'pg_authid') AS description ) AS d WHERE (d.description)->>'id' IS NOT NULL AND (d.description)->>'tenant_id' = edgedb.get_backend_tenant_id() ''' member_of_link_query = f''' SELECT ((d.description)->>'id')::uuid AS {qi(ptr_col_name(schema, member_of, 'source'))}, ((md.description)->>'id')::uuid AS {qi(ptr_col_name(schema, member_of, 'target'))} FROM pg_catalog.pg_roles AS a CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(a.oid, 'pg_authid') AS description ) AS d INNER JOIN pg_auth_members m ON m.member = a.oid CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(m.roleid, 'pg_authid') AS description ) AS md ''' bases_link_query = f''' SELECT ((d.description)->>'id')::uuid AS {qi(ptr_col_name(schema, bases, 'source'))}, ((md.description)->>'id')::uuid AS {qi(ptr_col_name(schema, bases, 'target'))}, row_number() OVER (PARTITION BY a.oid ORDER BY m.roleid) AS {qi(ptr_col_name(schema, bases, 'index'))} FROM pg_catalog.pg_roles AS a CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(a.oid, 'pg_authid') AS description ) AS d INNER JOIN pg_auth_members m ON m.member = a.oid CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(m.roleid, 'pg_authid') AS description ) AS md ''' ancestors_link_query = f''' SELECT ((d.description)->>'id')::uuid AS {qi(ptr_col_name(schema, ancestors, 'source'))}, ((md.description)->>'id')::uuid AS {qi(ptr_col_name(schema, ancestors, 'target'))}, row_number() OVER (PARTITION BY a.oid ORDER BY m.roleid) AS {qi(ptr_col_name(schema, ancestors, 'index'))} FROM pg_catalog.pg_roles AS a CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(a.oid, 'pg_authid') AS description ) AS d INNER JOIN pg_auth_members m ON m.member = a.oid CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(m.roleid, 'pg_authid') AS description ) AS md ''' annos_link_query = f''' SELECT ((d.description)->>'id')::uuid AS {qi(ptr_col_name(schema, annos, 'source'))}, (annotations->>'id')::uuid AS {qi(ptr_col_name(schema, annos, 'target'))}, (annotations->>'value')::text AS {qi(ptr_col_name(schema, annos, 'value'))}, (annotations->>'owned')::bool AS {qi(ptr_col_name(schema, annos, 'owned'))} FROM pg_catalog.pg_roles AS a CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(a.oid, 'pg_authid') AS description ) AS d CROSS JOIN LATERAL ROWS FROM ( jsonb_array_elements( (d.description)->'annotations' ) ) AS annotations ''' int_annos_link_query = f''' SELECT ((d.description)->>'id')::uuid AS {qi(ptr_col_name(schema, int_annos, 'source'))}, (annotations->>'id')::uuid AS {qi(ptr_col_name(schema, int_annos, 'target'))}, (annotations->>'owned')::bool AS {qi(ptr_col_name(schema, int_annos, 'owned'))} FROM pg_catalog.pg_roles AS a CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(a.oid, 'pg_authid') AS description ) AS d CROSS JOIN LATERAL ROWS FROM ( jsonb_array_elements( (d.description)->'annotations__internal' ) ) AS annotations ''' objects = { Role: view_query, member_of: member_of_link_query, bases: bases_link_query, ancestors: ancestors_link_query, annos: annos_link_query, int_annos: int_annos_link_query, } views = [] for obj, query in objects.items(): tabview = dbops.View(name=tabname(schema, obj), query=query) inhview = dbops.View(name=inhviewname(schema, obj), query=query) views.append(tabview) views.append(inhview) return views def _generate_schema_ver_views(schema: s_schema.Schema) -> List[dbops.View]: Ver = schema.get( 'sys::GlobalSchemaVersion', type=s_objtypes.ObjectType, ) view_query = f''' SELECT (v.value->>'id')::uuid AS {qi(ptr_col_name(schema, Ver, 'id'))}, (SELECT id FROM edgedb."_SchemaObjectType" WHERE name = 'sys::GlobalSchemaVersion') AS {qi(ptr_col_name(schema, Ver, '__type__'))}, (v.value->>'name') AS {qi(ptr_col_name(schema, Ver, 'name'))}, (v.value->>'name') AS {qi(ptr_col_name(schema, Ver, 'name__internal'))}, (v.value->>'version')::uuid AS {qi(ptr_col_name(schema, Ver, 'version'))}, (v.value->>'builtin')::bool AS {qi(ptr_col_name(schema, Ver, 'builtin'))}, (v.value->>'internal')::bool AS {qi(ptr_col_name(schema, Ver, 'internal'))}, ARRAY[]::text[] AS {qi(ptr_col_name(schema, Ver, 'computed_fields'))} FROM jsonb_each( edgedb.get_database_metadata( {ql(defines.EDGEDB_TEMPLATE_DB)} ) -> 'GlobalSchemaVersion' ) AS v ''' objects = { Ver: view_query } views = [] for obj, query in objects.items(): tabview = dbops.View(name=tabname(schema, obj), query=query) inhview = dbops.View(name=inhviewname(schema, obj), query=query) views.append(tabview) views.append(inhview) return views def _make_json_caster( schema: s_schema.Schema, json_casts: Mapping[s_types.Type, s_casts.Cast], stype: s_types.Type, context: str, ) -> Callable[[Any], str]: cast = json_casts.get(stype) if cast is None: raise RuntimeError( f'there is no direct cast from std::json to ' f'the type of {context!r} ' f'({stype.get_displayname(schema)})' ) if cast.get_from_cast(schema): pgtype = types.pg_type_from_object(schema, stype) def _cast(val: Any) -> str: return f'({val})::{q(*pgtype)}' else: if cast.get_code(schema): cast_name = cast.get_name(schema) func_name = common.get_cast_backend_name( cast_name, aspect='function') else: func_name = cast.get_from_function(schema) def _cast(val: Any) -> str: return f'{q(*func_name)}({val})' return _cast def _generate_schema_aliases( schema: s_schema.Schema, module: s_name.UnqualName, ) -> List[dbops.View]: views = [] schema_objs = schema.get_objects( type=s_objtypes.ObjectType, included_modules=(module,), ) for schema_obj in schema_objs: bn = common.get_backend_name( schema, schema_obj, aspect='inhview', catenate=False, ) if module.name == 'sys' and not schema_obj.get_abstract(schema): bn = ('edgedbss', bn[1]) targets = [] for ptr in schema_obj.get_pointers(schema).objects(schema): if ptr.is_pure_computable(schema): continue psi = types.get_pointer_storage_info(ptr, schema=schema) if psi.table_type == 'ObjectType': ptr_name = ptr.get_shortname(schema).name col_name = psi.column_name if col_name != ptr_name: targets.append(f'{qi(col_name)} AS {qi(ptr_name)}') targets.append(f'{qi(col_name)} AS {qi(col_name)}') prefix = module.name.capitalize() alias_view = dbops.View( name=('edgedb', f'_{prefix}{schema_obj.get_name(schema).name}'), query=(f'SELECT {', '.join(targets)} FROM {q(*bn)}') ) views.append(alias_view) return views async def generate_support_views( conn: asyncpg.Connection, schema: s_schema.Schema, ) -> None: commands = dbops.CommandGroup() schema_alias_views = _generate_schema_aliases( schema, s_name.UnqualName('schema')) for alias_view in schema_alias_views: commands.add_command(dbops.CreateView(alias_view, or_replace=True)) InhObject = schema.get( 'schema::InheritingObject', type=s_objtypes.ObjectType) InhObject_ancestors = InhObject.getptr( schema, s_name.UnqualName('ancestors')) # "issubclass" SQL functions rely on access to the ancestors link. bn = common.get_backend_name( schema, InhObject_ancestors, aspect='inhview', catenate=False, ) alias_view = dbops.View( name=('edgedb', f'_SchemaInheritingObject__ancestors'), query=(f'SELECT * FROM {q(*bn)}') ) commands.add_command(dbops.CreateView(alias_view, or_replace=True)) conf = schema.get('cfg::Config', type=s_objtypes.ObjectType) cfg_views, _ = _generate_config_type_view( schema, conf, scope=None, path=[], rptr=None) commands.add_commands([ dbops.CreateView(dbops.View(name=tn, query=q), or_replace=True) for tn, q in cfg_views ]) conf = schema.get('cfg::SystemConfig', type=s_objtypes.ObjectType) cfg_views, _ = _generate_config_type_view( schema, conf, scope=qltypes.ConfigScope.SYSTEM, path=[], rptr=None) commands.add_commands([ dbops.CreateView(dbops.View(name=tn, query=q), or_replace=True) for tn, q in cfg_views ]) conf = schema.get('cfg::DatabaseConfig', type=s_objtypes.ObjectType) cfg_views, _ = _generate_config_type_view( schema, conf, scope=qltypes.ConfigScope.DATABASE, path=[], rptr=None) commands.add_commands([ dbops.CreateView(dbops.View(name=tn, query=q), or_replace=True) for tn, q in cfg_views ]) for dbview in _generate_database_views(schema): commands.add_command(dbops.CreateView(dbview, or_replace=True)) for extview in _generate_extension_views(schema): commands.add_command(dbops.CreateView(extview, or_replace=True)) for roleview in _generate_role_views(schema): commands.add_command(dbops.CreateView(roleview, or_replace=True)) for verview in _generate_schema_ver_views(schema): commands.add_command(dbops.CreateView(verview, or_replace=True)) sys_alias_views = _generate_schema_aliases( schema, s_name.UnqualName('sys')) for alias_view in sys_alias_views: commands.add_command(dbops.CreateView(alias_view, or_replace=True)) block = dbops.PLTopBlock() commands.generate(block) await _execute_block(conn, block) async def generate_support_functions( conn: asyncpg.Connection, schema: s_schema.Schema, ) -> None: commands = dbops.CommandGroup() commands.add_commands([ dbops.CreateFunction(IssubclassFunction()), dbops.CreateFunction(IssubclassFunction2()), dbops.CreateFunction(GetSchemaObjectNameFunction()), ]) block = dbops.PLTopBlock() commands.generate(block) await _execute_block(conn, block) async def generate_more_support_functions( conn: asyncpg.Connection, compiler: edbcompiler.Compiler, schema: s_schema.Schema, testmode: bool, ) -> None: commands = dbops.CommandGroup() _, text = edbbootstrap.compile_bootstrap_script( compiler, schema, _describe_config( schema, source='system override', testmode=testmode), output_format=edbcompiler.IoFormat.BINARY, ) DescribeSystemConfigAsDDLFunction = dbops.Function( name=('edgedb', '_describe_system_config_as_ddl'), args=[], returns=('text'), # Stable because it's raising exceptions. volatility='stable', text=text, ) _, text = edbbootstrap.compile_bootstrap_script( compiler, schema, _describe_config( schema, source='database', testmode=testmode), output_format=edbcompiler.IoFormat.BINARY, ) DescribeDatabaseConfigAsDDLFunction = dbops.Function( name=('edgedb', '_describe_database_config_as_ddl'), args=[], returns=('text'), # Stable because it's raising exceptions. volatility='stable', text=text, ) commands.add_commands([ dbops.CreateFunction( DescribeSystemConfigAsDDLFunction, or_replace=True), dbops.CreateFunction( DescribeDatabaseConfigAsDDLFunction, or_replace=True), dbops.CreateFunction( DescribeRolesAsDDLFunction(schema), or_replace=True), dbops.CreateFunction(GetSequenceBackendNameFunction()), dbops.CreateFunction(DumpSequencesFunction()), ]) block = dbops.PLTopBlock() commands.generate(block) await _execute_block(conn, block) def _describe_config( schema: s_schema.Schema, source: str, testmode: bool, ) -> str: """Generate an EdgeQL query to render config as DDL.""" if source == 'system override': scope = qltypes.ConfigScope.SYSTEM config_object_name = 'cfg::SystemConfig' elif source == 'database': scope = qltypes.ConfigScope.DATABASE config_object_name = 'cfg::DatabaseConfig' else: raise AssertionError(f'unexpected configuration source: {source!r}') cfg = schema.get(config_object_name, type=s_objtypes.ObjectType) items = [] for ptr_name, p in cfg.get_pointers(schema).items(schema): pn = str(ptr_name) if pn in ('id', '__type__'): continue is_internal = ( p.get_annotation( schema, s_name.QualName('cfg', 'internal') ) == 'true' ) if is_internal and not testmode: continue ptype = p.get_target(schema) assert ptype is not None ptr_card = p.get_cardinality(schema) mult = ptr_card.is_multi() if isinstance(ptype, s_objtypes.ObjectType): item = textwrap.indent( _render_config_object( schema=schema, valtype=ptype, value_expr=str(ptype.get_name(schema)), scope=scope, join_term='', level=1, ), ' ' * 4, ) else: psource = f'{config_object_name}.{ qlquote.quote_ident(pn) }' renderer = _render_config_set if mult else _render_config_scalar item = textwrap.indent( renderer( schema=schema, valtype=ptype, value_expr=psource, name=pn, scope=scope, level=1, ), ' ' * 4, ) condition = f'EXISTS json_get(conf, {ql(pn)})' if is_internal: condition = f'({condition}) AND testmode' items.append(f"(\n{item}\n IF {condition} ELSE ''\n )") testmode_check = ( "<bool>json_get(cfg::get_config_json(),'__internal_testmode','value')" " ?? false" ) query = ( f"FOR conf IN {{cfg::get_config_json(sources := [{ql(source)}])}} " + "UNION (\n" + (f"FOR testmode IN {{{testmode_check}}} UNION (\n" if testmode else "") + "SELECT\n " + ' ++ '.join(items) + (")" if testmode else "") + ")" ) return query def _render_config_value( *, schema: s_schema.Schema, valtype: s_types.Type, value_expr: str, ) -> str: if valtype.issubclass( schema, schema.get('std::anyreal', type=s_scalars.ScalarType), ): val = f'<str>{value_expr}' elif valtype.issubclass( schema, schema.get('std::bool', type=s_scalars.ScalarType), ): val = f'<str>{value_expr}' elif valtype.issubclass( schema, schema.get('std::str', type=s_scalars.ScalarType), ): val = f'cfg::_quote({value_expr})' else: raise AssertionError( f'unexpected configuration value type: ' f'{valtype.get_displayname(schema)}' ) return val def _render_config_set( *, schema: s_schema.Schema, valtype: s_types.Type, value_expr: str, scope: qltypes.ConfigScope, name: str, level: int, ) -> str: assert isinstance(valtype, s_scalars.ScalarType) v = _render_config_value( schema=schema, valtype=valtype, value_expr=value_expr) if level == 1: return ( f"'CONFIGURE {scope.to_edgeql()} " f"SET { qlquote.quote_ident(name) } := {{' ++ " f"array_join(array_agg({v}), ', ') ++ '}};'" ) else: indent = ' ' * (4 * (level - 1)) return ( f"'{indent}{ qlquote.quote_ident(name) } := {{' ++ " f"array_join(array_agg({v}), ', ') ++ '}},'" ) def _render_config_scalar( *, schema: s_schema.Schema, valtype: s_types.Type, value_expr: str, scope: qltypes.ConfigScope, name: str, level: int, ) -> str: assert isinstance(valtype, s_scalars.ScalarType) v = _render_config_value( schema=schema, valtype=valtype, value_expr=value_expr) if level == 1: return ( f"'CONFIGURE {scope.to_edgeql()} " f"SET { qlquote.quote_ident(name) } := ' ++ {v} ++ ';'" ) else: indent = ' ' * (4 * (level - 1)) return f"'{indent}{ qlquote.quote_ident(name) } := ' ++ {v} ++ ','" def _render_config_object( *, schema: s_schema.Schema, valtype: s_objtypes.ObjectType, value_expr: str, scope: qltypes.ConfigScope, join_term: str, level: int, ) -> str: # Generate a valid `CONFIGURE <SCOPE> INSERT ConfigObject` # shape for a given configuration object type or # `INSERT ConfigObject` for a nested configuration type. sub_layouts = _describe_config_object( schema=schema, valtype=valtype, level=level + 1, scope=scope) sub_layouts_items = [] if level == 1: decor = [f'CONFIGURE {scope.to_edgeql()} INSERT ', ';\\n'] else: decor = ['(INSERT ', ')'] indent = ' ' * (4 * (level - 1)) for type_name, type_layout in sub_layouts.items(): if type_layout: sub_layout_item = ( f"'{indent}{decor[0]}{type_name} {{\\n'\n++ " + "\n++ ".join(type_layout) + f" ++ '{indent}}}{decor[1]}'" ) else: sub_layout_item = ( f"'{indent}{decor[0]}{type_name}{decor[1]}'" ) if len(sub_layouts) > 1: if type_layout: sub_layout_item = ( f'(WITH item := item[IS {type_name}]' f' SELECT {sub_layout_item}) ' f'IF item.__type__.name = {ql(str(type_name))}' ) else: sub_layout_item = ( f'{sub_layout_item} ' f'IF item.__type__.name = {ql(str(type_name))}' ) sub_layouts_items.append(sub_layout_item) if len(sub_layouts_items) > 1: sli_render = '\nELSE '.join(sub_layouts_items) + "\nELSE ''" else: sli_render = sub_layouts_items[0] return '\n'.join(( f"array_join(array_agg((", f" FOR item IN {{ {value_expr} }}", f" UNION (", f"{textwrap.indent(sli_render, " " * 4)}", f" )", f")), {ql(join_term)})", )) def _describe_config_object( *, schema: s_schema.Schema, valtype: s_objtypes.ObjectType, level: int, scope: qltypes.ConfigScope, ) -> Dict[s_name.QualName, List[str]]: cfg_types = [valtype] cfg_types.extend(cfg_types[0].descendants(schema)) layouts = {} for cfg in cfg_types: items = [] for ptr_name, p in cfg.get_pointers(schema).items(schema): pn = str(ptr_name) if ( pn in ('id', '__type__') or p.get_annotation( schema, s_name.QualName('cfg', 'internal'), ) == 'true' ): continue ptype = p.get_target(schema) assert ptype is not None ptr_card = p.get_cardinality(schema) mult = ptr_card.is_multi() psource = f'item.{ qlquote.quote_ident(pn) }' if isinstance(ptype, s_objtypes.ObjectType): rval = textwrap.indent( _render_config_object( schema=schema, valtype=ptype, value_expr=psource, scope=scope, join_term=' UNION ', level=level + 1, ), ' ' * 2, ).strip() indent = ' ' * (4 * (level - 1)) item = ( f"'{indent}{qlquote.quote_ident(pn)} " f":= (\\n'\n++ {rval} ++ '\\n{indent}),\\n'" ) condition = None else: render = _render_config_set if mult else _render_config_scalar item = render( schema=schema, valtype=ptype, value_expr=psource, scope=scope, name=pn, level=level, ) condition = f'EXISTS {psource}' if condition is not None: item = f"({item} ++ '\\n' IF {condition} ELSE '')" items.append(item) layouts[cfg.get_name(schema)] = items return layouts def _build_key_source( schema: s_schema.Schema, exc_props: Iterable[s_pointers.Pointer], rptr: Optional[s_pointers.Pointer], source_idx: str, ) -> str: if exc_props: restargets = [] for prop in exc_props: pname = prop.get_shortname(schema).name restarget = f'(q{source_idx}.val)->>{ql(pname)}' restargets.append(restarget) targetlist = ','.join(restargets) keysource = textwrap.dedent(f'''\ (SELECT ARRAY[{targetlist}] AS key ) AS k{source_idx}''') else: assert rptr is not None rptr_name = rptr.get_shortname(schema).name keysource = textwrap.dedent(f'''\ (SELECT ARRAY[ (CASE WHEN q{source_idx}.val = 'null'::jsonb THEN NULL ELSE {ql(rptr_name)} END) ] AS key ) AS k{source_idx}''') return keysource def _build_key_expr(key_components: List[str]) -> str: key_expr = ' || '.join(key_components) final_keysource = textwrap.dedent(f'''\ (SELECT (CASE WHEN array_position(q.v, NULL) IS NULL THEN edgedbext.uuid_generate_v5( '{DATABASE_ID_NAMESPACE}'::uuid, array_to_string(q.v, ';') ) ELSE NULL END) AS key FROM (SELECT {key_expr} AS v) AS q )''') return final_keysource def _build_data_source( schema: s_schema.Schema, rptr: s_pointers.Pointer, source_idx: int, *, alias: Optional[str] = None, ) -> str: rptr_name = rptr.get_shortname(schema).name rptr_card = rptr.get_cardinality(schema) rptr_multi = rptr_card.is_multi() if alias is None: alias = f'q{source_idx + 1}' else: alias = f'q{alias}' if rptr_multi: sourceN = textwrap.dedent(f'''\ (SELECT jel.val FROM jsonb_array_elements( (q{source_idx}.val)->{ql(rptr_name)}) AS jel(val) ) AS {alias}''') else: sourceN = textwrap.dedent(f'''\ (SELECT (q{source_idx}.val)->{ql(rptr_name)} AS val ) AS {alias}''') return sourceN def _generate_config_type_view( schema: s_schema.Schema, stype: s_objtypes.ObjectType, *, scope: Optional[qltypes.ConfigScope], path: List[Tuple[s_pointers.Pointer, List[s_pointers.Pointer]]], rptr: Optional[s_pointers.Pointer], _memo: Optional[Set[s_obj.Object]] = None, ) -> Tuple[ List[Tuple[Tuple[str, str], str]], List[s_pointers.Pointer], ]: exc = schema.get('std::exclusive', type=s_constr.Constraint) json_t = schema.get('std::json', type=s_scalars.ScalarType) if scope is not None: if scope is qltypes.ConfigScope.SYSTEM: max_source = "'system override'" elif scope is qltypes.ConfigScope.DATABASE: max_source = "'database'" else: raise AssertionError(f'unexpected config scope: {scope!r}') else: max_source = 'NULL' if _memo is None: _memo = set() _memo.add(stype) views = [] json_casts = { c.get_to_type(schema): c for c in schema.get_casts_from_type(json_t) } sources = [] if not path: # This is the root config object. if rptr is None: source0 = textwrap.dedent(f'''\ (SELECT jsonb_object_agg(name, value) AS val FROM edgedb._read_sys_config(NULL, {max_source}) cfg) AS q0''') else: rptr_card = rptr.get_cardinality(schema) rptr_multi = rptr_card.is_multi() rptr_name = rptr.get_shortname(schema).name if rptr_multi: source0 = textwrap.dedent(f'''\ (SELECT el.val FROM (SELECT (value::jsonb) AS val FROM edgedb._read_sys_config(NULL, {max_source}) WHERE name = {ql(rptr_name)}) AS cfg, LATERAL jsonb_array_elements(cfg.val) AS el(val) ) AS q0''') else: source0 = textwrap.dedent(f'''\ (SELECT (value::jsonb) AS val FROM edgedb._read_sys_config(NULL, {max_source}) cfg WHERE name = {ql(rptr_name)}) AS q0''') sources.append(source0) key_start = 0 else: key_start = 0 for i, (l, exc_props) in enumerate(path): l_card = l.get_cardinality(schema) l_multi = l_card.is_multi() l_name = l.get_shortname(schema).name if i == 0: if l_multi: sourceN = textwrap.dedent(f'''\ (SELECT el.val FROM (SELECT (value::jsonb) AS val FROM edgedb._read_sys_config(NULL, {max_source}) WHERE name = {ql(l_name)}) AS cfg, LATERAL jsonb_array_elements(cfg.val) AS el(val) ) AS q{i}''') else: sourceN = textwrap.dedent(f'''\ (SELECT (value::jsonb) AS val FROM edgedb._read_sys_config(NULL, {max_source}) cfg WHERE name = {ql(l_name)}) AS q{i}''') else: sourceN = _build_data_source(schema, l, i - 1) sources.append(sourceN) sources.append(_build_key_source(schema, exc_props, l, str(i))) if exc_props: key_start = i exclusive_props = [] single_links = [] multi_links = [] multi_props = [] target_cols = [] where = '' path_steps = [p.get_shortname(schema).name for p, _ in path] if rptr is not None: self_idx = len(path) # Generate a source rvar for _this_ target rptr_name = rptr.get_shortname(schema).name path_steps.append(rptr_name) if self_idx > 0: sourceN = _build_data_source(schema, rptr, self_idx - 1) sources.append(sourceN) else: self_idx = 0 sval = f'(q{self_idx}.val)' for pp_name, pp in stype.get_pointers(schema).items(schema): pn = str(pp_name) if pn in ('id', '__type__'): continue pp_type = pp.get_target(schema) assert pp_type is not None pp_card = pp.get_cardinality(schema) pp_multi = pp_card.is_multi() pp_psi = types.get_pointer_storage_info(pp, schema=schema) pp_col = pp_psi.column_name if isinstance(pp, s_links.Link): if pp_multi: multi_links.append(pp) else: single_links.append(pp) else: pp_cast = _make_json_caster( schema, json_casts, pp_type, f'cfg::Config.{'.'.join(path_steps)}') if pp_multi: multi_props.append((pp, pp_cast)) else: extract_col = ( f'{pp_cast(f'{sval}->{ql(pn)}')}' f' AS {qi(pp_col)}') target_cols.append(extract_col) constraints = pp.get_constraints(schema).objects(schema) if any(c.issubclass(schema, exc) for c in constraints): exclusive_props.append(pp) exclusive_props.sort(key=lambda p: p.get_shortname(schema).name) if exclusive_props or rptr: sources.append( _build_key_source(schema, exclusive_props, rptr, str(self_idx))) key_components = [f'k{i}.key' for i in range(key_start, self_idx + 1)] final_keysource = f'{_build_key_expr(key_components)} AS k' sources.append(final_keysource) key_expr = 'k.key' target_cols.append(f'{key_expr} AS id') where = f'{key_expr} IS NOT NULL' target_cols.append(textwrap.dedent(f'''\ (SELECT id FROM edgedb."_SchemaObjectType" WHERE name = 'cfg::' || ({sval}->>'_tname')) AS __type__''')) else: key_expr = f"'{CONFIG_ID}'::uuid" target_cols.extend([ f"{key_expr} AS id", f'(SELECT id FROM edgedb."_SchemaObjectType" ' f"WHERE name = 'cfg::Config') AS __type__", ]) key_components = [] for link in single_links: link_name = link.get_shortname(schema).name link_type = link.get_target(schema) link_psi = types.get_pointer_storage_info(link, schema=schema) link_col = link_psi.column_name if rptr is not None: target_path = path + [(rptr, exclusive_props)] else: target_path = path target_views, target_exc_props = _generate_config_type_view( schema, link_type, scope=scope, path=target_path, rptr=link, _memo=_memo, ) for descendant in link_type.descendants(schema): if descendant not in _memo: desc_views, _ = _generate_config_type_view( schema, descendant, scope=scope, path=target_path, rptr=link, _memo=_memo, ) views.extend(desc_views) target_source = _build_data_source( schema, link, self_idx, alias=link_name) sources.append(target_source) target_key_source = _build_key_source( schema, target_exc_props, link, source_idx=link_name) sources.append(target_key_source) if target_exc_props: target_key_components = [f'k{link_name}.key'] else: target_key_components = key_components + [f'k{link_name}.key'] target_key = _build_key_expr(target_key_components) target_cols.append(f'({target_key}) AS {qi(link_col)}') views.extend(target_views) target_cols_str = ',\n'.join(target_cols) fromlist = ',\n'.join(f'LATERAL {s}' for s in sources) target_query = textwrap.dedent(f'''\ SELECT {textwrap.indent(target_cols_str, ' ' * 4).strip()} FROM {fromlist} ''') if where: target_query += f'\nWHERE\n {where}' views.append((tabname(schema, stype), target_query)) views.append((inhviewname(schema, stype), target_query)) for link in multi_links: target_sources = list(sources) link_name = link.get_shortname(schema).name link_type = link.get_target(schema) if rptr is not None: target_path = path + [(rptr, exclusive_props)] else: target_path = path target_views, target_exc_props = _generate_config_type_view( schema, link_type, scope=scope, path=target_path, rptr=link, _memo=_memo, ) views.extend(target_views) for descendant in link_type.descendants(schema): if descendant not in _memo: desc_views, _ = _generate_config_type_view( schema, descendant, scope=scope, path=target_path, rptr=link, _memo=_memo, ) views.extend(desc_views) target_source = _build_data_source( schema, link, self_idx, alias=link_name) target_sources.append(target_source) target_key_source = _build_key_source( schema, target_exc_props, link, source_idx=link_name) target_sources.append(target_key_source) target_key_components = key_components + [f'k{link_name}.key'] target_key = _build_key_expr(target_key_components) target_fromlist = ',\n'.join(f'LATERAL {s}' for s in target_sources) link_query = textwrap.dedent(f'''\ SELECT q.source, q.target FROM (SELECT {key_expr} AS source, {target_key} AS target FROM {target_fromlist} ) q WHERE q.target IS NOT NULL ''') views.append((tabname(schema, link), link_query)) views.append((inhviewname(schema, link), link_query)) for prop, pp_cast in multi_props: target_sources = list(sources) pn = prop.get_shortname(schema).name target_source = _build_data_source( schema, prop, self_idx, alias=pn) target_sources.append(target_source) target_fromlist = ',\n'.join(f'LATERAL {s}' for s in target_sources) link_query = textwrap.dedent(f'''\ SELECT {key_expr} AS source, {pp_cast(f'q{pn}.val')} AS target FROM {target_fromlist} ''') views.append((tabname(schema, prop), link_query)) views.append((inhviewname(schema, prop), link_query)) return views, exclusive_props async def _execute_block( conn: asyncpg.Connection, block: dbops.SQLBlock, ) -> None: await _execute_sql_script(conn, block.to_string()) async def _execute_sql_script( conn: asyncpg.Connection, sql_text: str, ) -> None: if debug.flags.bootstrap: debug.header('Bootstrap Script') if len(sql_text) > 102400: # Make sure we don't hog CPU by attempting to highlight # huge scripts. print(sql_text) else: debug.dump_code(sql_text, lexer='sql') try: await conn.execute(sql_text) except Exception as e: position = getattr(e, 'position', None) internal_position = getattr(e, 'internal_position', None) context = getattr(e, 'context', '') pl_func_line: Optional[int] if context: pl_func_line_m = re.search( r'^PL/pgSQL function inline_code_block line (\d+).*', context, re.M) if pl_func_line_m: pl_func_line = int(pl_func_line_m.group(1)) else: pl_func_line = None point = None if position is not None: point = int(position) text = getattr(e, 'query', None) if text is None: # Parse errors text = sql_text elif internal_position is not None: point = int(internal_position) text = getattr(e, 'internal_query', None) elif pl_func_line: point = _edgeql_rust.offset_of_line(sql_text, pl_func_line) text = sql_text if point is not None: context = parser_context.ParserContext( 'query', text, start=point, end=point) exceptions.replace_context(e, context) raise
# # This source file is part of the EdgeDB open source project. # # Copyright 2016-present MagicStack Inc. and the EdgeDB authors. # # 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. # """Database structure and objects supporting EdgeDB metadata.""" from __future__ import annotations from typing import * import re import textwrap from edb import _edgeql_rust from edb.common import context as parser_context from edb.common import debug from edb.common import exceptions from edb.common import uuidgen from edb.edgeql import qltypes from edb.edgeql import quote as qlquote from edb.schema import casts as s_casts from edb.schema import constraints as s_constr from edb.schema import links as s_links from edb.schema import name as s_name from edb.schema import objects as s_obj from edb.schema import objtypes as s_objtypes from edb.schema import pointers as s_pointers from edb.schema import properties as s_props from edb.schema import scalars as s_scalars from edb.schema import schema as s_schema from edb.schema import sources as s_sources from edb.schema import types as s_types from edb.server import defines from edb.server import compiler as edbcompiler from edb.server import bootstrap as edbbootstrap from edb.server import pgcluster from . import common from . import dbops from . import types if TYPE_CHECKING: import asyncpg q = common.qname qi = common.quote_ident ql = common.quote_literal qt = common.quote_type DATABASE_ID_NAMESPACE = uuidgen.UUID('0e6fed66-204b-11e9-8666-cffd58a5240b') CONFIG_ID_NAMESPACE = uuidgen.UUID('a48b38fa-349b-11e9-a6be-4f337f82f5ad') CONFIG_ID = uuidgen.UUID('172097a4-39f4-11e9-b189-9321eb2f4b97') class DBConfigTable(dbops.Table): def __init__(self) -> None: super().__init__(name=('edgedb', '_db_config')) self.add_columns([ dbops.Column(name='name', type='text'), dbops.Column(name='value', type='jsonb'), ]) self.add_constraint( dbops.UniqueConstraint( table_name=('edgedb', '_db_config'), columns=['name'], ), ) class ExpressionType(dbops.CompositeType): def __init__(self) -> None: super().__init__(name=('edgedb', 'expression_t')) self.add_columns([ dbops.Column(name='text', type='text'), dbops.Column(name='refs', type='uuid[]'), ]) class BigintDomain(dbops.Domain): """Bigint: a variant of numeric that enforces zero digits after the dot. We're using an explicit scale check as opposed to simply specifying the numeric bounds, because using bounds severly restricts the range of the numeric type (1000 vs 131072 digits). """ def __init__(self) -> None: super().__init__( name=('edgedb', 'bigint_t'), base='numeric', constraints=( dbops.DomainCheckConstraint( domain_name=('edgedb', 'bigint_t'), expr=("scale(VALUE) = 0 AND VALUE != 'NaN'"), ), ), ) class TimestampTzDomain(dbops.Domain): """Timestamptz clamped to years 0001-9999. The default timestamp range of (4713 BC - 294276 AD) has problems: Postgres isn't ISO compliant with years out of the 0-9999 range and language compatibility is questionable. """ def __init__(self) -> None: super().__init__( name=('edgedb', 'timestamptz_t'), base='timestamptz', constraints=( dbops.DomainCheckConstraint( domain_name=('edgedb', 'timestamptz_t'), expr=("EXTRACT(years from VALUE) BETWEEN 1 AND 9999"), ), ), ) class TimestampDomain(dbops.Domain): """Timestamp clamped to years 0001-9999. The default timestamp range of (4713 BC - 294276 AD) has problems: Postgres isn't ISO compliant with years out of the 0-9999 range and language compatibility is questionable. """ def __init__(self) -> None: super().__init__( name=('edgedb', 'timestamp_t'), base='timestamp', constraints=( dbops.DomainCheckConstraint( domain_name=('edgedb', 'timestamp_t'), expr=("EXTRACT(years from VALUE) BETWEEN 1 AND 9999"), ), ), ) class DateDomain(dbops.Domain): """Date clamped to years 0001-9999. The default timestamp range of (4713 BC - 294276 AD) has problems: Postgres isn't ISO compliant with years out of the 0-9999 range and language compatibility is questionable. """ def __init__(self) -> None: super().__init__( name=('edgedb', 'date_t'), base='date', constraints=( dbops.DomainCheckConstraint( domain_name=('edgedb', 'date_t'), expr=("EXTRACT(years from VALUE) BETWEEN 1 AND 9999"), ), ), ) class DurationDomain(dbops.Domain): def __init__(self) -> None: super().__init__( name=('edgedb', 'duration_t'), base='interval', constraints=( dbops.DomainCheckConstraint( domain_name=('edgedb', 'duration_t'), expr=r''' EXTRACT(months from VALUE) = 0 AND EXTRACT(years from VALUE) = 0 AND EXTRACT(days from VALUE) = 0 ''', ), ), ) class RelativeDurationDomain(dbops.Domain): def __init__(self) -> None: super().__init__( name=('edgedb', 'relative_duration_t'), base='interval', constraints=( dbops.DomainCheckConstraint( domain_name=('edgedb', 'relative_duration_t'), expr="true", ), ), ) class AlterCurrentDatabaseSetString(dbops.Function): """Alter a PostgreSQL configuration parameter of the current database.""" text = ''' BEGIN EXECUTE 'ALTER DATABASE ' || quote_ident(current_database()) || ' SET ' || quote_ident(parameter) || ' = ' || coalesce(quote_literal(value), 'DEFAULT'); RETURN value; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_alter_current_database_set'), args=[('parameter', ('text',)), ('value', ('text',))], returns=('text',), volatility='volatile', language='plpgsql', text=self.text, ) class AlterCurrentDatabaseSetStringArray(dbops.Function): """Alter a PostgreSQL configuration parameter of the current database.""" text = ''' BEGIN EXECUTE 'ALTER DATABASE ' || quote_ident(current_database()) || ' SET ' || quote_ident(parameter) || ' = ' || coalesce( (SELECT array_to_string(array_agg(quote_literal(q.v)), ',') FROM unnest(value) AS q(v) ), 'DEFAULT' ); RETURN value; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_alter_current_database_set'), args=[ ('parameter', ('text',)), ('value', ('text[]',)), ], returns=('text[]',), volatility='volatile', language='plpgsql', text=self.text, ) class AlterCurrentDatabaseSetNonArray(dbops.Function): """Alter a PostgreSQL configuration parameter of the current database.""" text = ''' BEGIN EXECUTE 'ALTER DATABASE ' || quote_ident(current_database()) || ' SET ' || quote_ident(parameter) || ' = ' || coalesce(value::text, 'DEFAULT'); RETURN value; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_alter_current_database_set'), args=[ ('parameter', ('text',)), ('value', ('anynonarray',)), ], returns=('anynonarray',), volatility='volatile', language='plpgsql', text=self.text, ) class AlterCurrentDatabaseSetArray(dbops.Function): """Alter a PostgreSQL configuration parameter of the current database.""" text = ''' BEGIN EXECUTE 'ALTER DATABASE ' || quote_ident(current_database()) || ' SET ' || quote_ident(parameter) || ' = ' || coalesce( (SELECT array_to_string(array_agg(q.v::text), ',') FROM unnest(value) AS q(v) ), 'DEFAULT' ); RETURN value; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_alter_current_database_set'), args=[ ('parameter', ('text',)), ('value', ('anyarray',)), ], returns=('anyarray',), volatility='volatile', language='plpgsql', text=self.text, ) class StrToBigint(dbops.Function): """Parse bigint from text.""" text = r''' SELECT (CASE WHEN scale(v.column1) = 0 THEN v.column1 ELSE edgedb.raise( NULL::numeric, 'invalid_text_representation', msg => ( 'invalid syntax for edgedb.bigint_t: ' || quote_literal(val) ) ) END)::edgedb.bigint_t FROM (VALUES ( val::numeric )) AS v ; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'str_to_bigint'), args=[('val', ('text',))], returns=('edgedb', 'bigint_t'), # Stable because it's raising exceptions. volatility='stable', text=self.text) class StrToDecimal(dbops.Function): """Parse decimal from text.""" text = r''' SELECT (CASE WHEN v.column1 != 'NaN' THEN v.column1 ELSE edgedb.raise( NULL::numeric, 'invalid_text_representation', msg => ( 'invalid syntax for numeric: ' || quote_literal(val) ) ) END) FROM (VALUES ( val::numeric )) AS v ; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'str_to_decimal'), args=[('val', ('text',))], returns=('numeric',), # Stable because it's raising exceptions. volatility='stable', text=self.text, ) class StrToInt64NoInline(dbops.Function): """String-to-int64 cast with noinline guard. Adding a LIMIT clause to the function statement makes it uninlinable due to the Postgres inlining heuristic looking for simple SELECT expressions only (i.e. no clauses.) This might need to change in the future if the heuristic changes. """ text = r''' SELECT "val"::bigint LIMIT 1 ; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'str_to_int64_noinline'), args=[('val', ('text',))], returns=('bigint',), volatility='stable', text=self.text, ) class StrToInt32NoInline(dbops.Function): """String-to-int32 cast with noinline guard.""" text = r''' SELECT "val"::int LIMIT 1 ; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'str_to_int32_noinline'), args=[('val', ('text',))], returns=('int',), volatility='stable', text=self.text, ) class StrToInt16NoInline(dbops.Function): """String-to-int16 cast with noinline guard.""" text = r''' SELECT "val"::smallint LIMIT 1 ; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'str_to_int16_noinline'), args=[('val', ('text',))], returns=('smallint',), volatility='stable', text=self.text, ) class StrToFloat64NoInline(dbops.Function): """String-to-float64 cast with noinline guard.""" text = r''' SELECT "val"::float8 LIMIT 1 ; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'str_to_float64_noinline'), args=[('val', ('text',))], returns=('float8',), volatility='stable', text=self.text, ) class StrToFloat32NoInline(dbops.Function): """String-to-float32 cast with noinline guard.""" text = r''' SELECT "val"::float4 LIMIT 1 ; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'str_to_float32_noinline'), args=[('val', ('text',))], returns=('float4',), volatility='stable', text=self.text, ) class GetBackendCapabilitiesFunction(dbops.Function): text = f''' SELECT (json ->> 'capabilities')::bigint FROM edgedbinstdata.instdata WHERE key = 'backend_instance_params' ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_backend_capabilities'), args=[], returns=('bigint',), language='sql', volatility='stable', text=self.text, ) class GetBackendTenantIDFunction(dbops.Function): text = f''' SELECT (json ->> 'tenant_id')::text FROM edgedbinstdata.instdata WHERE key = 'backend_instance_params' ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_backend_tenant_id'), args=[], returns=('text',), language='sql', volatility='stable', text=self.text, ) class GetDatabaseBackendNameFunction(dbops.Function): text = f''' SELECT edgedb.get_backend_tenant_id() || '_' || "db_name" ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_database_backend_name'), args=[('db_name', ('text',))], returns=('text',), language='sql', volatility='stable', text=self.text, ) class GetRoleBackendNameFunction(dbops.Function): text = f''' SELECT edgedb.get_backend_tenant_id() || '_' || "role_name" ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_role_backend_name'), args=[('role_name', ('text',))], returns=('text',), language='sql', volatility='stable', text=self.text, ) class GetUserSequenceBackendNameFunction(dbops.Function): text = f""" SELECT 'edgedbpub', "sequence_type_id"::text || '_sequence' """ def __init__(self) -> None: super().__init__( name=('edgedb', 'get_user_sequence_backend_name'), args=[('sequence_type_id', ('uuid',))], returns=('record',), language='sql', volatility='stable', text=self.text, ) class GetSequenceBackendNameFunction(dbops.Function): text = f''' SELECT (CASE WHEN edgedb.get_name_module(st.name) = any(edgedb.get_std_modules()) THEN 'edgedbstd' ELSE 'edgedbpub' END), "sequence_type_id"::text || '_sequence' FROM edgedb."_SchemaScalarType" AS st WHERE st.id = "sequence_type_id" ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_sequence_backend_name'), args=[('sequence_type_id', ('uuid',))], returns=('record',), language='sql', volatility='stable', text=self.text, ) class GetStdModulesFunction(dbops.Function): text = f''' SELECT ARRAY[{",".join(ql(str(m)) for m in s_schema.STD_MODULES)}] ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_std_modules'), args=[], returns=('text[]',), language='sql', volatility='immutable', text=self.text, ) class GetObjectMetadata(dbops.Function): """Return EdgeDB metadata associated with a backend object.""" text = ''' SELECT CASE WHEN substr(d, 1, char_length({prefix})) = {prefix} THEN substr(d, char_length({prefix}) + 1)::jsonb ELSE '{{}}'::jsonb END FROM obj_description("objoid", "objclass") AS d '''.format( prefix=f'E{ql(defines.EDGEDB_VISIBLE_METADATA_PREFIX)}', ) def __init__(self) -> None: super().__init__( name=('edgedb', 'obj_metadata'), args=[('objoid', ('oid',)), ('objclass', ('text',))], returns=('jsonb',), volatility='stable', text=self.text) class GetColumnMetadata(dbops.Function): """Return EdgeDB metadata associated with a backend object.""" text = ''' SELECT CASE WHEN substr(d, 1, char_length({prefix})) = {prefix} THEN substr(d, char_length({prefix}) + 1)::jsonb ELSE '{{}}'::jsonb END FROM col_description("tableoid", "column") AS d '''.format( prefix=f'E{ql(defines.EDGEDB_VISIBLE_METADATA_PREFIX)}', ) def __init__(self) -> None: super().__init__( name=('edgedb', 'col_metadata'), args=[('tableoid', ('oid',)), ('column', ('integer',))], returns=('jsonb',), volatility='stable', text=self.text) class GetSharedObjectMetadata(dbops.Function): """Return EdgeDB metadata associated with a backend object.""" text = ''' SELECT CASE WHEN substr(d, 1, char_length({prefix})) = {prefix} THEN substr(d, char_length({prefix}) + 1)::jsonb ELSE '{{}}'::jsonb END FROM shobj_description("objoid", "objclass") AS d '''.format( prefix=f'E{ql(defines.EDGEDB_VISIBLE_METADATA_PREFIX)}', ) def __init__(self) -> None: super().__init__( name=('edgedb', 'shobj_metadata'), args=[('objoid', ('oid',)), ('objclass', ('text',))], returns=('jsonb',), volatility='stable', text=self.text) class GetDatabaseMetadataFunction(dbops.Function): """Return EdgeDB metadata associated with a given database.""" text = ''' SELECT edgedb.shobj_metadata( (SELECT oid FROM pg_database WHERE datname = edgedb.get_database_backend_name("dbname") ), 'pg_database' ) ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_database_metadata'), args=[('dbname', ('text',))], returns=('jsonb',), volatility='stable', text=self.text, ) class GetCurrentDatabaseFunction(dbops.Function): text = f''' SELECT substr( current_database(), char_length(edgedb.get_backend_tenant_id()) + 2 ) ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_current_database'), args=[], returns=('text',), language='sql', volatility='stable', text=self.text, ) class RaiseExceptionFunction(dbops.Function): text = ''' BEGIN RAISE EXCEPTION USING ERRCODE = "exc", MESSAGE = "msg", DETAIL = COALESCE("detail", ''), HINT = COALESCE("hint", ''), COLUMN = COALESCE("column", ''), CONSTRAINT = COALESCE("constraint", ''), DATATYPE = COALESCE("datatype", ''), TABLE = COALESCE("table", ''), SCHEMA = COALESCE("schema", ''); RETURN "rtype"; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'raise'), args=[ ('rtype', ('anyelement',)), ('exc', ('text',), "'raise_exception'"), ('msg', ('text',), "''"), ('detail', ('text',), "''"), ('hint', ('text',), "''"), ('column', ('text',), "''"), ('constraint', ('text',), "''"), ('datatype', ('text',), "''"), ('table', ('text',), "''"), ('schema', ('text',), "''"), ], returns=('anyelement',), # NOTE: The main reason why we don't want this function to be # immutable is that immutable functions can be # pre-evaluated by the query planner once if they have # constant arguments. This means that using this function # as the second argument in a COALESCE will raise an # exception regardless of whether the first argument is # NULL or not. volatility='stable', language='plpgsql', text=self.text, ) class RaiseExceptionOnNullFunction(dbops.Function): """Return the passed value or raise an exception if it's NULL.""" text = ''' SELECT coalesce( val, edgedb.raise( val, exc, msg => msg, detail => detail, hint => hint, "column" => "column", "constraint" => "constraint", "datatype" => "datatype", "table" => "table", "schema" => "schema" ) ) ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'raise_on_null'), args=[ ('val', ('anyelement',)), ('exc', ('text',)), ('msg', ('text',)), ('detail', ('text',), "''"), ('hint', ('text',), "''"), ('column', ('text',), "''"), ('constraint', ('text',), "''"), ('datatype', ('text',), "''"), ('table', ('text',), "''"), ('schema', ('text',), "''"), ], returns=('anyelement',), # Same volatility as raise() volatility='stable', text=self.text, ) class RaiseExceptionOnNotNullFunction(dbops.Function): """Return the passed value or raise an exception if it's NOT NULL.""" text = ''' SELECT CASE WHEN val IS NULL THEN val ELSE edgedb.raise( val, exc, msg => msg, detail => detail, hint => hint, "column" => "column", "constraint" => "constraint", "datatype" => "datatype", "table" => "table", "schema" => "schema" ) END ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'raise_on_not_null'), args=[ ('val', ('anyelement',)), ('exc', ('text',)), ('msg', ('text',)), ('detail', ('text',), "''"), ('hint', ('text',), "''"), ('column', ('text',), "''"), ('constraint', ('text',), "''"), ('datatype', ('text',), "''"), ('table', ('text',), "''"), ('schema', ('text',), "''"), ], returns=('anyelement',), # Same volatility as raise() volatility='stable', text=self.text, ) class RaiseExceptionOnEmptyStringFunction(dbops.Function): """Return the passed string or raise an exception if it's empty.""" text = ''' SELECT CASE WHEN edgedb._length(val) = 0 THEN edgedb.raise(val, exc, msg => msg, detail => detail) ELSE val END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'raise_on_empty'), args=[ ('val', ('anyelement',)), ('exc', ('text',)), ('msg', ('text',)), ('detail', ('text',), "''"), ], returns=('anyelement',), # Same volatility as raise() volatility='stable', text=self.text, ) class AssertJSONTypeFunction(dbops.Function): """Assert that the JSON type matches what is expected.""" text = ''' SELECT CASE WHEN array_position(typenames, jsonb_typeof(val)) IS NULL THEN edgedb.raise( NULL::jsonb, 'wrong_object_type', msg => coalesce( msg, ( 'expected json ' || array_to_string(typenames, ' or ') || '; got json ' || coalesce(jsonb_typeof(val), 'UNKNOWN') ) ), detail => detail ) ELSE val END ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'jsonb_assert_type'), args=[ ('val', ('jsonb',)), ('typenames', ('text[]',)), ('msg', ('text',), 'NULL'), ('detail', ('text',), "''"), ], returns=('jsonb',), # Max volatility of raise() and array_to_string() (stable) volatility='stable', text=self.text, ) class ExtractJSONScalarFunction(dbops.Function): """Convert a given JSON scalar value into a text value.""" text = ''' SELECT (to_jsonb(ARRAY[ edgedb.jsonb_assert_type( coalesce(val, 'null'::jsonb), ARRAY[json_typename, 'null'], msg => msg, detail => detail ) ])->>0) ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'jsonb_extract_scalar'), args=[ ('val', ('jsonb',)), ('json_typename', ('text',)), ('msg', ('text',), 'NULL'), ('detail', ('text',), "''"), ], returns=('text',), volatility='stable', text=self.text, ) class GetSchemaObjectNameFunction(dbops.Function): text = ''' SELECT coalesce( (SELECT name FROM edgedb."_SchemaObject" WHERE id = type::uuid), edgedb.raise( NULL::text, msg => 'resolve_type_name: unknown type: "' || type || '"' ) ) ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_get_schema_object_name'), args=[('type', ('uuid',))], returns=('text',), # Max volatility of raise() and a SELECT from a # table (stable). volatility='stable', text=self.text, strict=True, ) class IssubclassFunction(dbops.Function): text = ''' SELECT clsid = any(classes) OR ( SELECT classes && q.ancestors FROM (SELECT array_agg(o.target) AS ancestors FROM edgedb."_SchemaInheritingObject__ancestors" o WHERE o.source = clsid ) AS q ); ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'issubclass'), args=[('clsid', 'uuid'), ('classes', 'uuid[]')], returns='bool', volatility='stable', text=self.__class__.text) class IssubclassFunction2(dbops.Function): text = ''' SELECT clsid = pclsid OR ( SELECT pclsid IN ( SELECT o.target FROM edgedb."_SchemaInheritingObject__ancestors" o WHERE o.source = clsid ) ); ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'issubclass'), args=[('clsid', 'uuid'), ('pclsid', 'uuid')], returns='bool', volatility='stable', text=self.__class__.text) class NormalizeNameFunction(dbops.Function): text = ''' SELECT CASE WHEN strpos(name, '@') = 0 THEN name ELSE CASE WHEN strpos(name, '::') = 0 THEN replace(split_part(name, '@', 1), '|', '::') ELSE replace( split_part( -- "reverse" calls are to emulate "rsplit" reverse(split_part(reverse(name), '::', 1)), '@', 1), '|', '::') END END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'shortname_from_fullname'), args=[('name', 'text')], returns='text', volatility='immutable', language='sql', text=self.__class__.text) class GetNameModuleFunction(dbops.Function): text = ''' SELECT reverse(split_part(reverse("name"), '::', 1)) ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_name_module'), args=[('name', 'text')], returns='text', volatility='immutable', language='sql', text=self.__class__.text) class NullIfArrayNullsFunction(dbops.Function): """Check if array contains NULLs and if so, return NULL.""" def __init__(self) -> None: super().__init__( name=('edgedb', '_nullif_array_nulls'), args=[('a', 'anyarray')], returns='anyarray', volatility='stable', language='sql', text=''' SELECT CASE WHEN array_position(a, NULL) IS NULL THEN a ELSE NULL END ''') class IndexDescType(dbops.CompositeType): """Introspected index description.""" def __init__(self) -> None: super().__init__(name=('edgedb', 'intro_index_desc_t')) self.add_columns([ dbops.Column(name='table_name', type='text[]'), dbops.Column(name='name', type='text'), dbops.Column(name='is_unique', type='bool'), dbops.Column(name='predicate', type='text'), dbops.Column(name='expression', type='text'), dbops.Column(name='columns', type='text[]'), dbops.Column(name='metadata', type='jsonb'), ]) class IntrospectIndexesFunction(dbops.Function): """Return set of indexes for each table.""" text = ''' SELECT i.table_name, i.index_name, i.index_is_unique, i.index_predicate, i.index_expression, i.index_columns, i.index_metadata FROM (SELECT * FROM (SELECT ARRAY[ns.nspname::text, c.relname::text] AS table_name, ic.relname::text AS index_name, i.indisunique AS index_is_unique, pg_get_expr(i.indpred, i.indrelid)::text AS index_predicate, pg_get_expr(i.indexprs, i.indrelid)::text AS index_expression, (SELECT array_agg(ia.attname::text ORDER BY ia.attnum) FROM pg_attribute AS ia WHERE ia.attrelid = i.indexrelid AND (ia.attnum IS NULL OR ia.attnum >= 1) ) AS index_columns, edgedb.obj_metadata(i.indexrelid, 'pg_class') AS index_metadata FROM pg_class AS c INNER JOIN pg_namespace AS ns ON ns.oid = c.relnamespace INNER JOIN pg_index AS i ON i.indrelid = c.oid INNER JOIN pg_class AS ic ON i.indexrelid = ic.oid WHERE ($1::text IS NULL OR ns.nspname LIKE $1::text) AND ($2::text IS NULL OR c.relname LIKE $2::text) AND ($3::text[] IS NULL OR ns.nspname || '.' || ic.relname = any($3::text[])) AND ($4::text IS NULL OR ic.relname LIKE $4::text) ) AS q WHERE (NOT $5::bool OR (index_metadata IS NOT NULL AND (index_metadata->>'ddl:inherit')::bool)) AND ( $6 OR ( index_metadata IS NULL OR NOT coalesce( (index_metadata->>'ddl:inherited')::bool, false) ) ) ) AS i ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'introspect_indexes'), args=[ ('schema_pattern', 'text', 'NULL'), ('table_pattern', 'text', 'NULL'), ('table_list', 'text[]', 'NULL'), ('index_pattern', 'text', 'NULL'), ('inheritable_only', 'bool', 'FALSE'), ('include_inherited', 'bool', 'FALSE'), ], returns=('edgedb', 'intro_index_desc_t'), set_returning=True, volatility='stable', language='sql', text=self.__class__.text) class TriggerDescType(dbops.CompositeType): """Introspected trigger description.""" def __init__(self) -> None: super().__init__(name=('edgedb', 'intro_trigger_desc_t')) self.add_columns([ dbops.Column(name='table_name', type='text[]'), dbops.Column(name='name', type='text'), dbops.Column(name='proc', type='text[]'), dbops.Column(name='is_constraint', type='bool'), dbops.Column(name='granularity', type='text'), dbops.Column(name='deferred', type='bool'), dbops.Column(name='timing', type='text'), dbops.Column(name='events', type='text[]'), dbops.Column(name='definition', type='text'), dbops.Column(name='condition', type='text'), dbops.Column(name='metadata', type='jsonb'), ]) class IntrospectTriggersFunction(dbops.Function): """Return a set of triggers for each table.""" text = ''' SELECT table_name, trg_name, trg_proc, trg_constraint, trg_granularity, trg_deferred, trg_timing, trg_events, trg_definition, NULL::text, trg_metadata FROM (SELECT * FROM (SELECT ARRAY[ns.nspname::text, tc.relname::text] AS table_name, t.oid::int AS trg_id, t.tgname::text AS trg_name, (SELECT ARRAY[nsp.nspname::text, p.proname::text] FROM pg_proc AS p INNER JOIN pg_namespace AS nsp ON nsp.oid = p.pronamespace WHERE t.tgfoid = p.oid ) AS trg_proc, t.tgconstraint != 0 AS trg_constraint, (CASE WHEN (t.tgtype & (1 << 0)) != 0 THEN 'row' ELSE 'statement' END) AS trg_granularity, t.tginitdeferred AS trg_deferred, (CASE WHEN (t.tgtype & (1 << 1)) != 0 THEN 'before' WHEN (t.tgtype & (1 << 6)) != 0 THEN 'instead' ELSE 'after' END) AS trg_timing, array_remove(ARRAY[ (CASE WHEN (t.tgtype & (1 << 2)) != 0 THEN 'insert' ELSE NULL END), (CASE WHEN (t.tgtype & (1 << 3)) != 0 THEN 'delete' ELSE NULL END), (CASE WHEN (t.tgtype & (1 << 4)) != 0 THEN 'update' ELSE NULL END), (CASE WHEN (t.tgtype & (1 << 5)) != 0 THEN 'truncate' ELSE NULL END) ]::text[], NULL) AS trg_events, pg_get_triggerdef(t.oid)::text AS trg_definition, edgedb.obj_metadata(t.oid, 'pg_trigger') AS trg_metadata FROM pg_trigger AS t INNER JOIN pg_class AS tc ON t.tgrelid = tc.oid INNER JOIN pg_namespace AS ns ON ns.oid = tc.relnamespace WHERE ($1::text IS NULL OR ns.nspname LIKE $1::text) AND ($2::text IS NULL OR tc.relname LIKE $2::text) AND ($3::text[] IS NULL OR ns.nspname || '.' || tc.relname = any($3::text[])) AND ($4::text IS NULL OR t.tgname LIKE $4::text) ) AS q WHERE (NOT $5::bool OR (trg_metadata IS NOT NULL AND (trg_metadata->>'ddl:inherit')::bool)) AND ( $6 OR ( trg_metadata IS NULL OR NOT coalesce( (trg_metadata->>'ddl:inherited')::bool, false) ) ) ) AS t ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'introspect_triggers'), args=[ ('schema_pattern', 'text', 'NULL'), ('table_pattern', 'text', 'NULL'), ('table_list', 'text[]', 'NULL'), ('trigger_pattern', 'text', 'NULL'), ('inheritable_only', 'bool', 'FALSE'), ('include_inherited', 'bool', 'FALSE'), ], returns=('edgedb', 'intro_trigger_desc_t'), set_returning=True, volatility='stable', language='sql', text=self.__class__.text) class TableInheritanceDescType(dbops.CompositeType): """Introspected table inheritance descriptor.""" def __init__(self) -> None: super().__init__(name=('edgedb', 'intro_tab_inh_t')) self.add_columns([ dbops.Column(name='name', type='text[]'), dbops.Column(name='depth', type='int'), dbops.Column(name='pos', type='int'), ]) class GetTableDescendantsFunction(dbops.Function): """Return a set of table descendants.""" text = ''' SELECT * FROM (WITH RECURSIVE inheritance(oid, name, ns, depth, path) AS ( SELECT c.oid, c.relname, ns.nspname, 0, ARRAY[c.relname] FROM pg_class c INNER JOIN pg_namespace ns ON c.relnamespace = ns.oid WHERE ($1::text IS NULL OR ns.nspname LIKE $1::text) AND ($2::text IS NULL OR c.relname LIKE $2::text) UNION ALL SELECT c.oid, c.relname, ns.nspname, i.depth + 1, i.path || c.relname FROM pg_class c, inheritance i, pg_inherits pgi, pg_namespace ns WHERE i.oid = pgi.inhparent AND c.oid = pgi.inhrelid AND ns.oid = c.relnamespace AND ($3::int IS NULL OR i.depth < $3::int) ) SELECT DISTINCT ON (ns, name) ARRAY[ns::text, name::text], depth, 0 FROM inheritance) q WHERE depth > 0 ORDER BY depth ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_table_descendants'), args=[ ('schema_name', 'text'), ('table_name', 'text'), ('max_depth', 'int', 'NULL'), ], returns=('edgedb', 'intro_tab_inh_t'), set_returning=True, volatility='stable', language='sql', text=self.__class__.text) class ParseTriggerConditionFunction(dbops.Function): """Return a set of table descendants.""" text = ''' DECLARE when_off integer; pos integer; brackets integer; chr text; def_len integer; BEGIN def_len := char_length(definition); when_off := strpos(definition, 'WHEN ('); IF when_off IS NULL OR when_off = 0 THEN RETURN NULL; ELSE pos := when_off + 6; brackets := 1; WHILE brackets > 0 AND pos < def_len LOOP chr := substr(definition, pos, 1); IF chr = ')' THEN brackets := brackets - 1; ELSIF chr = '(' THEN brackets := brackets + 1; END IF; pos := pos + 1; END LOOP; IF brackets != 0 THEN RAISE EXCEPTION 'cannot parse trigger condition: %', definition; END IF; RETURN substr( definition, when_off + 6, pos - (when_off + 6) - 1 ); END IF; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_parse_trigger_condition'), args=[ ('definition', 'text'), ], returns='text', volatility='stable', language='plpgsql', text=self.__class__.text) class NormalizeArrayIndexFunction(dbops.Function): """Convert an EdgeQL index to SQL index.""" text = ''' SELECT ( CASE WHEN index < 0 THEN length + index + 1 ELSE index + 1 END )::int ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_normalize_array_index'), args=[('index', ('bigint',)), ('length', ('int',))], returns=('int',), volatility='immutable', strict=True, text=self.text) class ArrayIndexWithBoundsFunction(dbops.Function): """Get an array element or raise an out-of-bounds exception.""" text = ''' SELECT edgedb.raise_on_null( val[edgedb._normalize_array_index(index, array_upper(val, 1))], 'array_subscript_error', msg => 'array index ' || index::text || ' is out of bounds', detail => detail ) ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_index'), args=[('val', ('anyarray',)), ('index', ('bigint',)), ('detail', ('text',))], returns=('anyelement',), # Same volatility as raise() volatility='stable', strict=True, text=self.text, ) class ArraySliceFunction(dbops.Function): """Get an array slice.""" text = ''' SELECT CASE WHEN start IS NULL THEN val[:edgedb._normalize_array_index( stop, array_upper(val, 1)) - 1] WHEN stop IS NULL THEN val[edgedb._normalize_array_index( start, array_upper(val, 1)):] ELSE val[edgedb._normalize_array_index( start, array_upper(val, 1)): edgedb._normalize_array_index( stop, array_upper(val, 1)) - 1] END ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_slice'), args=[('val', ('anyarray',)), ('start', ('bigint',)), ('stop', ('bigint',))], returns=('anyarray',), volatility='immutable', text=self.text, ) class StringIndexWithBoundsFunction(dbops.Function): """Get a string character or raise an out-of-bounds exception.""" text = ''' SELECT edgedb.raise_on_empty( substr( "val", edgedb._normalize_array_index("index", char_length("val")), 1 ), 'invalid_parameter_value', 'string index ' || "index"::text || ' is out of bounds', "detail" ) ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_index'), args=[ ('val', ('text',)), ('index', ('bigint',)), ('detail', ('text',)), ], returns=('text',), # Same volatility as raise_on_empty volatility='stable', strict=True, text=self.text, ) class BytesIndexWithBoundsFunction(dbops.Function): """Get a bytes character or raise an out-of-bounds exception.""" text = ''' SELECT edgedb.raise_on_empty( substr( "val", edgedb._normalize_array_index("index", length("val")), 1 ), 'invalid_parameter_value', 'byte string index ' || "index"::text || ' is out of bounds', "detail" ) ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_index'), args=[ ('val', ('bytea',)), ('index', ('bigint',)), ('detail', ('text',)), ], returns=('bytea',), # Same volatility as raise_on_empty volatility='stable', strict=True, text=self.text, ) class SubstrProxyFunction(dbops.Function): """Same as substr, but interpret negative length as 0 instead.""" text = r''' SELECT CASE WHEN length < 0 THEN '' ELSE substr(val, start::int, length) END ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_substr'), args=[('val', ('anyelement',)), ('start', ('bigint',)), ('length', ('int',))], returns=('anyelement',), volatility='immutable', strict=True, text=self.text) class LengthStringProxyFunction(dbops.Function): """Same as substr, but interpret negative length as 0 instead.""" text = r''' SELECT char_length(val) ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_length'), args=[('val', ('text',))], returns=('int',), volatility='immutable', strict=True, text=self.text) class LengthBytesProxyFunction(dbops.Function): """Same as substr, but interpret negative length as 0 instead.""" text = r''' SELECT length(val) ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_length'), args=[('val', ('bytea',))], returns=('int',), volatility='immutable', strict=True, text=self.text) class StringSliceImplFunction(dbops.Function): """Get a string slice.""" text = r''' SELECT CASE WHEN start IS NULL THEN edgedb._substr( val, 1, edgedb._normalize_array_index( stop, edgedb._length(val)) - 1 ) WHEN stop IS NULL THEN substr( val, edgedb._normalize_array_index( start, edgedb._length(val)) ) ELSE edgedb._substr( val, edgedb._normalize_array_index( start, edgedb._length(val)), edgedb._normalize_array_index( stop, edgedb._length(val)) - edgedb._normalize_array_index( start, edgedb._length(val)) ) END ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_str_slice'), args=[ ('val', ('anyelement',)), ('start', ('bigint',)), ('stop', ('bigint',)) ], returns=('anyelement',), volatility='immutable', text=self.text) class StringSliceFunction(dbops.Function): """Get a string slice.""" text = r''' SELECT edgedb._str_slice(val, start, stop) ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_slice'), args=[ ('val', ('text',)), ('start', ('bigint',)), ('stop', ('bigint',)) ], returns=('text',), volatility='immutable', text=self.text) class BytesSliceFunction(dbops.Function): """Get a string slice.""" text = r''' SELECT edgedb._str_slice(val, start, stop) ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_slice'), args=[ ('val', ('bytea',)), ('start', ('bigint',)), ('stop', ('bigint',)) ], returns=('bytea',), volatility='immutable', text=self.text) class JSONIndexByTextFunction(dbops.Function): """Get a JSON element by text index or raise an exception.""" text = r''' SELECT CASE jsonb_typeof(val) WHEN 'object' THEN ( edgedb.raise_on_null( val -> index, 'invalid_parameter_value', msg => ( 'json index ' || quote_literal(index) || ' is out of bounds' ), detail => detail ) ) WHEN 'array' THEN ( edgedb.raise( NULL::jsonb, 'wrong_object_type', msg => ( 'cannot index json ' || jsonb_typeof(val) || ' by ' || pg_typeof(index)::text ), detail => detail ) ) ELSE edgedb.raise( NULL::jsonb, 'wrong_object_type', msg => ( 'cannot index json ' || coalesce(jsonb_typeof(val), 'UNKNOWN') ), detail => detail ) END ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_index'), args=[ ('val', ('jsonb',)), ('index', ('text',)), ('detail', ('text',), "''"), ], returns=('jsonb',), # Same volatility as exception helpers volatility='stable', strict=True, text=self.text, ) class JSONIndexByIntFunction(dbops.Function): """Get a JSON element by int index or raise an exception.""" text = r''' SELECT CASE jsonb_typeof(val) WHEN 'object' THEN ( edgedb.raise( NULL::jsonb, 'wrong_object_type', msg => ( 'cannot index json ' || jsonb_typeof(val) || ' by ' || pg_typeof(index)::text ), detail => detail ) ) WHEN 'array' THEN ( edgedb.raise_on_null( val -> index::int, 'invalid_parameter_value', msg => 'json index ' || index::text || ' is out of bounds', detail => detail ) ) ELSE edgedb.raise( NULL::jsonb, 'wrong_object_type', msg => ( 'cannot index json ' || coalesce(jsonb_typeof(val), 'UNKNOWN') ), detail => detail ) END ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_index'), args=[ ('val', ('jsonb',)), ('index', ('bigint',)), ('detail', ('text',), "''"), ], returns=('jsonb',), # Min volatility of exception helpers and pg_typeof (stable). volatility='stable', strict=True, text=self.text, ) class JSONSliceFunction(dbops.Function): """Get a JSON array slice.""" text = r''' SELECT to_jsonb(_slice( ( SELECT array_agg(value) FROM jsonb_array_elements( edgedb.jsonb_assert_type(val, ARRAY['array'])) ), start, stop )) ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_slice'), args=[('val', ('jsonb',)), ('start', ('bigint',)), ('stop', ('bigint',))], returns=('jsonb',), # Same volatility as to_jsonb (stable) volatility='stable', text=self.text) # We need custom casting functions for various datetime scalars in # order to enforce correctness w.r.t. local vs time-zone-aware # datetime. Postgres does a lot of magic and guessing for time zones # and generally will accept text with or without time zone for any # particular flavor of timestamp. In order to guarantee that we can # detect time-zones we restrict the inputs to ISO8601 format. # # See issue #740. class DatetimeInFunction(dbops.Function): """Cast text into timestamptz using ISO8601 spec.""" text = r''' SELECT CASE WHEN val !~ ( '^\s*(' || '(\d{4}-\d{2}-\d{2}|\d{8})' || '[ tT]' || '(\d{2}(:\d{2}(:\d{2}(\.\d+)?)?)?|\d{2,6}(\.\d+)?)' || '([zZ]|[-+](\d{2,4}|\d{2}:\d{2}))' || ')\s*$' ) THEN edgedb.raise( NULL::edgedb.timestamptz_t, 'invalid_datetime_format', msg => ( 'invalid input syntax for type timestamptz: ' || quote_literal(val) ), detail => ( '{"hint":"Please use ISO8601 format. Example: ' || '2010-12-27T23:59:59-07:00 Alternatively ' || '\"to_datetime\" function provides custom ' || 'formatting options."}' ) ) ELSE val::edgedb.timestamptz_t END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'datetime_in'), args=[('val', ('text',))], returns=('edgedb', 'timestamptz_t'), # Same volatility as raise() (stable) volatility='stable', text=self.text) class DurationInFunction(dbops.Function): """Cast text into duration, ensuring there is no days or months units""" text = r''' SELECT CASE WHEN EXTRACT(MONTH FROM v.column1) != 0 OR EXTRACT(YEAR FROM v.column1) != 0 OR EXTRACT(DAY FROM v.column1) != 0 THEN edgedb.raise( NULL::edgedb.duration_t, 'invalid_datetime_format', msg => ( 'invalid input syntax for type std::duration: ' || quote_literal(val) ), detail => ( '{"hint":"Units bigger than days cannot be used ' || 'for std::duration."}' ) ) ELSE v.column1::edgedb.duration_t END FROM (VALUES ( val::interval )) AS v ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'duration_in'), args=[('val', ('text',))], returns=('edgedb', 'duration_t'), # Same volatility as raise() (stable) volatility='stable', text=self.text, ) class LocalDatetimeInFunction(dbops.Function): """Cast text into timestamp using ISO8601 spec.""" text = r''' SELECT CASE WHEN val !~ ( '^\s*(' || '(\d{4}-\d{2}-\d{2}|\d{8})' || '[ tT]' || '(\d{2}(:\d{2}(:\d{2}(\.\d+)?)?)?|\d{2,6}(\.\d+)?)' || ')\s*$' ) THEN edgedb.raise( NULL::edgedb.timestamp_t, 'invalid_datetime_format', msg => ( 'invalid input syntax for type timestamp: ' || quote_literal(val) ), detail => ( '{"hint":"Please use ISO8601 format. Example ' || '2010-04-18T09:27:00 Alternatively ' || '\"to_local_datetime\" function provides custom ' || 'formatting options."}' ) ) ELSE val::edgedb.timestamp_t END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'local_datetime_in'), args=[('val', ('text',))], returns=('edgedb', 'timestamp_t'), # Same volatility as raise() (stable) volatility='stable', text=self.text) class LocalDateInFunction(dbops.Function): """Cast text into date using ISO8601 spec.""" text = r''' SELECT CASE WHEN val !~ ( '^\s*(' || '(\d{4}-\d{2}-\d{2}|\d{8})' || ')\s*$' ) THEN edgedb.raise( NULL::edgedb.date_t, 'invalid_datetime_format', msg => ( 'invalid input syntax for type date: ' || quote_literal(val) ), detail => ( '{"hint":"Please use ISO8601 format. Example ' || '2010-04-18 Alternatively ' || '\"to_local_date\" function provides custom ' || 'formatting options."}' ) ) ELSE val::edgedb.date_t END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'local_date_in'), args=[('val', ('text',))], returns=('edgedb', 'date_t'), # Same volatility as raise() (stable) volatility='stable', text=self.text) class LocalTimeInFunction(dbops.Function): """Cast text into time using ISO8601 spec.""" text = r''' SELECT CASE WHEN val !~ ( '^\s*(' || '(\d{2}(:\d{2}(:\d{2}(\.\d+)?)?)?|\d{2,6}(\.\d+)?)' || ')\s*$' ) THEN edgedb.raise( NULL::time, 'invalid_datetime_format', msg => ( 'invalid input syntax for type time: ' || quote_literal(val) ), detail => ( '{"hint":"Please use ISO8601 format. Examples: ' || '18:43:27 or 18:43 Alternatively ' || '\"to_local_time\" function provides custom ' || 'formatting options."}' ) ) ELSE val::time END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'local_time_in'), args=[('val', ('text',))], returns=('time',), # Same volatility as raise() (stable) volatility='stable', text=self.text, ) class ToTimestampTZCheck(dbops.Function): """Checks if the original text has time zone or not.""" # What are we trying to mitigate? # We're trying to detect that when we're casting to datetime the # time zone is in fact present in the input. It is a problem if # it's not since then one gets assigned implicitly based on the # server settings. # # It is insufficient to rely on the presence of TZH in the format # string, since `to_timestamp` will happily ignore the missing # time-zone in the input anyway. So in order to tell whether the # input string contained a time zone that was in fact parsed we # employ the following trick: # # If the time zone is in the input then it is unambiguous and the # parsed value will not depend on the current server time zone. # However, if the time zone was omitted, then the parsed value # will default to the server time zone. This implies that if # changing the server time zone for the same input string affects # the parsed value, the input string itself didn't contain a time # zone. text = r''' DECLARE result timestamptz; chk timestamptz; msg text; BEGIN result := to_timestamp(val, fmt); PERFORM set_config('TimeZone', 'America/Toronto', true); chk := to_timestamp(val, fmt); -- We're deliberately not doing any save/restore because -- the server MUST be in UTC. In fact, this check relies -- on it. PERFORM set_config('TimeZone', 'UTC', true); IF hastz THEN msg := 'missing required'; ELSE msg := 'unexpected'; END IF; IF (result = chk) != hastz THEN RAISE EXCEPTION USING ERRCODE = 'invalid_datetime_format', MESSAGE = msg || ' time zone in input ' || quote_literal(val), DETAIL = ''; END IF; RETURN result::edgedb.timestamptz_t; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_to_timestamptz_check'), args=[('val', ('text',)), ('fmt', ('text',)), ('hastz', ('bool',))], returns=('edgedb', 'timestamptz_t'), # We're relying on changing settings, so it's volatile. volatility='volatile', language='plpgsql', text=self.text) class ToDatetimeFunction(dbops.Function): """Convert text into timestamptz using a formatting spec.""" # NOTE that if only the TZM (minutes) are mentioned it is not # enough for a valid time zone definition text = r''' SELECT CASE WHEN fmt !~ ( '^(' || '("([^"\\]|\\.)*")|' || '([^"]+)' || ')*(TZH).*$' ) THEN edgedb.raise( NULL::edgedb.timestamptz_t, 'invalid_datetime_format', msg => ( 'missing required time zone in format: ' || quote_literal(fmt) ), detail => ( $h${"hint":"Use one or both of the following: $h$ || $h$'TZH', 'TZM'"}$h$ ) ) ELSE edgedb._to_timestamptz_check(val, fmt, true) END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'to_datetime'), args=[('val', ('text',)), ('fmt', ('text',))], returns=('edgedb', 'timestamptz_t'), # Same as _to_timestamptz_check. volatility='volatile', text=self.text) class ToLocalDatetimeFunction(dbops.Function): """Convert text into timestamp using a formatting spec.""" # NOTE time zone should not be mentioned at all. text = r''' SELECT CASE WHEN fmt ~ ( '^(' || '("([^"\\]|\\.)*")|' || '([^"]+)' || ')*(TZH|TZM).*$' ) THEN edgedb.raise( NULL::edgedb.timestamp_t, 'invalid_datetime_format', msg => ( 'unexpected time zone in format: ' || quote_literal(fmt) ) ) ELSE edgedb._to_timestamptz_check(val, fmt, false) ::edgedb.timestamp_t END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'to_local_datetime'), args=[('val', ('text',)), ('fmt', ('text',))], returns=('edgedb', 'timestamp_t'), # Same as _to_timestamptz_check. volatility='volatile', text=self.text) class StrToBool(dbops.Function): """Parse bool from text.""" # We first try to match case-insensitive "true|false" at all. On # null, we raise an exception. But otherwise we know that we have # an array of matches. The first element matching "true" and # second - "false". So the boolean value is then "true" if the # second array element is NULL and false otherwise. text = r''' SELECT ( coalesce( regexp_match(val, '^\s*(?:(true)|(false))\s*$', 'i')::text[], edgedb.raise( NULL::text[], 'invalid_text_representation', msg => 'invalid syntax for bool: ' || quote_literal(val) ) ) )[2] IS NULL; ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'str_to_bool'), args=[('val', ('text',))], returns=('bool',), # Stable because it's raising exceptions. volatility='stable', text=self.text) class QuoteLiteralFunction(dbops.Function): """Encode string as edgeql literal quoted string""" text = r''' SELECT concat('\'', replace( replace(val, '\\', '\\\\'), '\'', '\\\''), '\'') ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'quote_literal'), args=[('val', ('text',))], returns=('str',), volatility='immutable', text=self.text) class QuoteIdentFunction(dbops.Function): """Quote ident function.""" # TODO do not quote valid identifiers unless they are reserved text = r''' SELECT concat('`', replace(val, '`', '``'), '`') ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'quote_ident'), args=[('val', ('text',))], returns=('text',), volatility='immutable', text=self.text, ) class QuoteNameFunction(dbops.Function): text = r""" SELECT string_agg(edgedb.quote_ident(np), '::') FROM unnest(string_to_array("name", '::')) AS np """ def __init__(self) -> None: super().__init__( name=('edgedb', 'quote_name'), args=[('name', ('text',))], returns=('text',), volatility='immutable', text=self.text, ) class DescribeRolesAsDDLFunctionForwardDecl(dbops.Function): """Forward declaration for _describe_roles_as_ddl""" def __init__(self) -> None: super().__init__( name=('edgedb', '_describe_roles_as_ddl'), args=[], returns=('text'), # Stable because it's raising exceptions. volatility='stable', text='SELECT NULL::text', ) class DescribeRolesAsDDLFunction(dbops.Function): """Describe roles as DDL""" def __init__(self, schema: s_schema.Schema) -> None: role_obj = schema.get("sys::Role", type=s_objtypes.ObjectType) roles = inhviewname(schema, role_obj) member_of = role_obj.getptr(schema, s_name.UnqualName('member_of')) members = inhviewname(schema, member_of) name_col = ptr_col_name(schema, role_obj, 'name') pass_col = ptr_col_name(schema, role_obj, 'password') qi_superuser = qlquote.quote_ident(defines.EDGEDB_SUPERUSER) text = f""" WITH RECURSIVE dependencies AS ( SELECT r.id AS id, m.target AS parent FROM {q(*roles)} r LEFT OUTER JOIN {q(*members)} m ON r.id = m.source ), roles_with_depths(id, depth) AS ( SELECT id, 0 FROM dependencies WHERE parent IS NULL UNION ALL SELECT dependencies.id, roles_with_depths.depth + 1 FROM dependencies INNER JOIN roles_with_depths ON dependencies.parent = roles_with_depths.id ), ordered_roles AS ( SELECT id, max(depth) FROM roles_with_depths GROUP BY id ORDER BY max(depth) ASC ) SELECT coalesce(string_agg( CASE WHEN role.{qi(name_col)} = { ql(defines.EDGEDB_SUPERUSER) } THEN NULLIF(concat( 'ALTER ROLE { qi_superuser } {{', NULLIF((SELECT concat( ' EXTENDING ', string_agg( edgedb.quote_ident(parent.{qi(name_col)}), ', ' ), ';' ) FROM {q(*members)} member INNER JOIN {q(*roles)} parent ON parent.id = member.target WHERE member.source = role.id ), ' EXTENDING ;'), CASE WHEN role.{qi(pass_col)} IS NOT NULL THEN concat(' SET password_hash := ', quote_literal(role.{qi(pass_col)}), ';') ELSE '' END, '}};' ), 'ALTER ROLE { qi_superuser } {{}};') ELSE concat( 'CREATE SUPERUSER ROLE ', edgedb.quote_ident(role.{qi(name_col)}), NULLIF((SELECT concat(' EXTENDING ', string_agg( edgedb.quote_ident(parent.{qi(name_col)}), ', ' ) ) FROM {q(*members)} member INNER JOIN {q(*roles)} parent ON parent.id = member.target WHERE member.source = role.id ), ' EXTENDING '), CASE WHEN role.{qi(pass_col)} IS NOT NULL THEN concat(' {{ SET password_hash := ', quote_literal(role.{qi(pass_col)}), '}};') ELSE ';' END ) END, '\n' ), '') str FROM ordered_roles JOIN {q(*roles)} role ON role.id = ordered_roles.id """ super().__init__( name=('edgedb', '_describe_roles_as_ddl'), args=[], returns=('text'), # Stable because it's raising exceptions. volatility='stable', text=text) class DescribeSystemConfigAsDDLFunctionForwardDecl(dbops.Function): def __init__(self) -> None: super().__init__( name=('edgedb', '_describe_system_config_as_ddl'), args=[], returns=('text'), volatility='stable', text='SELECT NULL::text', ) class DescribeDatabaseConfigAsDDLFunctionForwardDecl(dbops.Function): def __init__(self) -> None: super().__init__( name=('edgedb', '_describe_database_config_as_ddl'), args=[], returns=('text'), volatility='stable', text='SELECT NULL::text', ) class DumpSequencesFunction(dbops.Function): text = r""" SELECT string_agg( 'SELECT std::sequence_reset(' || 'INTROSPECT ' || edgedb.quote_name(seq.name) || (CASE WHEN seq_st.is_called THEN ', ' || seq_st.last_value::text ELSE '' END) || ');', E'\n' ) FROM (SELECT id, name FROM edgedb."_SchemaScalarType" WHERE id = any("seqs") ) AS seq, LATERAL ( SELECT COALESCE(last_value, start_value)::text AS last_value, last_value IS NOT NULL AS is_called FROM pg_sequences, LATERAL ROWS FROM ( edgedb.get_sequence_backend_name(seq.id) ) AS seq_name(schema text, name text) WHERE (pg_sequences.schemaname, pg_sequences.sequencename) = (seq_name.schema, seq_name.name) ) AS seq_st """ def __init__(self) -> None: super().__init__( name=('edgedb', '_dump_sequences'), args=[('seqs', ('uuid[]',))], returns=('text',), # Volatile because sequence state is volatile volatility='volatile', text=self.text, ) class SysConfigSourceType(dbops.Enum): def __init__(self) -> None: super().__init__( name=('edgedb', '_sys_config_source_t'), values=[ 'default', 'postgres default', 'postgres environment variable', 'postgres configuration file', 'postgres command line', 'postgres global', 'system override', 'database', 'postgres client', 'postgres override', 'postgres interactive', 'postgres test', 'session', ] ) class SysConfigScopeType(dbops.Enum): def __init__(self) -> None: super().__init__( name=('edgedb', '_sys_config_scope_t'), values=[ 'SYSTEM', 'DATABASE', 'SESSION', ] ) class SysConfigValueType(dbops.CompositeType): """Type of values returned by _read_sys_config.""" def __init__(self) -> None: super().__init__(name=('edgedb', '_sys_config_val_t')) self.add_columns([ dbops.Column(name='name', type='text'), dbops.Column(name='value', type='jsonb'), dbops.Column(name='source', type='edgedb._sys_config_source_t'), dbops.Column(name='scope', type='edgedb._sys_config_scope_t'), ]) class SysConfigFullFunction(dbops.Function): # This is a function because "_edgecon_state" is a temporary table # and therefore cannot be used in a view. text = f''' BEGIN RETURN QUERY EXECUTE $$ WITH config_spec AS ( SELECT s.key AS name, s.value->'default' AS default, (s.value->>'internal')::bool AS internal, (s.value->>'system')::bool AS system, (s.value->>'typeid')::uuid AS typeid, (s.value->>'typemod') AS typemod, (s.value->>'backend_setting') AS backend_setting FROM jsonb_each( (SELECT json FROM edgedbinstdata.instdata WHERE key = 'configspec') ) AS s ), config_defaults AS ( SELECT s.name AS name, s.default AS value, 'default' AS source FROM config_spec s ), config_sys AS ( SELECT s.key AS name, s.value AS value, 'system override' AS source FROM jsonb_each( edgedb.get_database_metadata( {ql(defines.EDGEDB_SYSTEM_DB)} ) -> 'sysconfig' ) AS s ), config_db AS ( SELECT s.name AS name, s.value AS value, 'database' AS source FROM edgedb._db_config s ), config_sess AS ( SELECT s.name AS name, s.value AS value, 'session' AS source FROM _edgecon_state s WHERE s.type = 'C' ), pg_db_setting AS ( SELECT nameval.name, to_jsonb(nameval.value) AS value, 'database' AS source FROM (SELECT setconfig FROM pg_db_role_setting WHERE setdatabase = ( SELECT oid FROM pg_database WHERE datname = current_database() ) AND setrole = 0 ) AS cfg_array, LATERAL unnest(cfg_array.setconfig) AS cfg_set(s), LATERAL ( SELECT split_part(cfg_set.s, '=', 1) AS name, split_part(cfg_set.s, '=', 2) AS value ) AS nameval, LATERAL ( SELECT config_spec.name FROM config_spec WHERE nameval.name = config_spec.backend_setting ) AS spec ), pg_conf_settings AS ( SELECT spec.name, to_jsonb(setting) AS value, 'postgres configuration file' AS source FROM pg_file_settings, LATERAL ( SELECT config_spec.name FROM config_spec WHERE pg_file_settings.name = config_spec.backend_setting ) AS spec WHERE sourcefile != (( SELECT setting FROM pg_settings WHERE name = 'data_directory' ) || '/postgresql.auto.conf') AND applied ), pg_auto_conf_settings AS ( SELECT spec.name, to_jsonb(setting) AS value, 'system override' AS source FROM pg_file_settings, LATERAL ( SELECT config_spec.name FROM config_spec WHERE pg_file_settings.name = config_spec.backend_setting ) AS spec WHERE sourcefile = (( SELECT setting FROM pg_settings WHERE name = 'data_directory' ) || '/postgresql.auto.conf') AND applied ), pg_config AS ( SELECT spec.name, to_jsonb( CASE WHEN u.v[1] IS NOT NULL THEN (settings.setting::int * (u.v[1])::int)::text || u.v[2] ELSE settings.setting || COALESCE(settings.unit, '') END ) AS value, source AS source FROM ( SELECT pg_settings.name AS name, pg_settings.unit AS unit, pg_settings.setting AS setting, (CASE WHEN pg_settings.source IN ('session', 'database') THEN pg_settings.source ELSE 'postgres ' || pg_settings.source END) AS source FROM pg_settings ) AS settings, LATERAL ( SELECT regexp_match(settings.unit, '(\\d+)(\\w+)') AS v ) AS u, LATERAL ( SELECT config_spec.name FROM config_spec WHERE settings.name = config_spec.backend_setting ) AS spec ) SELECT q.name, q.value, q.source, (CASE WHEN q.source < 'database'::edgedb._sys_config_source_t THEN 'SYSTEM' WHEN q.source = 'database'::edgedb._sys_config_source_t THEN 'DATABASE' ELSE 'SESSION' END)::edgedb._sys_config_scope_t AS scope FROM (SELECT u.name, u.value, u.source::edgedb._sys_config_source_t, row_number() OVER ( PARTITION BY u.name ORDER BY u.source::edgedb._sys_config_source_t DESC ) AS n FROM (SELECT * FROM ( SELECT * FROM config_defaults UNION ALL SELECT * FROM config_sys UNION ALL SELECT * FROM config_db UNION ALL SELECT * FROM config_sess UNION ALL SELECT * FROM pg_db_setting UNION ALL SELECT * FROM pg_conf_settings UNION ALL SELECT * FROM pg_auto_conf_settings UNION ALL SELECT * FROM pg_config ) AS q WHERE ($1 IS NULL OR q.source::edgedb._sys_config_source_t = any($1)) AND ($2 IS NULL OR q.source::edgedb._sys_config_source_t <= $2) ) AS u ) AS q WHERE q.n = 1; $$ USING source_filter, max_source; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_read_sys_config_full'), args=[ ( 'source_filter', ('edgedb', '_sys_config_source_t[]',), 'NULL', ), ( 'max_source', ('edgedb', '_sys_config_source_t'), 'NULL', ), ], returns=('edgedb', '_sys_config_val_t'), set_returning=True, language='plpgsql', volatility='volatile', text=self.text, ) class SysConfigNoFileAccessFunction(dbops.Function): text = f''' BEGIN RETURN QUERY EXECUTE $$ WITH config_spec AS ( SELECT s.key AS name, s.value->'default' AS default, (s.value->>'internal')::bool AS internal, (s.value->>'system')::bool AS system, (s.value->>'typeid')::uuid AS typeid, (s.value->>'typemod') AS typemod, (s.value->>'backend_setting') AS backend_setting FROM jsonb_each( (SELECT json FROM edgedbinstdata.instdata WHERE key = 'configspec') ) AS s ), config_defaults AS ( SELECT s.name AS name, s.default AS value, 'default' AS source FROM config_spec s ), config_sys AS ( SELECT s.key AS name, s.value AS value, 'system override' AS source FROM jsonb_each( edgedb.get_database_metadata( {ql(defines.EDGEDB_SYSTEM_DB)} ) -> 'sysconfig' ) AS s ), config_db AS ( SELECT s.name AS name, s.value AS value, 'database' AS source FROM edgedb._db_config s ), config_sess AS ( SELECT s.name AS name, s.value AS value, 'session' AS source FROM _edgecon_state s WHERE s.type = 'C' ), pg_db_setting AS ( SELECT nameval.name, to_jsonb(nameval.value) AS value, 'database' AS source FROM (SELECT setconfig FROM pg_db_role_setting WHERE setdatabase = ( SELECT oid FROM pg_database WHERE datname = current_database() ) AND setrole = 0 ) AS cfg_array, LATERAL unnest(cfg_array.setconfig) AS cfg_set(s), LATERAL ( SELECT split_part(cfg_set.s, '=', 1) AS name, split_part(cfg_set.s, '=', 2) AS value ) AS nameval, LATERAL ( SELECT config_spec.name FROM config_spec WHERE nameval.name = config_spec.backend_setting ) AS spec ), pg_config AS ( SELECT spec.name, to_jsonb( CASE WHEN u.v[1] IS NOT NULL THEN (settings.setting::int * (u.v[1])::int)::text || u.v[2] ELSE settings.setting || COALESCE(settings.unit, '') END ) AS value, source AS source FROM ( SELECT pg_settings.name AS name, pg_settings.unit AS unit, pg_settings.setting AS setting, (CASE WHEN pg_settings.source IN ('session', 'database') THEN pg_settings.source ELSE 'postgres ' || pg_settings.source END) AS source FROM pg_settings ) AS settings, LATERAL ( SELECT regexp_match(settings.unit, '(\\d+)(\\w+)') AS v ) AS u, LATERAL ( SELECT config_spec.name FROM config_spec WHERE settings.name = config_spec.backend_setting ) AS spec ) SELECT q.name, q.value, q.source, (CASE WHEN q.source < 'database'::edgedb._sys_config_source_t THEN 'SYSTEM' WHEN q.source = 'database'::edgedb._sys_config_source_t THEN 'DATABASE' ELSE 'SESSION' END)::edgedb._sys_config_scope_t AS scope FROM (SELECT u.name, u.value, u.source::edgedb._sys_config_source_t, row_number() OVER ( PARTITION BY u.name ORDER BY u.source::edgedb._sys_config_source_t DESC ) AS n FROM (SELECT * FROM ( SELECT * FROM config_defaults UNION ALL SELECT * FROM config_sys UNION ALL SELECT * FROM config_db UNION ALL SELECT * FROM config_sess UNION ALL SELECT * FROM pg_db_setting UNION ALL SELECT * FROM pg_config ) AS q WHERE ($1 IS NULL OR q.source::edgedb._sys_config_source_t = any($1)) AND ($2 IS NULL OR q.source::edgedb._sys_config_source_t <= $2) ) AS u ) AS q WHERE q.n = 1; $$ USING source_filter, max_source; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_read_sys_config_no_file_access'), args=[ ( 'source_filter', ('edgedb', '_sys_config_source_t[]',), 'NULL', ), ( 'max_source', ('edgedb', '_sys_config_source_t'), 'NULL', ), ], returns=('edgedb', '_sys_config_val_t'), set_returning=True, language='plpgsql', volatility='volatile', text=self.text, ) class SysConfigFunction(dbops.Function): text = f''' DECLARE backend_caps bigint; BEGIN backend_caps := edgedb.get_backend_capabilities(); IF (backend_caps & {int(pgcluster.BackendCapabilities.CONFIGFILE_ACCESS)}) != 0 THEN RETURN QUERY SELECT * FROM edgedb._read_sys_config_full(source_filter, max_source); ELSE RETURN QUERY SELECT * FROM edgedb._read_sys_config_no_file_access(source_filter, max_source); END IF; END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_read_sys_config'), args=[ ( 'source_filter', ('edgedb', '_sys_config_source_t[]',), 'NULL', ), ( 'max_source', ('edgedb', '_sys_config_source_t'), 'NULL', ), ], returns=('edgedb', '_sys_config_val_t'), set_returning=True, language='plpgsql', volatility='volatile', text=self.text, ) class SysVersionFunction(dbops.Function): text = f''' BEGIN RETURN ( SELECT value FROM _edgecon_state WHERE name = 'server_version' AND type = 'R' ); END; ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_sys_version'), args=[], returns=('jsonb',), language='plpgsql', volatility='stable', text=self.text, ) class SysGetTransactionIsolation(dbops.Function): "Get transaction isolation value as text compatible with EdgeDB's enum." text = r''' SELECT CASE setting WHEN 'repeatable read' THEN 'RepeatableRead' WHEN 'serializable' THEN 'Serializable' ELSE ( SELECT edgedb.raise( NULL::text, msg => ( 'unknown transaction isolation level "' || setting || '"' ) ) ) END FROM pg_settings WHERE name = 'transaction_isolation' ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_get_transaction_isolation'), args=[], returns=('text',), # This function only reads from a table. volatility='stable', text=self.text) class GetCachedReflection(dbops.Function): "Return a list of existing schema reflection helpers." text = ''' SELECT substring(proname, '__rh_#"%#"', '#') AS eql_hash, proargnames AS argnames FROM pg_proc INNER JOIN pg_namespace ON (pronamespace = pg_namespace.oid) WHERE proname LIKE '\\_\\_rh\\_%' ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_get_cached_reflection'), args=[], returns=('record',), set_returning=True, # This function only reads from a table. volatility='stable', text=self.text, ) class GetBaseScalarTypeMap(dbops.Function): """Return a map of base EdgeDB scalar type ids to Postgres type names.""" text = f''' VALUES {", ".join( f"""( {ql(str(k))}::uuid, { ql(f'{v[0]}.{v[1]}') if len(v) == 2 else ql(f'pg_catalog.{v[0]}') } )""" for k, v in types.base_type_name_map.items())} ''' def __init__(self) -> None: super().__init__( name=('edgedb', '_get_base_scalar_type_map'), args=[], returns=('record',), set_returning=True, volatility='immutable', text=self.text, ) class GetPgTypeForEdgeDBTypeFunction(dbops.Function): """Return Postgres OID representing a given EdgeDB type.""" text = f''' SELECT coalesce( ( SELECT tn::regtype::oid FROM edgedb._get_base_scalar_type_map() AS m(tid uuid, tn text) WHERE m.tid = "typeid" ), ( SELECT typ.oid FROM pg_catalog.pg_type typ WHERE typ.typname = "typeid"::text || '_domain' OR typ.typname = "typeid"::text || '_t' ), ( SELECT typ.typarray FROM pg_catalog.pg_type typ WHERE typ.typname = "elemid"::text || '_domain' OR typ.typname = "elemid"::text || '_t' OR typ.oid = ( SELECT tn::regtype::oid FROM edgedb._get_base_scalar_type_map() AS m(tid uuid, tn text) WHERE tid = elemid ) ), edgedb.raise( NULL::bigint, 'invalid_parameter_value', msg => ( format( 'cannot determine OID of EdgeDB type %L', typeid::text ) ) ) )::bigint ''' def __init__(self) -> None: super().__init__( name=('edgedb', 'get_pg_type_for_edgedb_type'), args=[ ('typeid', ('uuid',)), ('elemid', ('uuid',)), ], returns=('bigint',), volatility='stable', text=self.text, ) async def bootstrap(conn: asyncpg.Connection) -> None: commands = dbops.CommandGroup() commands.add_commands([ dbops.CreateSchema(name='edgedb'), dbops.CreateSchema(name='edgedbss'), dbops.CreateSchema(name='edgedbpub'), dbops.CreateSchema(name='edgedbstd'), dbops.CreateCompositeType(ExpressionType()), dbops.CreateTable(DBConfigTable()), dbops.CreateFunction(QuoteIdentFunction()), dbops.CreateFunction(QuoteNameFunction()), dbops.CreateFunction(AlterCurrentDatabaseSetString()), dbops.CreateFunction(AlterCurrentDatabaseSetStringArray()), dbops.CreateFunction(AlterCurrentDatabaseSetNonArray()), dbops.CreateFunction(AlterCurrentDatabaseSetArray()), dbops.CreateFunction(GetBackendCapabilitiesFunction()), dbops.CreateFunction(GetBackendTenantIDFunction()), dbops.CreateFunction(GetDatabaseBackendNameFunction()), dbops.CreateFunction(GetRoleBackendNameFunction()), dbops.CreateFunction(GetUserSequenceBackendNameFunction()), dbops.CreateFunction(GetStdModulesFunction()), dbops.CreateFunction(GetObjectMetadata()), dbops.CreateFunction(GetColumnMetadata()), dbops.CreateFunction(GetSharedObjectMetadata()), dbops.CreateFunction(GetDatabaseMetadataFunction()), dbops.CreateFunction(GetCurrentDatabaseFunction()), dbops.CreateFunction(RaiseExceptionFunction()), dbops.CreateFunction(RaiseExceptionOnNullFunction()), dbops.CreateFunction(RaiseExceptionOnNotNullFunction()), dbops.CreateFunction(RaiseExceptionOnEmptyStringFunction()), dbops.CreateFunction(AssertJSONTypeFunction()), dbops.CreateFunction(ExtractJSONScalarFunction()), dbops.CreateFunction(NormalizeNameFunction()), dbops.CreateFunction(GetNameModuleFunction()), dbops.CreateFunction(NullIfArrayNullsFunction()), dbops.CreateCompositeType(IndexDescType()), dbops.CreateFunction(IntrospectIndexesFunction()), dbops.CreateCompositeType(TriggerDescType()), dbops.CreateFunction(IntrospectTriggersFunction()), dbops.CreateCompositeType(TableInheritanceDescType()), dbops.CreateDomain(BigintDomain()), dbops.CreateDomain(TimestampTzDomain()), dbops.CreateDomain(TimestampDomain()), dbops.CreateDomain(DateDomain()), dbops.CreateDomain(DurationDomain()), dbops.CreateDomain(RelativeDurationDomain()), dbops.CreateFunction(StrToBigint()), dbops.CreateFunction(StrToDecimal()), dbops.CreateFunction(StrToInt64NoInline()), dbops.CreateFunction(StrToInt32NoInline()), dbops.CreateFunction(StrToInt16NoInline()), dbops.CreateFunction(StrToFloat64NoInline()), dbops.CreateFunction(StrToFloat32NoInline()), dbops.CreateFunction(GetTableDescendantsFunction()), dbops.CreateFunction(ParseTriggerConditionFunction()), dbops.CreateFunction(NormalizeArrayIndexFunction()), dbops.CreateFunction(ArrayIndexWithBoundsFunction()), dbops.CreateFunction(ArraySliceFunction()), dbops.CreateFunction(StringIndexWithBoundsFunction()), dbops.CreateFunction(LengthStringProxyFunction()), dbops.CreateFunction(LengthBytesProxyFunction()), dbops.CreateFunction(SubstrProxyFunction()), dbops.CreateFunction(StringSliceImplFunction()), dbops.CreateFunction(StringSliceFunction()), dbops.CreateFunction(BytesSliceFunction()), dbops.CreateFunction(JSONIndexByTextFunction()), dbops.CreateFunction(JSONIndexByIntFunction()), dbops.CreateFunction(JSONSliceFunction()), dbops.CreateFunction(DatetimeInFunction()), dbops.CreateFunction(DurationInFunction()), dbops.CreateFunction(LocalDatetimeInFunction()), dbops.CreateFunction(LocalDateInFunction()), dbops.CreateFunction(LocalTimeInFunction()), dbops.CreateFunction(ToTimestampTZCheck()), dbops.CreateFunction(ToDatetimeFunction()), dbops.CreateFunction(ToLocalDatetimeFunction()), dbops.CreateFunction(StrToBool()), dbops.CreateFunction(BytesIndexWithBoundsFunction()), dbops.CreateEnum(SysConfigSourceType()), dbops.CreateEnum(SysConfigScopeType()), dbops.CreateCompositeType(SysConfigValueType()), dbops.CreateFunction(SysConfigFullFunction()), dbops.CreateFunction(SysConfigNoFileAccessFunction()), dbops.CreateFunction(SysConfigFunction()), dbops.CreateFunction(SysVersionFunction()), dbops.CreateFunction(SysGetTransactionIsolation()), dbops.CreateFunction(GetCachedReflection()), dbops.CreateFunction(GetBaseScalarTypeMap()), dbops.CreateFunction(GetPgTypeForEdgeDBTypeFunction()), dbops.CreateFunction(DescribeSystemConfigAsDDLFunctionForwardDecl()), dbops.CreateFunction(DescribeDatabaseConfigAsDDLFunctionForwardDecl()), dbops.CreateFunction(DescribeRolesAsDDLFunctionForwardDecl()), ]) block = dbops.PLTopBlock() commands.generate(block) await _execute_block(conn, block) async def create_pg_extensions(conn: asyncpg.Connection) -> None: commands = dbops.CommandGroup() commands.add_commands([ dbops.CreateSchema(name='edgedbext'), dbops.CreateExtension( dbops.Extension(name='uuid-ossp', schema='edgedbext'), ), ]) block = dbops.PLTopBlock() commands.generate(block) await _execute_block(conn, block) classref_attr_aliases = { 'links': 'pointers', 'link_properties': 'pointers' } def tabname(schema: s_schema.Schema, obj: s_obj.Object) -> Tuple[str, str]: return ( 'edgedbss', common.get_backend_name( schema, obj, aspect='table', catenate=False, )[1], ) def inhviewname(schema: s_schema.Schema, obj: s_obj.Object) -> Tuple[str, str]: return ( 'edgedbss', common.get_backend_name( schema, obj, aspect='inhview', catenate=False, )[1], ) def ptr_col_name( schema: s_schema.Schema, obj: s_sources.Source, propname: str, ) -> str: prop = obj.getptr(schema, s_name.UnqualName(propname)) psi = types.get_pointer_storage_info(prop, schema=schema) return psi.column_name # type: ignore[no-any-return] def _generate_database_views(schema: s_schema.Schema) -> List[dbops.View]: Database = schema.get('sys::Database', type=s_objtypes.ObjectType) annos = Database.getptr( schema, s_name.UnqualName('annotations'), type=s_links.Link) int_annos = Database.getptr( schema, s_name.UnqualName('annotations__internal'), type=s_links.Link) view_query = f''' SELECT ((d.description)->>'id')::uuid AS {qi(ptr_col_name(schema, Database, 'id'))}, (SELECT id FROM edgedb."_SchemaObjectType" WHERE name = 'sys::Database') AS {qi(ptr_col_name(schema, Database, '__type__'))}, (datname IN ( edgedb.get_database_backend_name( {ql(defines.EDGEDB_TEMPLATE_DB)}), edgedb.get_database_backend_name( {ql(defines.EDGEDB_SYSTEM_DB)}) )) AS {qi(ptr_col_name(schema, Database, 'internal'))}, (d.description)->>'name' AS {qi(ptr_col_name(schema, Database, 'name'))}, (d.description)->>'name' AS {qi(ptr_col_name(schema, Database, 'name__internal'))}, ARRAY[]::text[] AS {qi(ptr_col_name(schema, Database, 'computed_fields'))}, ((d.description)->>'builtin')::bool AS {qi(ptr_col_name(schema, Database, 'builtin'))} FROM pg_database dat CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(dat.oid, 'pg_database') AS description ) AS d WHERE (d.description)->>'id' IS NOT NULL AND (d.description)->>'tenant_id' = edgedb.get_backend_tenant_id() ''' annos_link_query = f''' SELECT ((d.description)->>'id')::uuid AS {qi(ptr_col_name(schema, annos, 'source'))}, (annotations->>'id')::uuid AS {qi(ptr_col_name(schema, annos, 'target'))}, (annotations->>'value')::text AS {qi(ptr_col_name(schema, annos, 'value'))}, (annotations->>'owned')::bool AS {qi(ptr_col_name(schema, annos, 'owned'))} FROM pg_database dat CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(dat.oid, 'pg_database') AS description ) AS d CROSS JOIN LATERAL ROWS FROM ( jsonb_array_elements((d.description)->'annotations') ) AS annotations ''' int_annos_link_query = f''' SELECT ((d.description)->>'id')::uuid AS {qi(ptr_col_name(schema, int_annos, 'source'))}, (annotations->>'id')::uuid AS {qi(ptr_col_name(schema, int_annos, 'target'))}, (annotations->>'owned')::bool AS {qi(ptr_col_name(schema, int_annos, 'owned'))} FROM pg_database dat CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(dat.oid, 'pg_database') AS description ) AS d CROSS JOIN LATERAL ROWS FROM ( jsonb_array_elements( (d.description)->'annotations__internal' ) ) AS annotations ''' objects = { Database: view_query, annos: annos_link_query, int_annos: int_annos_link_query, } views = [] for obj, query in objects.items(): tabview = dbops.View(name=tabname(schema, obj), query=query) inhview = dbops.View(name=inhviewname(schema, obj), query=query) views.append(tabview) views.append(inhview) return views def _generate_extension_views(schema: s_schema.Schema) -> List[dbops.View]: ExtPkg = schema.get('sys::ExtensionPackage', type=s_objtypes.ObjectType) annos = ExtPkg.getptr( schema, s_name.UnqualName('annotations'), type=s_links.Link) int_annos = ExtPkg.getptr( schema, s_name.UnqualName('annotations__internal'), type=s_links.Link) ver = ExtPkg.getptr( schema, s_name.UnqualName('version'), type=s_props.Property) ver_t = common.get_backend_name( schema, ver.get_target(schema), catenate=False, ) view_query = f''' SELECT (e.value->>'id')::uuid AS {qi(ptr_col_name(schema, ExtPkg, 'id'))}, (SELECT id FROM edgedb."_SchemaObjectType" WHERE name = 'sys::ExtensionPackage') AS {qi(ptr_col_name(schema, ExtPkg, '__type__'))}, (e.value->>'name') AS {qi(ptr_col_name(schema, ExtPkg, 'name'))}, (e.value->>'name__internal') AS {qi(ptr_col_name(schema, ExtPkg, 'name__internal'))}, ( (e.value->'version'->>'major')::int, (e.value->'version'->>'minor')::int, (e.value->'version'->>'stage')::text, (e.value->'version'->>'stage_no')::int, COALESCE( (SELECT array_agg(q.v::text) FROM jsonb_array_elements( e.value->'version'->'local' ) AS q(v)), ARRAY[]::text[] ) )::{qt(ver_t)} AS {qi(ptr_col_name(schema, ExtPkg, 'version'))}, (e.value->>'script') AS {qi(ptr_col_name(schema, ExtPkg, 'script'))}, ARRAY[]::text[] AS {qi(ptr_col_name(schema, ExtPkg, 'computed_fields'))}, (e.value->>'builtin')::bool AS {qi(ptr_col_name(schema, ExtPkg, 'builtin'))}, (e.value->>'internal')::bool AS {qi(ptr_col_name(schema, ExtPkg, 'internal'))} FROM jsonb_each( edgedb.get_database_metadata( {ql(defines.EDGEDB_TEMPLATE_DB)} ) -> 'ExtensionPackage' ) AS e ''' annos_link_query = f''' SELECT (e.value->>'id')::uuid AS {qi(ptr_col_name(schema, annos, 'source'))}, (annotations->>'id')::uuid AS {qi(ptr_col_name(schema, annos, 'target'))}, (annotations->>'value')::text AS {qi(ptr_col_name(schema, annos, 'value'))}, (annotations->>'is_owned')::bool AS {qi(ptr_col_name(schema, annos, 'owned'))} FROM jsonb_each( edgedb.get_database_metadata( {ql(defines.EDGEDB_TEMPLATE_DB)} ) -> 'ExtensionPackage' ) AS e CROSS JOIN LATERAL ROWS FROM ( jsonb_array_elements(e.value->'annotations') ) AS annotations ''' int_annos_link_query = f''' SELECT (e.value->>'id')::uuid AS {qi(ptr_col_name(schema, int_annos, 'source'))}, (annotations->>'id')::uuid AS {qi(ptr_col_name(schema, int_annos, 'target'))}, (annotations->>'is_owned')::bool AS {qi(ptr_col_name(schema, int_annos, 'owned'))} FROM jsonb_each( edgedb.get_database_metadata( {ql(defines.EDGEDB_TEMPLATE_DB)} ) -> 'ExtensionPackage' ) AS e CROSS JOIN LATERAL ROWS FROM ( jsonb_array_elements(e.value->'annotations__internal') ) AS annotations ''' objects = { ExtPkg: view_query, annos: annos_link_query, int_annos: int_annos_link_query, } views = [] for obj, query in objects.items(): tabview = dbops.View(name=tabname(schema, obj), query=query) inhview = dbops.View(name=inhviewname(schema, obj), query=query) views.append(tabview) views.append(inhview) return views def _generate_role_views(schema: s_schema.Schema) -> List[dbops.View]: Role = schema.get('sys::Role', type=s_objtypes.ObjectType) member_of = Role.getptr( schema, s_name.UnqualName('member_of'), type=s_links.Link) bases = Role.getptr( schema, s_name.UnqualName('bases'), type=s_links.Link) ancestors = Role.getptr( schema, s_name.UnqualName('ancestors'), type=s_links.Link) annos = Role.getptr( schema, s_name.UnqualName('annotations'), type=s_links.Link) int_annos = Role.getptr( schema, s_name.UnqualName('annotations__internal'), type=s_links.Link) superuser = f''' a.rolsuper OR EXISTS ( SELECT FROM pg_auth_members m INNER JOIN pg_catalog.pg_roles g ON (m.roleid = g.oid) WHERE m.member = a.oid AND g.rolname = {ql(defines.EDGEDB_SUPERGROUP)} ) ''' view_query = f''' SELECT ((d.description)->>'id')::uuid AS {qi(ptr_col_name(schema, Role, 'id'))}, (SELECT id FROM edgedb."_SchemaObjectType" WHERE name = 'sys::Role') AS {qi(ptr_col_name(schema, Role, '__type__'))}, (d.description)->>'name' AS {qi(ptr_col_name(schema, Role, 'name'))}, (d.description)->>'name' AS {qi(ptr_col_name(schema, Role, 'name__internal'))}, {superuser} AS {qi(ptr_col_name(schema, Role, 'superuser'))}, False AS {qi(ptr_col_name(schema, Role, 'abstract'))}, False AS {qi(ptr_col_name(schema, Role, 'final'))}, False AS {qi(ptr_col_name(schema, Role, 'is_derived'))}, ARRAY[]::text[] AS {qi(ptr_col_name(schema, Role, 'inherited_fields'))}, ARRAY[]::text[] AS {qi(ptr_col_name(schema, Role, 'computed_fields'))}, ((d.description)->>'builtin')::bool AS {qi(ptr_col_name(schema, Role, 'builtin'))}, False AS {qi(ptr_col_name(schema, Role, 'internal'))}, (d.description)->>'password_hash' AS {qi(ptr_col_name(schema, Role, 'password'))} FROM pg_catalog.pg_roles AS a CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(a.oid, 'pg_authid') AS description ) AS d WHERE (d.description)->>'id' IS NOT NULL AND (d.description)->>'tenant_id' = edgedb.get_backend_tenant_id() ''' member_of_link_query = f''' SELECT ((d.description)->>'id')::uuid AS {qi(ptr_col_name(schema, member_of, 'source'))}, ((md.description)->>'id')::uuid AS {qi(ptr_col_name(schema, member_of, 'target'))} FROM pg_catalog.pg_roles AS a CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(a.oid, 'pg_authid') AS description ) AS d INNER JOIN pg_auth_members m ON m.member = a.oid CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(m.roleid, 'pg_authid') AS description ) AS md ''' bases_link_query = f''' SELECT ((d.description)->>'id')::uuid AS {qi(ptr_col_name(schema, bases, 'source'))}, ((md.description)->>'id')::uuid AS {qi(ptr_col_name(schema, bases, 'target'))}, row_number() OVER (PARTITION BY a.oid ORDER BY m.roleid) AS {qi(ptr_col_name(schema, bases, 'index'))} FROM pg_catalog.pg_roles AS a CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(a.oid, 'pg_authid') AS description ) AS d INNER JOIN pg_auth_members m ON m.member = a.oid CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(m.roleid, 'pg_authid') AS description ) AS md ''' ancestors_link_query = f''' SELECT ((d.description)->>'id')::uuid AS {qi(ptr_col_name(schema, ancestors, 'source'))}, ((md.description)->>'id')::uuid AS {qi(ptr_col_name(schema, ancestors, 'target'))}, row_number() OVER (PARTITION BY a.oid ORDER BY m.roleid) AS {qi(ptr_col_name(schema, ancestors, 'index'))} FROM pg_catalog.pg_roles AS a CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(a.oid, 'pg_authid') AS description ) AS d INNER JOIN pg_auth_members m ON m.member = a.oid CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(m.roleid, 'pg_authid') AS description ) AS md ''' annos_link_query = f''' SELECT ((d.description)->>'id')::uuid AS {qi(ptr_col_name(schema, annos, 'source'))}, (annotations->>'id')::uuid AS {qi(ptr_col_name(schema, annos, 'target'))}, (annotations->>'value')::text AS {qi(ptr_col_name(schema, annos, 'value'))}, (annotations->>'owned')::bool AS {qi(ptr_col_name(schema, annos, 'owned'))} FROM pg_catalog.pg_roles AS a CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(a.oid, 'pg_authid') AS description ) AS d CROSS JOIN LATERAL ROWS FROM ( jsonb_array_elements( (d.description)->'annotations' ) ) AS annotations ''' int_annos_link_query = f''' SELECT ((d.description)->>'id')::uuid AS {qi(ptr_col_name(schema, int_annos, 'source'))}, (annotations->>'id')::uuid AS {qi(ptr_col_name(schema, int_annos, 'target'))}, (annotations->>'owned')::bool AS {qi(ptr_col_name(schema, int_annos, 'owned'))} FROM pg_catalog.pg_roles AS a CROSS JOIN LATERAL ( SELECT edgedb.shobj_metadata(a.oid, 'pg_authid') AS description ) AS d CROSS JOIN LATERAL ROWS FROM ( jsonb_array_elements( (d.description)->'annotations__internal' ) ) AS annotations ''' objects = { Role: view_query, member_of: member_of_link_query, bases: bases_link_query, ancestors: ancestors_link_query, annos: annos_link_query, int_annos: int_annos_link_query, } views = [] for obj, query in objects.items(): tabview = dbops.View(name=tabname(schema, obj), query=query) inhview = dbops.View(name=inhviewname(schema, obj), query=query) views.append(tabview) views.append(inhview) return views def _generate_schema_ver_views(schema: s_schema.Schema) -> List[dbops.View]: Ver = schema.get( 'sys::GlobalSchemaVersion', type=s_objtypes.ObjectType, ) view_query = f''' SELECT (v.value->>'id')::uuid AS {qi(ptr_col_name(schema, Ver, 'id'))}, (SELECT id FROM edgedb."_SchemaObjectType" WHERE name = 'sys::GlobalSchemaVersion') AS {qi(ptr_col_name(schema, Ver, '__type__'))}, (v.value->>'name') AS {qi(ptr_col_name(schema, Ver, 'name'))}, (v.value->>'name') AS {qi(ptr_col_name(schema, Ver, 'name__internal'))}, (v.value->>'version')::uuid AS {qi(ptr_col_name(schema, Ver, 'version'))}, (v.value->>'builtin')::bool AS {qi(ptr_col_name(schema, Ver, 'builtin'))}, (v.value->>'internal')::bool AS {qi(ptr_col_name(schema, Ver, 'internal'))}, ARRAY[]::text[] AS {qi(ptr_col_name(schema, Ver, 'computed_fields'))} FROM jsonb_each( edgedb.get_database_metadata( {ql(defines.EDGEDB_TEMPLATE_DB)} ) -> 'GlobalSchemaVersion' ) AS v ''' objects = { Ver: view_query } views = [] for obj, query in objects.items(): tabview = dbops.View(name=tabname(schema, obj), query=query) inhview = dbops.View(name=inhviewname(schema, obj), query=query) views.append(tabview) views.append(inhview) return views def _make_json_caster( schema: s_schema.Schema, json_casts: Mapping[s_types.Type, s_casts.Cast], stype: s_types.Type, context: str, ) -> Callable[[Any], str]: cast = json_casts.get(stype) if cast is None: raise RuntimeError( f'there is no direct cast from std::json to ' f'the type of {context!r} ' f'({stype.get_displayname(schema)})' ) if cast.get_from_cast(schema): pgtype = types.pg_type_from_object(schema, stype) def _cast(val: Any) -> str: return f'({val})::{q(*pgtype)}' else: if cast.get_code(schema): cast_name = cast.get_name(schema) func_name = common.get_cast_backend_name( cast_name, aspect='function') else: func_name = cast.get_from_function(schema) def _cast(val: Any) -> str: return f'{q(*func_name)}({val})' return _cast def _generate_schema_aliases( schema: s_schema.Schema, module: s_name.UnqualName, ) -> List[dbops.View]: views = [] schema_objs = schema.get_objects( type=s_objtypes.ObjectType, included_modules=(module,), ) for schema_obj in schema_objs: bn = common.get_backend_name( schema, schema_obj, aspect='inhview', catenate=False, ) if module.name == 'sys' and not schema_obj.get_abstract(schema): bn = ('edgedbss', bn[1]) targets = [] for ptr in schema_obj.get_pointers(schema).objects(schema): if ptr.is_pure_computable(schema): continue psi = types.get_pointer_storage_info(ptr, schema=schema) if psi.table_type == 'ObjectType': ptr_name = ptr.get_shortname(schema).name col_name = psi.column_name if col_name != ptr_name: targets.append(f'{qi(col_name)} AS {qi(ptr_name)}') targets.append(f'{qi(col_name)} AS {qi(col_name)}') prefix = module.name.capitalize() alias_view = dbops.View( name=('edgedb', f'_{prefix}{schema_obj.get_name(schema).name}'), query=(f'SELECT {", ".join(targets)} FROM {q(*bn)}') ) views.append(alias_view) return views async def generate_support_views( conn: asyncpg.Connection, schema: s_schema.Schema, ) -> None: commands = dbops.CommandGroup() schema_alias_views = _generate_schema_aliases( schema, s_name.UnqualName('schema')) for alias_view in schema_alias_views: commands.add_command(dbops.CreateView(alias_view, or_replace=True)) InhObject = schema.get( 'schema::InheritingObject', type=s_objtypes.ObjectType) InhObject_ancestors = InhObject.getptr( schema, s_name.UnqualName('ancestors')) # "issubclass" SQL functions rely on access to the ancestors link. bn = common.get_backend_name( schema, InhObject_ancestors, aspect='inhview', catenate=False, ) alias_view = dbops.View( name=('edgedb', f'_SchemaInheritingObject__ancestors'), query=(f'SELECT * FROM {q(*bn)}') ) commands.add_command(dbops.CreateView(alias_view, or_replace=True)) conf = schema.get('cfg::Config', type=s_objtypes.ObjectType) cfg_views, _ = _generate_config_type_view( schema, conf, scope=None, path=[], rptr=None) commands.add_commands([ dbops.CreateView(dbops.View(name=tn, query=q), or_replace=True) for tn, q in cfg_views ]) conf = schema.get('cfg::SystemConfig', type=s_objtypes.ObjectType) cfg_views, _ = _generate_config_type_view( schema, conf, scope=qltypes.ConfigScope.SYSTEM, path=[], rptr=None) commands.add_commands([ dbops.CreateView(dbops.View(name=tn, query=q), or_replace=True) for tn, q in cfg_views ]) conf = schema.get('cfg::DatabaseConfig', type=s_objtypes.ObjectType) cfg_views, _ = _generate_config_type_view( schema, conf, scope=qltypes.ConfigScope.DATABASE, path=[], rptr=None) commands.add_commands([ dbops.CreateView(dbops.View(name=tn, query=q), or_replace=True) for tn, q in cfg_views ]) for dbview in _generate_database_views(schema): commands.add_command(dbops.CreateView(dbview, or_replace=True)) for extview in _generate_extension_views(schema): commands.add_command(dbops.CreateView(extview, or_replace=True)) for roleview in _generate_role_views(schema): commands.add_command(dbops.CreateView(roleview, or_replace=True)) for verview in _generate_schema_ver_views(schema): commands.add_command(dbops.CreateView(verview, or_replace=True)) sys_alias_views = _generate_schema_aliases( schema, s_name.UnqualName('sys')) for alias_view in sys_alias_views: commands.add_command(dbops.CreateView(alias_view, or_replace=True)) block = dbops.PLTopBlock() commands.generate(block) await _execute_block(conn, block) async def generate_support_functions( conn: asyncpg.Connection, schema: s_schema.Schema, ) -> None: commands = dbops.CommandGroup() commands.add_commands([ dbops.CreateFunction(IssubclassFunction()), dbops.CreateFunction(IssubclassFunction2()), dbops.CreateFunction(GetSchemaObjectNameFunction()), ]) block = dbops.PLTopBlock() commands.generate(block) await _execute_block(conn, block) async def generate_more_support_functions( conn: asyncpg.Connection, compiler: edbcompiler.Compiler, schema: s_schema.Schema, testmode: bool, ) -> None: commands = dbops.CommandGroup() _, text = edbbootstrap.compile_bootstrap_script( compiler, schema, _describe_config( schema, source='system override', testmode=testmode), output_format=edbcompiler.IoFormat.BINARY, ) DescribeSystemConfigAsDDLFunction = dbops.Function( name=('edgedb', '_describe_system_config_as_ddl'), args=[], returns=('text'), # Stable because it's raising exceptions. volatility='stable', text=text, ) _, text = edbbootstrap.compile_bootstrap_script( compiler, schema, _describe_config( schema, source='database', testmode=testmode), output_format=edbcompiler.IoFormat.BINARY, ) DescribeDatabaseConfigAsDDLFunction = dbops.Function( name=('edgedb', '_describe_database_config_as_ddl'), args=[], returns=('text'), # Stable because it's raising exceptions. volatility='stable', text=text, ) commands.add_commands([ dbops.CreateFunction( DescribeSystemConfigAsDDLFunction, or_replace=True), dbops.CreateFunction( DescribeDatabaseConfigAsDDLFunction, or_replace=True), dbops.CreateFunction( DescribeRolesAsDDLFunction(schema), or_replace=True), dbops.CreateFunction(GetSequenceBackendNameFunction()), dbops.CreateFunction(DumpSequencesFunction()), ]) block = dbops.PLTopBlock() commands.generate(block) await _execute_block(conn, block) def _describe_config( schema: s_schema.Schema, source: str, testmode: bool, ) -> str: """Generate an EdgeQL query to render config as DDL.""" if source == 'system override': scope = qltypes.ConfigScope.SYSTEM config_object_name = 'cfg::SystemConfig' elif source == 'database': scope = qltypes.ConfigScope.DATABASE config_object_name = 'cfg::DatabaseConfig' else: raise AssertionError(f'unexpected configuration source: {source!r}') cfg = schema.get(config_object_name, type=s_objtypes.ObjectType) items = [] for ptr_name, p in cfg.get_pointers(schema).items(schema): pn = str(ptr_name) if pn in ('id', '__type__'): continue is_internal = ( p.get_annotation( schema, s_name.QualName('cfg', 'internal') ) == 'true' ) if is_internal and not testmode: continue ptype = p.get_target(schema) assert ptype is not None ptr_card = p.get_cardinality(schema) mult = ptr_card.is_multi() if isinstance(ptype, s_objtypes.ObjectType): item = textwrap.indent( _render_config_object( schema=schema, valtype=ptype, value_expr=str(ptype.get_name(schema)), scope=scope, join_term='', level=1, ), ' ' * 4, ) else: psource = f'{config_object_name}.{ qlquote.quote_ident(pn) }' renderer = _render_config_set if mult else _render_config_scalar item = textwrap.indent( renderer( schema=schema, valtype=ptype, value_expr=psource, name=pn, scope=scope, level=1, ), ' ' * 4, ) condition = f'EXISTS json_get(conf, {ql(pn)})' if is_internal: condition = f'({condition}) AND testmode' items.append(f"(\n{item}\n IF {condition} ELSE ''\n )") testmode_check = ( "<bool>json_get(cfg::get_config_json(),'__internal_testmode','value')" " ?? false" ) query = ( f"FOR conf IN {{cfg::get_config_json(sources := [{ql(source)}])}} " + "UNION (\n" + (f"FOR testmode IN {{{testmode_check}}} UNION (\n" if testmode else "") + "SELECT\n " + ' ++ '.join(items) + (")" if testmode else "") + ")" ) return query def _render_config_value( *, schema: s_schema.Schema, valtype: s_types.Type, value_expr: str, ) -> str: if valtype.issubclass( schema, schema.get('std::anyreal', type=s_scalars.ScalarType), ): val = f'<str>{value_expr}' elif valtype.issubclass( schema, schema.get('std::bool', type=s_scalars.ScalarType), ): val = f'<str>{value_expr}' elif valtype.issubclass( schema, schema.get('std::str', type=s_scalars.ScalarType), ): val = f'cfg::_quote({value_expr})' else: raise AssertionError( f'unexpected configuration value type: ' f'{valtype.get_displayname(schema)}' ) return val def _render_config_set( *, schema: s_schema.Schema, valtype: s_types.Type, value_expr: str, scope: qltypes.ConfigScope, name: str, level: int, ) -> str: assert isinstance(valtype, s_scalars.ScalarType) v = _render_config_value( schema=schema, valtype=valtype, value_expr=value_expr) if level == 1: return ( f"'CONFIGURE {scope.to_edgeql()} " f"SET { qlquote.quote_ident(name) } := {{' ++ " f"array_join(array_agg({v}), ', ') ++ '}};'" ) else: indent = ' ' * (4 * (level - 1)) return ( f"'{indent}{ qlquote.quote_ident(name) } := {{' ++ " f"array_join(array_agg({v}), ', ') ++ '}},'" ) def _render_config_scalar( *, schema: s_schema.Schema, valtype: s_types.Type, value_expr: str, scope: qltypes.ConfigScope, name: str, level: int, ) -> str: assert isinstance(valtype, s_scalars.ScalarType) v = _render_config_value( schema=schema, valtype=valtype, value_expr=value_expr) if level == 1: return ( f"'CONFIGURE {scope.to_edgeql()} " f"SET { qlquote.quote_ident(name) } := ' ++ {v} ++ ';'" ) else: indent = ' ' * (4 * (level - 1)) return f"'{indent}{ qlquote.quote_ident(name) } := ' ++ {v} ++ ','" def _render_config_object( *, schema: s_schema.Schema, valtype: s_objtypes.ObjectType, value_expr: str, scope: qltypes.ConfigScope, join_term: str, level: int, ) -> str: # Generate a valid `CONFIGURE <SCOPE> INSERT ConfigObject` # shape for a given configuration object type or # `INSERT ConfigObject` for a nested configuration type. sub_layouts = _describe_config_object( schema=schema, valtype=valtype, level=level + 1, scope=scope) sub_layouts_items = [] if level == 1: decor = [f'CONFIGURE {scope.to_edgeql()} INSERT ', ';\\n'] else: decor = ['(INSERT ', ')'] indent = ' ' * (4 * (level - 1)) for type_name, type_layout in sub_layouts.items(): if type_layout: sub_layout_item = ( f"'{indent}{decor[0]}{type_name} {{\\n'\n++ " + "\n++ ".join(type_layout) + f" ++ '{indent}}}{decor[1]}'" ) else: sub_layout_item = ( f"'{indent}{decor[0]}{type_name}{decor[1]}'" ) if len(sub_layouts) > 1: if type_layout: sub_layout_item = ( f'(WITH item := item[IS {type_name}]' f' SELECT {sub_layout_item}) ' f'IF item.__type__.name = {ql(str(type_name))}' ) else: sub_layout_item = ( f'{sub_layout_item} ' f'IF item.__type__.name = {ql(str(type_name))}' ) sub_layouts_items.append(sub_layout_item) if len(sub_layouts_items) > 1: sli_render = '\nELSE '.join(sub_layouts_items) + "\nELSE ''" else: sli_render = sub_layouts_items[0] return '\n'.join(( f"array_join(array_agg((", f" FOR item IN {{ {value_expr} }}", f" UNION (", f"{textwrap.indent(sli_render, ' ' * 4)}", f" )", f")), {ql(join_term)})", )) def _describe_config_object( *, schema: s_schema.Schema, valtype: s_objtypes.ObjectType, level: int, scope: qltypes.ConfigScope, ) -> Dict[s_name.QualName, List[str]]: cfg_types = [valtype] cfg_types.extend(cfg_types[0].descendants(schema)) layouts = {} for cfg in cfg_types: items = [] for ptr_name, p in cfg.get_pointers(schema).items(schema): pn = str(ptr_name) if ( pn in ('id', '__type__') or p.get_annotation( schema, s_name.QualName('cfg', 'internal'), ) == 'true' ): continue ptype = p.get_target(schema) assert ptype is not None ptr_card = p.get_cardinality(schema) mult = ptr_card.is_multi() psource = f'item.{ qlquote.quote_ident(pn) }' if isinstance(ptype, s_objtypes.ObjectType): rval = textwrap.indent( _render_config_object( schema=schema, valtype=ptype, value_expr=psource, scope=scope, join_term=' UNION ', level=level + 1, ), ' ' * 2, ).strip() indent = ' ' * (4 * (level - 1)) item = ( f"'{indent}{qlquote.quote_ident(pn)} " f":= (\\n'\n++ {rval} ++ '\\n{indent}),\\n'" ) condition = None else: render = _render_config_set if mult else _render_config_scalar item = render( schema=schema, valtype=ptype, value_expr=psource, scope=scope, name=pn, level=level, ) condition = f'EXISTS {psource}' if condition is not None: item = f"({item} ++ '\\n' IF {condition} ELSE '')" items.append(item) layouts[cfg.get_name(schema)] = items return layouts def _build_key_source( schema: s_schema.Schema, exc_props: Iterable[s_pointers.Pointer], rptr: Optional[s_pointers.Pointer], source_idx: str, ) -> str: if exc_props: restargets = [] for prop in exc_props: pname = prop.get_shortname(schema).name restarget = f'(q{source_idx}.val)->>{ql(pname)}' restargets.append(restarget) targetlist = ','.join(restargets) keysource = textwrap.dedent(f'''\ (SELECT ARRAY[{targetlist}] AS key ) AS k{source_idx}''') else: assert rptr is not None rptr_name = rptr.get_shortname(schema).name keysource = textwrap.dedent(f'''\ (SELECT ARRAY[ (CASE WHEN q{source_idx}.val = 'null'::jsonb THEN NULL ELSE {ql(rptr_name)} END) ] AS key ) AS k{source_idx}''') return keysource def _build_key_expr(key_components: List[str]) -> str: key_expr = ' || '.join(key_components) final_keysource = textwrap.dedent(f'''\ (SELECT (CASE WHEN array_position(q.v, NULL) IS NULL THEN edgedbext.uuid_generate_v5( '{DATABASE_ID_NAMESPACE}'::uuid, array_to_string(q.v, ';') ) ELSE NULL END) AS key FROM (SELECT {key_expr} AS v) AS q )''') return final_keysource def _build_data_source( schema: s_schema.Schema, rptr: s_pointers.Pointer, source_idx: int, *, alias: Optional[str] = None, ) -> str: rptr_name = rptr.get_shortname(schema).name rptr_card = rptr.get_cardinality(schema) rptr_multi = rptr_card.is_multi() if alias is None: alias = f'q{source_idx + 1}' else: alias = f'q{alias}' if rptr_multi: sourceN = textwrap.dedent(f'''\ (SELECT jel.val FROM jsonb_array_elements( (q{source_idx}.val)->{ql(rptr_name)}) AS jel(val) ) AS {alias}''') else: sourceN = textwrap.dedent(f'''\ (SELECT (q{source_idx}.val)->{ql(rptr_name)} AS val ) AS {alias}''') return sourceN def _generate_config_type_view( schema: s_schema.Schema, stype: s_objtypes.ObjectType, *, scope: Optional[qltypes.ConfigScope], path: List[Tuple[s_pointers.Pointer, List[s_pointers.Pointer]]], rptr: Optional[s_pointers.Pointer], _memo: Optional[Set[s_obj.Object]] = None, ) -> Tuple[ List[Tuple[Tuple[str, str], str]], List[s_pointers.Pointer], ]: exc = schema.get('std::exclusive', type=s_constr.Constraint) json_t = schema.get('std::json', type=s_scalars.ScalarType) if scope is not None: if scope is qltypes.ConfigScope.SYSTEM: max_source = "'system override'" elif scope is qltypes.ConfigScope.DATABASE: max_source = "'database'" else: raise AssertionError(f'unexpected config scope: {scope!r}') else: max_source = 'NULL' if _memo is None: _memo = set() _memo.add(stype) views = [] json_casts = { c.get_to_type(schema): c for c in schema.get_casts_from_type(json_t) } sources = [] if not path: # This is the root config object. if rptr is None: source0 = textwrap.dedent(f'''\ (SELECT jsonb_object_agg(name, value) AS val FROM edgedb._read_sys_config(NULL, {max_source}) cfg) AS q0''') else: rptr_card = rptr.get_cardinality(schema) rptr_multi = rptr_card.is_multi() rptr_name = rptr.get_shortname(schema).name if rptr_multi: source0 = textwrap.dedent(f'''\ (SELECT el.val FROM (SELECT (value::jsonb) AS val FROM edgedb._read_sys_config(NULL, {max_source}) WHERE name = {ql(rptr_name)}) AS cfg, LATERAL jsonb_array_elements(cfg.val) AS el(val) ) AS q0''') else: source0 = textwrap.dedent(f'''\ (SELECT (value::jsonb) AS val FROM edgedb._read_sys_config(NULL, {max_source}) cfg WHERE name = {ql(rptr_name)}) AS q0''') sources.append(source0) key_start = 0 else: key_start = 0 for i, (l, exc_props) in enumerate(path): l_card = l.get_cardinality(schema) l_multi = l_card.is_multi() l_name = l.get_shortname(schema).name if i == 0: if l_multi: sourceN = textwrap.dedent(f'''\ (SELECT el.val FROM (SELECT (value::jsonb) AS val FROM edgedb._read_sys_config(NULL, {max_source}) WHERE name = {ql(l_name)}) AS cfg, LATERAL jsonb_array_elements(cfg.val) AS el(val) ) AS q{i}''') else: sourceN = textwrap.dedent(f'''\ (SELECT (value::jsonb) AS val FROM edgedb._read_sys_config(NULL, {max_source}) cfg WHERE name = {ql(l_name)}) AS q{i}''') else: sourceN = _build_data_source(schema, l, i - 1) sources.append(sourceN) sources.append(_build_key_source(schema, exc_props, l, str(i))) if exc_props: key_start = i exclusive_props = [] single_links = [] multi_links = [] multi_props = [] target_cols = [] where = '' path_steps = [p.get_shortname(schema).name for p, _ in path] if rptr is not None: self_idx = len(path) # Generate a source rvar for _this_ target rptr_name = rptr.get_shortname(schema).name path_steps.append(rptr_name) if self_idx > 0: sourceN = _build_data_source(schema, rptr, self_idx - 1) sources.append(sourceN) else: self_idx = 0 sval = f'(q{self_idx}.val)' for pp_name, pp in stype.get_pointers(schema).items(schema): pn = str(pp_name) if pn in ('id', '__type__'): continue pp_type = pp.get_target(schema) assert pp_type is not None pp_card = pp.get_cardinality(schema) pp_multi = pp_card.is_multi() pp_psi = types.get_pointer_storage_info(pp, schema=schema) pp_col = pp_psi.column_name if isinstance(pp, s_links.Link): if pp_multi: multi_links.append(pp) else: single_links.append(pp) else: pp_cast = _make_json_caster( schema, json_casts, pp_type, f'cfg::Config.{".".join(path_steps)}') if pp_multi: multi_props.append((pp, pp_cast)) else: extract_col = ( f'{pp_cast(f"{sval}->{ql(pn)}")}' f' AS {qi(pp_col)}') target_cols.append(extract_col) constraints = pp.get_constraints(schema).objects(schema) if any(c.issubclass(schema, exc) for c in constraints): exclusive_props.append(pp) exclusive_props.sort(key=lambda p: p.get_shortname(schema).name) if exclusive_props or rptr: sources.append( _build_key_source(schema, exclusive_props, rptr, str(self_idx))) key_components = [f'k{i}.key' for i in range(key_start, self_idx + 1)] final_keysource = f'{_build_key_expr(key_components)} AS k' sources.append(final_keysource) key_expr = 'k.key' target_cols.append(f'{key_expr} AS id') where = f'{key_expr} IS NOT NULL' target_cols.append(textwrap.dedent(f'''\ (SELECT id FROM edgedb."_SchemaObjectType" WHERE name = 'cfg::' || ({sval}->>'_tname')) AS __type__''')) else: key_expr = f"'{CONFIG_ID}'::uuid" target_cols.extend([ f"{key_expr} AS id", f'(SELECT id FROM edgedb."_SchemaObjectType" ' f"WHERE name = 'cfg::Config') AS __type__", ]) key_components = [] for link in single_links: link_name = link.get_shortname(schema).name link_type = link.get_target(schema) link_psi = types.get_pointer_storage_info(link, schema=schema) link_col = link_psi.column_name if rptr is not None: target_path = path + [(rptr, exclusive_props)] else: target_path = path target_views, target_exc_props = _generate_config_type_view( schema, link_type, scope=scope, path=target_path, rptr=link, _memo=_memo, ) for descendant in link_type.descendants(schema): if descendant not in _memo: desc_views, _ = _generate_config_type_view( schema, descendant, scope=scope, path=target_path, rptr=link, _memo=_memo, ) views.extend(desc_views) target_source = _build_data_source( schema, link, self_idx, alias=link_name) sources.append(target_source) target_key_source = _build_key_source( schema, target_exc_props, link, source_idx=link_name) sources.append(target_key_source) if target_exc_props: target_key_components = [f'k{link_name}.key'] else: target_key_components = key_components + [f'k{link_name}.key'] target_key = _build_key_expr(target_key_components) target_cols.append(f'({target_key}) AS {qi(link_col)}') views.extend(target_views) target_cols_str = ',\n'.join(target_cols) fromlist = ',\n'.join(f'LATERAL {s}' for s in sources) target_query = textwrap.dedent(f'''\ SELECT {textwrap.indent(target_cols_str, ' ' * 4).strip()} FROM {fromlist} ''') if where: target_query += f'\nWHERE\n {where}' views.append((tabname(schema, stype), target_query)) views.append((inhviewname(schema, stype), target_query)) for link in multi_links: target_sources = list(sources) link_name = link.get_shortname(schema).name link_type = link.get_target(schema) if rptr is not None: target_path = path + [(rptr, exclusive_props)] else: target_path = path target_views, target_exc_props = _generate_config_type_view( schema, link_type, scope=scope, path=target_path, rptr=link, _memo=_memo, ) views.extend(target_views) for descendant in link_type.descendants(schema): if descendant not in _memo: desc_views, _ = _generate_config_type_view( schema, descendant, scope=scope, path=target_path, rptr=link, _memo=_memo, ) views.extend(desc_views) target_source = _build_data_source( schema, link, self_idx, alias=link_name) target_sources.append(target_source) target_key_source = _build_key_source( schema, target_exc_props, link, source_idx=link_name) target_sources.append(target_key_source) target_key_components = key_components + [f'k{link_name}.key'] target_key = _build_key_expr(target_key_components) target_fromlist = ',\n'.join(f'LATERAL {s}' for s in target_sources) link_query = textwrap.dedent(f'''\ SELECT q.source, q.target FROM (SELECT {key_expr} AS source, {target_key} AS target FROM {target_fromlist} ) q WHERE q.target IS NOT NULL ''') views.append((tabname(schema, link), link_query)) views.append((inhviewname(schema, link), link_query)) for prop, pp_cast in multi_props: target_sources = list(sources) pn = prop.get_shortname(schema).name target_source = _build_data_source( schema, prop, self_idx, alias=pn) target_sources.append(target_source) target_fromlist = ',\n'.join(f'LATERAL {s}' for s in target_sources) link_query = textwrap.dedent(f'''\ SELECT {key_expr} AS source, {pp_cast(f'q{pn}.val')} AS target FROM {target_fromlist} ''') views.append((tabname(schema, prop), link_query)) views.append((inhviewname(schema, prop), link_query)) return views, exclusive_props async def _execute_block( conn: asyncpg.Connection, block: dbops.SQLBlock, ) -> None: await _execute_sql_script(conn, block.to_string()) async def _execute_sql_script( conn: asyncpg.Connection, sql_text: str, ) -> None: if debug.flags.bootstrap: debug.header('Bootstrap Script') if len(sql_text) > 102400: # Make sure we don't hog CPU by attempting to highlight # huge scripts. print(sql_text) else: debug.dump_code(sql_text, lexer='sql') try: await conn.execute(sql_text) except Exception as e: position = getattr(e, 'position', None) internal_position = getattr(e, 'internal_position', None) context = getattr(e, 'context', '') pl_func_line: Optional[int] if context: pl_func_line_m = re.search( r'^PL/pgSQL function inline_code_block line (\d+).*', context, re.M) if pl_func_line_m: pl_func_line = int(pl_func_line_m.group(1)) else: pl_func_line = None point = None if position is not None: point = int(position) text = getattr(e, 'query', None) if text is None: # Parse errors text = sql_text elif internal_position is not None: point = int(internal_position) text = getattr(e, 'internal_query', None) elif pl_func_line: point = _edgeql_rust.offset_of_line(sql_text, pl_func_line) text = sql_text if point is not None: context = parser_context.ParserContext( 'query', text, start=point, end=point) exceptions.replace_context(e, context) raise
#!/usr/bin/env python3 import time import re import os import logging import glob import argparse import change_dir import abunpack import acb2wav __version__ = "2.2.8" def main(): # argparse 설정 arg_parser = argparse.ArgumentParser() arg_parser.add_argument("-o", "--output_dir", help="Master output dir", type=str, default="./") arg_parser.add_argument("target", help="*.ab or *.acb.bytes file or folder's path", type=str, nargs="+") args = arg_parser.parse_args() output_dir = args.output_dir file_list = args.target # Logging 모듈 설정 logger = logging.getLogger("") logger.setLevel(logging.INFO) # 로거 포맷 설정 formatter = logging.Formatter('%(levelname)s | %(message)s') # 핸들러 설정 + 추가 stream_hander = logging.StreamHandler() stream_hander.setFormatter(formatter) logger.addHandler(stream_hander) # 파일 핸들러 if change_dir.config.getboolean("logger", "logger_save"): file_handler = logging.FileHandler('log.txt', encoding='utf-8') file_handler.setFormatter(formatter) logger.addHandler(file_handler) # 추출 시작 메시지 logger.info(f"girlsfrontline-resources-extractor: {__version__}") logger.info(f"Start Extracting: {time.strftime("%Y-%m-%d %I:%M:%S")}") # 지원가능한 파일인지 정규표현식으로 판단하기 위한 정규식 컴파일 re_ab = re.compile(".+[.]ab") re_acb = re.compile(".+[.]acb[.]bytes") # 받은 파일 목록으로 반복 구문 실행 for file_dir in file_list: # 폴더를 넣으면 폴더 내 ab, acb.bytes 파일들을 추출 if os.path.isdir(file_dir): file_dirs = glob.glob(f"{file_dir}/*.ab") + glob.glob(f"{file_dir}/*.acb.bytes") else: file_dirs = [file_dir] for fd in file_dirs: # AssetBunle 파일 (*.ab) 인 경우 if re_ab.match(fd): logger.info(f"\n=== AssetBundle File: {os.path.split(fd)[1]} ===") abunpack.abunpack(fd, output_dir) # ACB 파일 (*.acb.bytes) 인 경우 elif re_acb.match(fd): logger.info(f"=== ACB File: {os.path.split(fd)[1]} ===") acb2wav.acb2wav(fd, output_dir) # 둘다 아닌 경우 로거에 경고 반환 else: logger.warning(f"=== Unknown file: {os.path.split(fd)[1]}===") else: # 반복문 종료 이후 logger.info(f"Finish Extracting : {time.strftime("%Y-%m-%d %I:%M:%S")}\n\n") return if __name__ == "__main__": # 시간측정용 start_time = time.time() # 메인 함수 main() # 시간측정 종료 print("=== 소모시간 : %s초 ===" % (time.time() - start_time)) #os.system('pause')
#!/usr/bin/env python3 import time import re import os import logging import glob import argparse import change_dir import abunpack import acb2wav __version__ = "2.2.8" def main(): # argparse 설정 arg_parser = argparse.ArgumentParser() arg_parser.add_argument("-o", "--output_dir", help="Master output dir", type=str, default="./") arg_parser.add_argument("target", help="*.ab or *.acb.bytes file or folder's path", type=str, nargs="+") args = arg_parser.parse_args() output_dir = args.output_dir file_list = args.target # Logging 모듈 설정 logger = logging.getLogger("") logger.setLevel(logging.INFO) # 로거 포맷 설정 formatter = logging.Formatter('%(levelname)s | %(message)s') # 핸들러 설정 + 추가 stream_hander = logging.StreamHandler() stream_hander.setFormatter(formatter) logger.addHandler(stream_hander) # 파일 핸들러 if change_dir.config.getboolean("logger", "logger_save"): file_handler = logging.FileHandler('log.txt', encoding='utf-8') file_handler.setFormatter(formatter) logger.addHandler(file_handler) # 추출 시작 메시지 logger.info(f"girlsfrontline-resources-extractor: {__version__}") logger.info(f"Start Extracting: {time.strftime('%Y-%m-%d %I:%M:%S')}") # 지원가능한 파일인지 정규표현식으로 판단하기 위한 정규식 컴파일 re_ab = re.compile(".+[.]ab") re_acb = re.compile(".+[.]acb[.]bytes") # 받은 파일 목록으로 반복 구문 실행 for file_dir in file_list: # 폴더를 넣으면 폴더 내 ab, acb.bytes 파일들을 추출 if os.path.isdir(file_dir): file_dirs = glob.glob(f"{file_dir}/*.ab") + glob.glob(f"{file_dir}/*.acb.bytes") else: file_dirs = [file_dir] for fd in file_dirs: # AssetBunle 파일 (*.ab) 인 경우 if re_ab.match(fd): logger.info(f"\n=== AssetBundle File: {os.path.split(fd)[1]} ===") abunpack.abunpack(fd, output_dir) # ACB 파일 (*.acb.bytes) 인 경우 elif re_acb.match(fd): logger.info(f"=== ACB File: {os.path.split(fd)[1]} ===") acb2wav.acb2wav(fd, output_dir) # 둘다 아닌 경우 로거에 경고 반환 else: logger.warning(f"=== Unknown file: {os.path.split(fd)[1]}===") else: # 반복문 종료 이후 logger.info(f"Finish Extracting : {time.strftime('%Y-%m-%d %I:%M:%S')}\n\n") return if __name__ == "__main__": # 시간측정용 start_time = time.time() # 메인 함수 main() # 시간측정 종료 print("=== 소모시간 : %s초 ===" % (time.time() - start_time)) #os.system('pause')
from __future__ import annotations import asyncio import datetime import gzip import itertools import json import string from pathlib import Path from typing import Counter, Iterable, Sequence, TypeVar import platformdirs import pyperclip from rich.align import Align from rich.bar import Bar from rich.console import Group, RenderableType from rich.panel import Panel as RichPanel from rich.table import Table from textual import events from textual.app import App from textual.layout import Layout from textual.reactive import Reactive from textual.views import DockView, GridView from textual.widget import Widget from textual.widgets import Button, ButtonPressed, Header from textual.widgets._button import ButtonRenderable BASE_DIR = Path(__file__).parent IDLE = "bold white on rgb(130,130,130)" EMPTY = "bold on rgb(18,18,18)" ABSENT = 0 PRESENT = 1 CORRECT = 2 LETTER_STATUS = { ABSENT: "bold white on rgb(58,58,58)", PRESENT: "bold white on rgb(181,159,59)", CORRECT: "bold white on rgb(83,141,78)", } BLOCKS = {ABSENT: "⬛", PRESENT: "🟨", CORRECT: "🟩"} INITIAL_STATS = { "played": 0, "stats": [0, 0, 0, 0, 0, 0], "current_streak": 0, "max_streak": 0, } SEED_DATE = datetime.datetime.combine(datetime.datetime(2021, 6, 19), datetime.time()) STATS_JSON = Path(platformdirs.user_data_dir("wordle")) / ".stats.json" STATS_JSON.parent.mkdir(exist_ok=True, parents=True) with BASE_DIR.joinpath("La.gz").open("rb") as laf, BASE_DIR.joinpath("Ta.gz").open( "rb" ) as taf: La: list[str] = json.loads(gzip.decompress(laf.read())) Ta: list[str] = json.loads(gzip.decompress(taf.read())) T = TypeVar("T") def partition(l: Iterable[T], size: int) -> Iterable[Sequence[T]]: it = iter(l) return iter(lambda: tuple(itertools.islice(it, size)), ()) def calculate_eta(target_date: datetime.datetime) -> str | None: """Print a human-readable ETA to the next wordle""" units = [3600, 60, 1] now = datetime.datetime.now() dt = (target_date - now).total_seconds() if dt <= 0: return None digits = [] for unit in units: digits.append("%02d" % int(dt // unit)) dt %= unit return f'[green]{':'.join(digits)}[/green]' class GameStats(Widget): def __init__(self, stats: dict) -> None: super().__init__() self.stats = stats def render(self) -> RenderableType: total_played = self.stats["played"] total_win = sum(self.stats["stats"]) num_guesses = ( len(self.stats["last_guesses"][0]) // 5 if self.stats["last_result"] else 0 ) data = { "Played": total_played, "Win %": round(total_win / total_played * 100, 1) if total_played else 0, "Current Streak": self.stats.get("current_streak", 0), "Max Streak": self.stats.get("max_streak", 0), } table = Table(*data.keys()) table.add_row(*map(str, data.values())) bars = Table.grid("idx", "bar", padding=(0, 1)) for i, value in enumerate(self.stats["stats"], 1): bars.add_row( str(i), Bar( max(self.stats["stats"]), 0, value, color="rgb(83,141,78)" if i == num_guesses and self.stats["last_result"] else "rgb(58,58,58)", ), ) render_group = Group(table, bars) return RichPanel(render_group, title="Stats") class GameMessage(Widget): def __init__(self) -> None: super().__init__() self.timer = None content: Reactive[str] = Reactive("") def show_eta(self, target: datetime.datetime) -> None: self.target_date = target self.timer = self.set_interval(1, self.refresh) async def clear_eta(self) -> None: if self.timer is not None: await self.timer.stop() self.timer = None def render(self) -> RenderableType: renderable = self.content if self.timer is not None: eta = calculate_eta(self.target_date) if eta is None: self._child_tasks.add(asyncio.create_task(self.clear_eta())) else: renderable += f"\n\nNext wordle: {eta}" renderable = Align.center(renderable, vertical="middle") return RichPanel(renderable, title="Message") class Letter(Widget): label: Reactive[RenderableType] = Reactive("") status: Reactive[int | None] = Reactive(None) def __init__(self, name: str, clickable: bool = False): super().__init__(name) self.name = name self.label = name self.clickable = clickable self.style = IDLE if clickable else EMPTY def render(self) -> RenderableType: return ButtonRenderable( self.label, self.style if self.status is None else LETTER_STATUS[self.status], ) async def on_click(self, event: events.Click) -> None: event.prevent_default().stop() if self.clickable: await self.emit(ButtonPressed(self)) class GuessView(GridView): COLUMN_SIZE = 5 ROW_SIZE = 6 def __init__(self, layout: Layout = None, name: str | None = None) -> None: super().__init__(layout, name) self.slots = [Letter("") for _ in range(self.COLUMN_SIZE * self.ROW_SIZE)] self.current = 0 @property def current_guess(self) -> list[Letter]: start = self.current // self.COLUMN_SIZE * self.COLUMN_SIZE return self.slots[start : start + self.COLUMN_SIZE] @property def current_word(self) -> list[str]: return [b.name for b in self.current_guess] @property def valid_guesses(self) -> list[Sequence[Letter]]: return list( partition( itertools.takewhile(lambda x: bool(x.name), self.slots), self.COLUMN_SIZE, ) ) def input_letter(self, letter: str) -> None: button = self.slots[self.current] if button.name: if self.current % self.COLUMN_SIZE == self.COLUMN_SIZE - 1: # The last letter is filled return self.current += 1 button = self.slots[self.current] button.name = letter button.label = letter def backspace_letter(self) -> None: button = self.slots[self.current] if not button.name: if self.current % self.COLUMN_SIZE == 0: # the first letter return self.current -= 1 button = self.slots[self.current] button.name = button.label = "" async def on_mount(self) -> None: self.grid.set_align("center", "center") self.grid.set_gap(1, 1) self.grid.add_column("column", repeat=self.COLUMN_SIZE, size=7) self.grid.add_row("row", size=3, repeat=self.ROW_SIZE) self.grid.place(*self.slots) def check_solution(self, solution: str) -> bool | None: word = self.current_word letters = self.current_guess self.log("Checking solution") if list(solution) == word: for b in letters: b.status = CORRECT return True counter = Counter(solution) for i, b in enumerate(letters): if solution[i] == b.name: counter[b.name] -= 1 b.status = CORRECT for b in letters: if b.status == CORRECT: continue if counter.get(b.name, 0) <= 0: b.status = ABSENT else: counter[b.name] -= 1 b.status = PRESENT if self.current < self.COLUMN_SIZE * self.ROW_SIZE - 1: self.current += 1 else: return False class KeyboardRow(GridView): def __init__( self, letters: Iterable[str], layout: Layout = None, name: str | None = None ) -> None: super().__init__(layout=layout, name=name) self.children = list(letters) async def on_mount(self) -> None: self.grid.set_align("center", "center") self.grid.set_gap(1, 1) self.grid.add_column("column", repeat=len(self.children), size=7) self.grid.add_row("row", size=3) self.grid.place(*self.children) class WordleApp(App): KEYBOARD = ["QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM"] def on_key(self, event: events.Key) -> None: if self.result is not None: if event.key == "c": self.copy_result() return self.message.content = "" if event.key in string.ascii_letters: self.guess.input_letter(event.key.upper()) elif event.key == "enter": self.check_input() elif event.key == "ctrl+h": self.guess.backspace_letter() def check_input(self) -> bool | None: current = self.guess.current_guess current_word = "".join(self.guess.current_word).lower() if "" in self.guess.current_word: self.message.content = "Not enough letters" return if current_word not in Ta and current_word not in La: self.message.content = "Not in word list" return self.result = self.guess.check_solution(self.solution) for l in current: button = self.buttons[l.name] button.status = max(button.status or 0, l.status) self.save_statistics() if self.result is not None: self.show_result() def copy_result(self) -> None: guesses = self.guess.valid_guesses trials = len(guesses) if self.result else "x" result = [f"Wordle {self.index} {trials}/6", ""] for row in guesses: result.append("".join(BLOCKS[l.status] for l in row)) text = "\n".join(result) pyperclip.copy(text) old_content = self.message.content self.message.content = "Successfully copied to the clipboard." def restore(): self.message.content = old_content self.message.set_timer(2, restore) def save_statistics(self) -> None: guesses = self.guess.valid_guesses if self.result: self.stats["stats"][len(guesses) - 1] += 1 is_streak = ( "last_played" in self.stats and self.index - self.stats["last_played"] == 1 ) current_streak = self.stats.get("current_streak", 0) if is_streak else 0 if self.result is not None: self.stats["played"] += 1 current_streak += 1 max_streak = max(current_streak, self.stats.get("max_streak", 0)) data = { "last_played": self.index, "last_guesses": ( "".join("".join(str(l.name) for row in guesses for l in row)), "".join("".join(str(l.status) for row in guesses for l in row)), ), "last_result": self.result, "played": self.stats["played"] + 1, "stats": self.stats["stats"], "current_streak": current_streak, "max_streak": max_streak, } self.stats.update(data) self.stats_view.refresh() with open(STATS_JSON, "w") as f: json.dump(data, f, indent=2) def show_result(self) -> None: if self.result: content = "You Win!" else: content = f"You are almost there! The answer is:\n{self.solution}" content += "\nPress 'c' to copy the result." self.message.content = content self.message.show_eta(SEED_DATE + datetime.timedelta(days=self.index + 1)) def handle_button_pressed(self, message: ButtonPressed) -> None: if self.result is not None: return self.message.content = "" if message.sender.name == "enter": self.check_input() elif message.sender.name == "backspace": self.guess.backspace_letter() else: self.guess.input_letter(message.sender.name) def get_index(self) -> int: this_date = datetime.datetime.combine(datetime.date.today(), datetime.time()) return (this_date - SEED_DATE).days def init_game(self) -> None: if self.index > self.stats.get("last_played", -1): self.stats["last_result"] = None return slots = self.guess.slots for i, (letter, status) in enumerate(zip(*self.stats["last_guesses"])): slots[i].name = slots[i].label = letter slots[i].status = int(status) self.buttons[letter].status = max( self.buttons[letter].status or 0, int(status) ) self.result = self.stats["last_result"] self.guess.current = i + 1 if self.result is not None: self.show_result() async def on_mount(self) -> None: self.index = self.get_index() self.solution = La[self.index].upper() self.log("Loading stats", STATS_JSON) if not STATS_JSON.exists(): self.stats = INITIAL_STATS.copy() else: with open(STATS_JSON, "rb") as f: self.stats = json.load(f) self.result: bool | None = None self.buttons = { name: Letter(name, True) for row in self.KEYBOARD for name in row } keyboard_rows = [ KeyboardRow([self.buttons[k] for k in row]) for row in self.KEYBOARD ] # add enter and backspace buttons keyboard_rows[-1].children.insert(0, Button("ENTER", "enter", style=IDLE)) keyboard_rows[-1].children.append(Button("⌫", "backspace", style=IDLE)) view = await self.push_view(DockView()) header = Header() self.message = GameMessage() await view.dock(header, edge="top") subview = DockView() self.guess = GuessView() self.init_game() await subview.dock(self.guess, size=26) await subview.dock(*keyboard_rows, size=4) right_side = DockView() self.stats_view = GameStats(self.stats) await right_side.dock(self.message, self.stats_view) await view.dock(right_side, edge="right", size=40) await view.dock(subview, edge="right") def main(): WordleApp.run(title="WORDLE", log="textual.log") if __name__ == "__main__": main()
from __future__ import annotations import asyncio import datetime import gzip import itertools import json import string from pathlib import Path from typing import Counter, Iterable, Sequence, TypeVar import platformdirs import pyperclip from rich.align import Align from rich.bar import Bar from rich.console import Group, RenderableType from rich.panel import Panel as RichPanel from rich.table import Table from textual import events from textual.app import App from textual.layout import Layout from textual.reactive import Reactive from textual.views import DockView, GridView from textual.widget import Widget from textual.widgets import Button, ButtonPressed, Header from textual.widgets._button import ButtonRenderable BASE_DIR = Path(__file__).parent IDLE = "bold white on rgb(130,130,130)" EMPTY = "bold on rgb(18,18,18)" ABSENT = 0 PRESENT = 1 CORRECT = 2 LETTER_STATUS = { ABSENT: "bold white on rgb(58,58,58)", PRESENT: "bold white on rgb(181,159,59)", CORRECT: "bold white on rgb(83,141,78)", } BLOCKS = {ABSENT: "⬛", PRESENT: "🟨", CORRECT: "🟩"} INITIAL_STATS = { "played": 0, "stats": [0, 0, 0, 0, 0, 0], "current_streak": 0, "max_streak": 0, } SEED_DATE = datetime.datetime.combine(datetime.datetime(2021, 6, 19), datetime.time()) STATS_JSON = Path(platformdirs.user_data_dir("wordle")) / ".stats.json" STATS_JSON.parent.mkdir(exist_ok=True, parents=True) with BASE_DIR.joinpath("La.gz").open("rb") as laf, BASE_DIR.joinpath("Ta.gz").open( "rb" ) as taf: La: list[str] = json.loads(gzip.decompress(laf.read())) Ta: list[str] = json.loads(gzip.decompress(taf.read())) T = TypeVar("T") def partition(l: Iterable[T], size: int) -> Iterable[Sequence[T]]: it = iter(l) return iter(lambda: tuple(itertools.islice(it, size)), ()) def calculate_eta(target_date: datetime.datetime) -> str | None: """Print a human-readable ETA to the next wordle""" units = [3600, 60, 1] now = datetime.datetime.now() dt = (target_date - now).total_seconds() if dt <= 0: return None digits = [] for unit in units: digits.append("%02d" % int(dt // unit)) dt %= unit return f'[green]{":".join(digits)}[/green]' class GameStats(Widget): def __init__(self, stats: dict) -> None: super().__init__() self.stats = stats def render(self) -> RenderableType: total_played = self.stats["played"] total_win = sum(self.stats["stats"]) num_guesses = ( len(self.stats["last_guesses"][0]) // 5 if self.stats["last_result"] else 0 ) data = { "Played": total_played, "Win %": round(total_win / total_played * 100, 1) if total_played else 0, "Current Streak": self.stats.get("current_streak", 0), "Max Streak": self.stats.get("max_streak", 0), } table = Table(*data.keys()) table.add_row(*map(str, data.values())) bars = Table.grid("idx", "bar", padding=(0, 1)) for i, value in enumerate(self.stats["stats"], 1): bars.add_row( str(i), Bar( max(self.stats["stats"]), 0, value, color="rgb(83,141,78)" if i == num_guesses and self.stats["last_result"] else "rgb(58,58,58)", ), ) render_group = Group(table, bars) return RichPanel(render_group, title="Stats") class GameMessage(Widget): def __init__(self) -> None: super().__init__() self.timer = None content: Reactive[str] = Reactive("") def show_eta(self, target: datetime.datetime) -> None: self.target_date = target self.timer = self.set_interval(1, self.refresh) async def clear_eta(self) -> None: if self.timer is not None: await self.timer.stop() self.timer = None def render(self) -> RenderableType: renderable = self.content if self.timer is not None: eta = calculate_eta(self.target_date) if eta is None: self._child_tasks.add(asyncio.create_task(self.clear_eta())) else: renderable += f"\n\nNext wordle: {eta}" renderable = Align.center(renderable, vertical="middle") return RichPanel(renderable, title="Message") class Letter(Widget): label: Reactive[RenderableType] = Reactive("") status: Reactive[int | None] = Reactive(None) def __init__(self, name: str, clickable: bool = False): super().__init__(name) self.name = name self.label = name self.clickable = clickable self.style = IDLE if clickable else EMPTY def render(self) -> RenderableType: return ButtonRenderable( self.label, self.style if self.status is None else LETTER_STATUS[self.status], ) async def on_click(self, event: events.Click) -> None: event.prevent_default().stop() if self.clickable: await self.emit(ButtonPressed(self)) class GuessView(GridView): COLUMN_SIZE = 5 ROW_SIZE = 6 def __init__(self, layout: Layout = None, name: str | None = None) -> None: super().__init__(layout, name) self.slots = [Letter("") for _ in range(self.COLUMN_SIZE * self.ROW_SIZE)] self.current = 0 @property def current_guess(self) -> list[Letter]: start = self.current // self.COLUMN_SIZE * self.COLUMN_SIZE return self.slots[start : start + self.COLUMN_SIZE] @property def current_word(self) -> list[str]: return [b.name for b in self.current_guess] @property def valid_guesses(self) -> list[Sequence[Letter]]: return list( partition( itertools.takewhile(lambda x: bool(x.name), self.slots), self.COLUMN_SIZE, ) ) def input_letter(self, letter: str) -> None: button = self.slots[self.current] if button.name: if self.current % self.COLUMN_SIZE == self.COLUMN_SIZE - 1: # The last letter is filled return self.current += 1 button = self.slots[self.current] button.name = letter button.label = letter def backspace_letter(self) -> None: button = self.slots[self.current] if not button.name: if self.current % self.COLUMN_SIZE == 0: # the first letter return self.current -= 1 button = self.slots[self.current] button.name = button.label = "" async def on_mount(self) -> None: self.grid.set_align("center", "center") self.grid.set_gap(1, 1) self.grid.add_column("column", repeat=self.COLUMN_SIZE, size=7) self.grid.add_row("row", size=3, repeat=self.ROW_SIZE) self.grid.place(*self.slots) def check_solution(self, solution: str) -> bool | None: word = self.current_word letters = self.current_guess self.log("Checking solution") if list(solution) == word: for b in letters: b.status = CORRECT return True counter = Counter(solution) for i, b in enumerate(letters): if solution[i] == b.name: counter[b.name] -= 1 b.status = CORRECT for b in letters: if b.status == CORRECT: continue if counter.get(b.name, 0) <= 0: b.status = ABSENT else: counter[b.name] -= 1 b.status = PRESENT if self.current < self.COLUMN_SIZE * self.ROW_SIZE - 1: self.current += 1 else: return False class KeyboardRow(GridView): def __init__( self, letters: Iterable[str], layout: Layout = None, name: str | None = None ) -> None: super().__init__(layout=layout, name=name) self.children = list(letters) async def on_mount(self) -> None: self.grid.set_align("center", "center") self.grid.set_gap(1, 1) self.grid.add_column("column", repeat=len(self.children), size=7) self.grid.add_row("row", size=3) self.grid.place(*self.children) class WordleApp(App): KEYBOARD = ["QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM"] def on_key(self, event: events.Key) -> None: if self.result is not None: if event.key == "c": self.copy_result() return self.message.content = "" if event.key in string.ascii_letters: self.guess.input_letter(event.key.upper()) elif event.key == "enter": self.check_input() elif event.key == "ctrl+h": self.guess.backspace_letter() def check_input(self) -> bool | None: current = self.guess.current_guess current_word = "".join(self.guess.current_word).lower() if "" in self.guess.current_word: self.message.content = "Not enough letters" return if current_word not in Ta and current_word not in La: self.message.content = "Not in word list" return self.result = self.guess.check_solution(self.solution) for l in current: button = self.buttons[l.name] button.status = max(button.status or 0, l.status) self.save_statistics() if self.result is not None: self.show_result() def copy_result(self) -> None: guesses = self.guess.valid_guesses trials = len(guesses) if self.result else "x" result = [f"Wordle {self.index} {trials}/6", ""] for row in guesses: result.append("".join(BLOCKS[l.status] for l in row)) text = "\n".join(result) pyperclip.copy(text) old_content = self.message.content self.message.content = "Successfully copied to the clipboard." def restore(): self.message.content = old_content self.message.set_timer(2, restore) def save_statistics(self) -> None: guesses = self.guess.valid_guesses if self.result: self.stats["stats"][len(guesses) - 1] += 1 is_streak = ( "last_played" in self.stats and self.index - self.stats["last_played"] == 1 ) current_streak = self.stats.get("current_streak", 0) if is_streak else 0 if self.result is not None: self.stats["played"] += 1 current_streak += 1 max_streak = max(current_streak, self.stats.get("max_streak", 0)) data = { "last_played": self.index, "last_guesses": ( "".join("".join(str(l.name) for row in guesses for l in row)), "".join("".join(str(l.status) for row in guesses for l in row)), ), "last_result": self.result, "played": self.stats["played"] + 1, "stats": self.stats["stats"], "current_streak": current_streak, "max_streak": max_streak, } self.stats.update(data) self.stats_view.refresh() with open(STATS_JSON, "w") as f: json.dump(data, f, indent=2) def show_result(self) -> None: if self.result: content = "You Win!" else: content = f"You are almost there! The answer is:\n{self.solution}" content += "\nPress 'c' to copy the result." self.message.content = content self.message.show_eta(SEED_DATE + datetime.timedelta(days=self.index + 1)) def handle_button_pressed(self, message: ButtonPressed) -> None: if self.result is not None: return self.message.content = "" if message.sender.name == "enter": self.check_input() elif message.sender.name == "backspace": self.guess.backspace_letter() else: self.guess.input_letter(message.sender.name) def get_index(self) -> int: this_date = datetime.datetime.combine(datetime.date.today(), datetime.time()) return (this_date - SEED_DATE).days def init_game(self) -> None: if self.index > self.stats.get("last_played", -1): self.stats["last_result"] = None return slots = self.guess.slots for i, (letter, status) in enumerate(zip(*self.stats["last_guesses"])): slots[i].name = slots[i].label = letter slots[i].status = int(status) self.buttons[letter].status = max( self.buttons[letter].status or 0, int(status) ) self.result = self.stats["last_result"] self.guess.current = i + 1 if self.result is not None: self.show_result() async def on_mount(self) -> None: self.index = self.get_index() self.solution = La[self.index].upper() self.log("Loading stats", STATS_JSON) if not STATS_JSON.exists(): self.stats = INITIAL_STATS.copy() else: with open(STATS_JSON, "rb") as f: self.stats = json.load(f) self.result: bool | None = None self.buttons = { name: Letter(name, True) for row in self.KEYBOARD for name in row } keyboard_rows = [ KeyboardRow([self.buttons[k] for k in row]) for row in self.KEYBOARD ] # add enter and backspace buttons keyboard_rows[-1].children.insert(0, Button("ENTER", "enter", style=IDLE)) keyboard_rows[-1].children.append(Button("⌫", "backspace", style=IDLE)) view = await self.push_view(DockView()) header = Header() self.message = GameMessage() await view.dock(header, edge="top") subview = DockView() self.guess = GuessView() self.init_game() await subview.dock(self.guess, size=26) await subview.dock(*keyboard_rows, size=4) right_side = DockView() self.stats_view = GameStats(self.stats) await right_side.dock(self.message, self.stats_view) await view.dock(right_side, edge="right", size=40) await view.dock(subview, edge="right") def main(): WordleApp.run(title="WORDLE", log="textual.log") if __name__ == "__main__": main()
""" serverextension for starters """ from .handlers import add_handlers from .manager import StarterManager def load_jupyter_server_extension(nbapp): """create a StarterManager and add handlers""" manager = StarterManager(parent=nbapp) add_handlers(nbapp, manager) nbapp.log.info(f"""💡 starters: {", ".join(manager.starter_names)}""")
""" serverextension for starters """ from .handlers import add_handlers from .manager import StarterManager def load_jupyter_server_extension(nbapp): """create a StarterManager and add handlers""" manager = StarterManager(parent=nbapp) add_handlers(nbapp, manager) nbapp.log.info(f"""💡 starters: {", ".join(manager.starter_names)}""")
#!/usr/bin/env python3 """ Rules for building C/API module with f2py2e. Here is a skeleton of a new wrapper function (13Dec2001): wrapper_function(args) declarations get_python_arguments, say, `a' and `b' get_a_from_python if (successful) { get_b_from_python if (successful) { callfortran if (successful) { put_a_to_python if (successful) { put_b_to_python if (successful) { buildvalue = ... } } } } cleanup_b } cleanup_a return buildvalue Copyright 1999,2000 Pearu Peterson all rights reserved, Pearu Peterson <pearu@ioc.ee> Permission to use, modify, and distribute this software is given under the terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/08/30 08:58:42 $ Pearu Peterson """ __version__ = "$Revision: 1.129 $"[10:-1] from . import __version__ f2py_version = __version__.version from .. import version as _numpy_version numpy_version = _numpy_version.version import os import time import copy from .auxfuncs import ( applyrules, debugcapi, dictappend, errmess, gentitle, getargs2, hascallstatement, hasexternals, hasinitvalue, hasnote, hasresultnote, isarray, isarrayofstrings, iscomplex, iscomplexarray, iscomplexfunction, iscomplexfunction_warn, isdummyroutine, isexternal, isfunction, isfunction_wrap, isint1array, isintent_aux, isintent_c, isintent_callback, isintent_copy, isintent_hide, isintent_inout, isintent_nothide, isintent_out, isintent_overwrite, islogical, islong_complex, islong_double, islong_doublefunction, islong_long, islong_longfunction, ismoduleroutine, isoptional, isrequired, isscalar, issigned_long_longarray, isstring, isstringarray, isstringfunction, issubroutine, issubroutine_wrap, isthreadsafe, isunsigned, isunsigned_char, isunsigned_chararray, isunsigned_long_long, isunsigned_long_longarray, isunsigned_short, isunsigned_shortarray, l_and, l_not, l_or, outmess, replace, stripcomma, requiresf90wrapper ) from . import capi_maps from . import cfuncs from . import common_rules from . import use_rules from . import f90mod_rules from . import func2subr options = {} sepdict = {} #for k in ['need_cfuncs']: sepdict[k]=',' for k in ['decl', 'frompyobj', 'cleanupfrompyobj', 'topyarr', 'method', 'pyobjfrom', 'closepyobjfrom', 'freemem', 'userincludes', 'includes0', 'includes', 'typedefs', 'typedefs_generated', 'cppmacros', 'cfuncs', 'callbacks', 'latexdoc', 'restdoc', 'routine_defs', 'externroutines', 'initf2pywraphooks', 'commonhooks', 'initcommonhooks', 'f90modhooks', 'initf90modhooks']: sepdict[k] = '\n' #################### Rules for C/API module ################# generationtime = int(os.environ.get('SOURCE_DATE_EPOCH', time.time())) module_rules = { 'modulebody': """\ /* File: #modulename#module.c * This file is auto-generated with f2py (version:#f2py_version#). * f2py is a Fortran to Python Interface Generator (FPIG), Second Edition, * written by Pearu Peterson <pearu@cens.ioc.ee>. * Generation date: """ + time.asctime(time.gmtime(generationtime)) + """ * Do not edit this file directly unless you know what you are doing!!! */ #ifdef __cplusplus extern \"C\" { #endif """ + gentitle("See f2py2e/cfuncs.py: includes") + """ #includes# #includes0# """ + gentitle("See f2py2e/rules.py: mod_rules['modulebody']") + """ static PyObject *#modulename#_error; static PyObject *#modulename#_module; """ + gentitle("See f2py2e/cfuncs.py: typedefs") + """ #typedefs# """ + gentitle("See f2py2e/cfuncs.py: typedefs_generated") + """ #typedefs_generated# """ + gentitle("See f2py2e/cfuncs.py: cppmacros") + """ #cppmacros# """ + gentitle("See f2py2e/cfuncs.py: cfuncs") + """ #cfuncs# """ + gentitle("See f2py2e/cfuncs.py: userincludes") + """ #userincludes# """ + gentitle("See f2py2e/capi_rules.py: usercode") + """ #usercode# /* See f2py2e/rules.py */ #externroutines# """ + gentitle("See f2py2e/capi_rules.py: usercode1") + """ #usercode1# """ + gentitle("See f2py2e/cb_rules.py: buildcallback") + """ #callbacks# """ + gentitle("See f2py2e/rules.py: buildapi") + """ #body# """ + gentitle("See f2py2e/f90mod_rules.py: buildhooks") + """ #f90modhooks# """ + gentitle("See f2py2e/rules.py: module_rules['modulebody']") + """ """ + gentitle("See f2py2e/common_rules.py: buildhooks") + """ #commonhooks# """ + gentitle("See f2py2e/rules.py") + """ static FortranDataDef f2py_routine_defs[] = { #routine_defs# \t{NULL} }; static PyMethodDef f2py_module_methods[] = { #pymethoddef# \t{NULL,NULL} }; static struct PyModuleDef moduledef = { \tPyModuleDef_HEAD_INIT, \t"#modulename#", \tNULL, \t-1, \tf2py_module_methods, \tNULL, \tNULL, \tNULL, \tNULL }; PyMODINIT_FUNC PyInit_#modulename#(void) { \tint i; \tPyObject *m,*d, *s, *tmp; \tm = #modulename#_module = PyModule_Create(&moduledef); \tPy_SET_TYPE(&PyFortran_Type, &PyType_Type); \timport_array(); \tif (PyErr_Occurred()) \t\t{PyErr_SetString(PyExc_ImportError, \"can't initialize module #modulename# (failed to import numpy)\"); return m;} \td = PyModule_GetDict(m); \ts = PyUnicode_FromString(\"$R""" + """evision: $\"); \tPyDict_SetItemString(d, \"__version__\", s); \tPy_DECREF(s); \ts = PyUnicode_FromString( \t\t\"This module '#modulename#' is auto-generated with f2py (version:#f2py_version#).\\nFunctions:\\n\"\n#docs#\".\"); \tPyDict_SetItemString(d, \"__doc__\", s); \tPy_DECREF(s); \ts = PyUnicode_FromString(\"""" + numpy_version + """\"); \tPyDict_SetItemString(d, \"__f2py_numpy_version__\", s); \tPy_DECREF(s); \t#modulename#_error = PyErr_NewException (\"#modulename#.error\", NULL, NULL); \t/* \t * Store the error object inside the dict, so that it could get deallocated. \t * (in practice, this is a module, so it likely will not and cannot.) \t */ \tPyDict_SetItemString(d, \"_#modulename#_error\", #modulename#_error); \tPy_DECREF(#modulename#_error); \tfor(i=0;f2py_routine_defs[i].name!=NULL;i++) { \t\ttmp = PyFortranObject_NewAsAttr(&f2py_routine_defs[i]); \t\tPyDict_SetItemString(d, f2py_routine_defs[i].name, tmp); \t\tPy_DECREF(tmp); \t} #initf2pywraphooks# #initf90modhooks# #initcommonhooks# #interface_usercode# #ifdef F2PY_REPORT_ATEXIT \tif (! PyErr_Occurred()) \t\ton_exit(f2py_report_on_exit,(void*)\"#modulename#\"); #endif \treturn m; } #ifdef __cplusplus } #endif """, 'separatorsfor': {'latexdoc': '\n\n', 'restdoc': '\n\n'}, 'latexdoc': ['\\section{Module \\texttt{#texmodulename#}}\n', '#modnote#\n', '#latexdoc#'], 'restdoc': ['Module #modulename#\n' + '=' * 80, '\n#restdoc#'] } defmod_rules = [ {'body': '/*eof body*/', 'method': '/*eof method*/', 'externroutines': '/*eof externroutines*/', 'routine_defs': '/*eof routine_defs*/', 'initf90modhooks': '/*eof initf90modhooks*/', 'initf2pywraphooks': '/*eof initf2pywraphooks*/', 'initcommonhooks': '/*eof initcommonhooks*/', 'latexdoc': '', 'restdoc': '', 'modnote': {hasnote: '#note#', l_not(hasnote): ''}, } ] routine_rules = { 'separatorsfor': sepdict, 'body': """ #begintitle# static char doc_#apiname#[] = \"\\\n#docreturn##name#(#docsignatureshort#)\\n\\nWrapper for ``#name#``.\\\n\\n#docstrsigns#\"; /* #declfortranroutine# */ static PyObject *#apiname#(const PyObject *capi_self, PyObject *capi_args, PyObject *capi_keywds, #functype# (*f2py_func)(#callprotoargument#)) { PyObject * volatile capi_buildvalue = NULL; volatile int f2py_success = 1; #decl# static char *capi_kwlist[] = {#kwlist##kwlistopt##kwlistxa#NULL}; #usercode# #routdebugenter# #ifdef F2PY_REPORT_ATEXIT f2py_start_clock(); #endif if (!PyArg_ParseTupleAndKeywords(capi_args,capi_keywds,\\ \"#argformat#|#keyformat##xaformat#:#pyname#\",\\ capi_kwlist#args_capi##keys_capi##keys_xa#))\n return NULL; #frompyobj# /*end of frompyobj*/ #ifdef F2PY_REPORT_ATEXIT f2py_start_call_clock(); #endif #callfortranroutine# if (PyErr_Occurred()) f2py_success = 0; #ifdef F2PY_REPORT_ATEXIT f2py_stop_call_clock(); #endif /*end of callfortranroutine*/ if (f2py_success) { #pyobjfrom# /*end of pyobjfrom*/ CFUNCSMESS(\"Building return value.\\n\"); capi_buildvalue = Py_BuildValue(\"#returnformat#\"#return#); /*closepyobjfrom*/ #closepyobjfrom# } /*if (f2py_success) after callfortranroutine*/ /*cleanupfrompyobj*/ #cleanupfrompyobj# if (capi_buildvalue == NULL) { #routdebugfailure# } else { #routdebugleave# } CFUNCSMESS(\"Freeing memory.\\n\"); #freemem# #ifdef F2PY_REPORT_ATEXIT f2py_stop_clock(); #endif return capi_buildvalue; } #endtitle# """, 'routine_defs': '#routine_def#', 'initf2pywraphooks': '#initf2pywraphook#', 'externroutines': '#declfortranroutine#', 'doc': '#docreturn##name#(#docsignature#)', 'docshort': '#docreturn##name#(#docsignatureshort#)', 'docs': '"\t#docreturn##name#(#docsignature#)\\n"\n', 'need': ['arrayobject.h', 'CFUNCSMESS', 'MINMAX'], 'cppmacros': {debugcapi: '#define DEBUGCFUNCS'}, 'latexdoc': ['\\subsection{Wrapper function \\texttt{#texname#}}\n', """ \\noindent{{}\\verb@#docreturn##name#@{}}\\texttt{(#latexdocsignatureshort#)} #routnote# #latexdocstrsigns# """], 'restdoc': ['Wrapped function ``#name#``\n' + '-' * 80, ] } ################## Rules for C/API function ############## rout_rules = [ { # Init 'separatorsfor': {'callfortranroutine': '\n', 'routdebugenter': '\n', 'decl': '\n', 'routdebugleave': '\n', 'routdebugfailure': '\n', 'setjmpbuf': ' || ', 'docstrreq': '\n', 'docstropt': '\n', 'docstrout': '\n', 'docstrcbs': '\n', 'docstrsigns': '\\n"\n"', 'latexdocstrsigns': '\n', 'latexdocstrreq': '\n', 'latexdocstropt': '\n', 'latexdocstrout': '\n', 'latexdocstrcbs': '\n', }, 'kwlist': '', 'kwlistopt': '', 'callfortran': '', 'callfortranappend': '', 'docsign': '', 'docsignopt': '', 'decl': '/*decl*/', 'freemem': '/*freemem*/', 'docsignshort': '', 'docsignoptshort': '', 'docstrsigns': '', 'latexdocstrsigns': '', 'docstrreq': '\\nParameters\\n----------', 'docstropt': '\\nOther Parameters\\n----------------', 'docstrout': '\\nReturns\\n-------', 'docstrcbs': '\\nNotes\\n-----\\nCall-back functions::\\n', 'latexdocstrreq': '\\noindent Required arguments:', 'latexdocstropt': '\\noindent Optional arguments:', 'latexdocstrout': '\\noindent Return objects:', 'latexdocstrcbs': '\\noindent Call-back functions:', 'args_capi': '', 'keys_capi': '', 'functype': '', 'frompyobj': '/*frompyobj*/', # this list will be reversed 'cleanupfrompyobj': ['/*end of cleanupfrompyobj*/'], 'pyobjfrom': '/*pyobjfrom*/', # this list will be reversed 'closepyobjfrom': ['/*end of closepyobjfrom*/'], 'topyarr': '/*topyarr*/', 'routdebugleave': '/*routdebugleave*/', 'routdebugenter': '/*routdebugenter*/', 'routdebugfailure': '/*routdebugfailure*/', 'callfortranroutine': '/*callfortranroutine*/', 'argformat': '', 'keyformat': '', 'need_cfuncs': '', 'docreturn': '', 'return': '', 'returnformat': '', 'rformat': '', 'kwlistxa': '', 'keys_xa': '', 'xaformat': '', 'docsignxa': '', 'docsignxashort': '', 'initf2pywraphook': '', 'routnote': {hasnote: '--- #note#', l_not(hasnote): ''}, }, { 'apiname': 'f2py_rout_#modulename#_#name#', 'pyname': '#modulename#.#name#', 'decl': '', '_check': l_not(ismoduleroutine) }, { 'apiname': 'f2py_rout_#modulename#_#f90modulename#_#name#', 'pyname': '#modulename#.#f90modulename#.#name#', 'decl': '', '_check': ismoduleroutine }, { # Subroutine 'functype': 'void', 'declfortranroutine': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'extern void #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);', l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): 'extern void #fortranname#(#callprotoargument#);', ismoduleroutine: '', isdummyroutine: '' }, 'routine_def': {l_not(l_or(ismoduleroutine, isintent_c, isdummyroutine)): '\t{\'#name#\',-1,{{-1}},0,(char *)#F_FUNC#(#fortranname#,#FORTRANNAME#),(f2py_init_func)#apiname#,doc_#apiname#},', l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): '\t{\"#name#\",-1,{{-1}},0,(char *)#fortranname#,(f2py_init_func)#apiname#,doc_#apiname#},', l_and(l_not(ismoduleroutine), isdummyroutine): '\t{\"#name#\",-1,{{-1}},0,NULL,(f2py_init_func)#apiname#,doc_#apiname#},', }, 'need': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'F_FUNC'}, 'callfortranroutine': [ {debugcapi: [ """\tfprintf(stderr,\"debug-capi:Fortran subroutine `#fortranname#(#callfortran#)\'\\n\");"""]}, {hasexternals: """\ \t\tif (#setjmpbuf#) { \t\t\tf2py_success = 0; \t\t} else {"""}, {isthreadsafe: '\t\t\tPy_BEGIN_ALLOW_THREADS'}, {hascallstatement: '''\t\t\t\t#callstatement#; \t\t\t\t/*(*f2py_func)(#callfortran#);*/'''}, {l_not(l_or(hascallstatement, isdummyroutine)) : '\t\t\t\t(*f2py_func)(#callfortran#);'}, {isthreadsafe: '\t\t\tPy_END_ALLOW_THREADS'}, {hasexternals: """\t\t}"""} ], '_check': l_and(issubroutine, l_not(issubroutine_wrap)), }, { # Wrapped function 'functype': 'void', 'declfortranroutine': {l_not(l_or(ismoduleroutine, isdummyroutine)): 'extern void #F_WRAPPEDFUNC#(#name_lower#,#NAME#)(#callprotoargument#);', isdummyroutine: '', }, 'routine_def': {l_not(l_or(ismoduleroutine, isdummyroutine)): '\t{\'#name#\',-1,{{-1}},0,(char *)#F_WRAPPEDFUNC#(#name_lower#,#NAME#),(f2py_init_func)#apiname#,doc_#apiname#},', isdummyroutine: '\t{\"#name#\",-1,{{-1}},0,NULL,(f2py_init_func)#apiname#,doc_#apiname#},', }, 'initf2pywraphook': {l_not(l_or(ismoduleroutine, isdummyroutine)): ''' { extern #ctype# #F_FUNC#(#name_lower#,#NAME#)(void); PyObject* o = PyDict_GetItemString(d,"#name#"); tmp = F2PyCapsule_FromVoidPtr((void*)#F_FUNC#(#name_lower#,#NAME#),NULL); PyObject_SetAttrString(o,"_cpointer", tmp); Py_DECREF(tmp); s = PyUnicode_FromString("#name#"); PyObject_SetAttrString(o,"__name__", s); Py_DECREF(s); } '''}, 'need': {l_not(l_or(ismoduleroutine, isdummyroutine)): ['F_WRAPPEDFUNC', 'F_FUNC']}, 'callfortranroutine': [ {debugcapi: [ """\tfprintf(stderr,\"debug-capi:Fortran subroutine `f2pywrap#name_lower#(#callfortran#)\'\\n\");"""]}, {hasexternals: """\ \tif (#setjmpbuf#) { \t\tf2py_success = 0; \t} else {"""}, {isthreadsafe: '\tPy_BEGIN_ALLOW_THREADS'}, {l_not(l_or(hascallstatement, isdummyroutine)) : '\t(*f2py_func)(#callfortran#);'}, {hascallstatement: '\t#callstatement#;\n\t/*(*f2py_func)(#callfortran#);*/'}, {isthreadsafe: '\tPy_END_ALLOW_THREADS'}, {hasexternals: '\t}'} ], '_check': isfunction_wrap, }, { # Wrapped subroutine 'functype': 'void', 'declfortranroutine': {l_not(l_or(ismoduleroutine, isdummyroutine)): 'extern void #F_WRAPPEDFUNC#(#name_lower#,#NAME#)(#callprotoargument#);', isdummyroutine: '', }, 'routine_def': {l_not(l_or(ismoduleroutine, isdummyroutine)): '\t{\'#name#\',-1,{{-1}},0,(char *)#F_WRAPPEDFUNC#(#name_lower#,#NAME#),(f2py_init_func)#apiname#,doc_#apiname#},', isdummyroutine: '\t{\"#name#\",-1,{{-1}},0,NULL,(f2py_init_func)#apiname#,doc_#apiname#},', }, 'initf2pywraphook': {l_not(l_or(ismoduleroutine, isdummyroutine)): ''' { extern void #F_FUNC#(#name_lower#,#NAME#)(void); PyObject* o = PyDict_GetItemString(d,"#name#"); tmp = F2PyCapsule_FromVoidPtr((void*)#F_FUNC#(#name_lower#,#NAME#),NULL); PyObject_SetAttrString(o,"_cpointer", tmp); Py_DECREF(tmp); s = PyUnicode_FromString("#name#"); PyObject_SetAttrString(o,"__name__", s); Py_DECREF(s); } '''}, 'need': {l_not(l_or(ismoduleroutine, isdummyroutine)): ['F_WRAPPEDFUNC', 'F_FUNC']}, 'callfortranroutine': [ {debugcapi: [ """\tfprintf(stderr,\"debug-capi:Fortran subroutine `f2pywrap#name_lower#(#callfortran#)\'\\n\");"""]}, {hasexternals: """\ \tif (#setjmpbuf#) { \t\tf2py_success = 0; \t} else {"""}, {isthreadsafe: '\tPy_BEGIN_ALLOW_THREADS'}, {l_not(l_or(hascallstatement, isdummyroutine)) : '\t(*f2py_func)(#callfortran#);'}, {hascallstatement: '\t#callstatement#;\n\t/*(*f2py_func)(#callfortran#);*/'}, {isthreadsafe: '\tPy_END_ALLOW_THREADS'}, {hasexternals: '\t}'} ], '_check': issubroutine_wrap, }, { # Function 'functype': '#ctype#', 'docreturn': {l_not(isintent_hide): '#rname#,'}, 'docstrout': '#pydocsignout#', 'latexdocstrout': ['\\item[]{{}\\verb@#pydocsignout#@{}}', {hasresultnote: '--- #resultnote#'}], 'callfortranroutine': [{l_and(debugcapi, isstringfunction): """\ #ifdef USESCOMPAQFORTRAN \tfprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callcompaqfortran#)\\n\"); #else \tfprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callfortran#)\\n\"); #endif """}, {l_and(debugcapi, l_not(isstringfunction)): """\ \tfprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callfortran#)\\n\"); """} ], '_check': l_and(isfunction, l_not(isfunction_wrap)) }, { # Scalar function 'declfortranroutine': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'extern #ctype# #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);', l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): 'extern #ctype# #fortranname#(#callprotoargument#);', isdummyroutine: '' }, 'routine_def': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): '\t{\'#name#\',-1,{{-1}},0,(char *)#F_FUNC#(#fortranname#,#FORTRANNAME#),(f2py_init_func)#apiname#,doc_#apiname#},', l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): '\t{\"#name#\",-1,{{-1}},0,(char *)#fortranname#,(f2py_init_func)#apiname#,doc_#apiname#},', isdummyroutine: '\t{\"#name#\",-1,{{-1}},0,NULL,(f2py_init_func)#apiname#,doc_#apiname#},', }, 'decl': [{iscomplexfunction_warn: '\t#ctype# #name#_return_value={0,0};', l_not(iscomplexfunction): '\t#ctype# #name#_return_value=0;'}, {iscomplexfunction: '\tPyObject *#name#_return_value_capi = Py_None;'} ], 'callfortranroutine': [ {hasexternals: """\ \tif (#setjmpbuf#) { \t\tf2py_success = 0; \t} else {"""}, {isthreadsafe: '\tPy_BEGIN_ALLOW_THREADS'}, {hascallstatement: '''\t#callstatement#; /*\t#name#_return_value = (*f2py_func)(#callfortran#);*/ '''}, {l_not(l_or(hascallstatement, isdummyroutine)) : '\t#name#_return_value = (*f2py_func)(#callfortran#);'}, {isthreadsafe: '\tPy_END_ALLOW_THREADS'}, {hasexternals: '\t}'}, {l_and(debugcapi, iscomplexfunction) : '\tfprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value.r,#name#_return_value.i);'}, {l_and(debugcapi, l_not(iscomplexfunction)): '\tfprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value);'}], 'pyobjfrom': {iscomplexfunction: '\t#name#_return_value_capi = pyobj_from_#ctype#1(#name#_return_value);'}, 'need': [{l_not(isdummyroutine): 'F_FUNC'}, {iscomplexfunction: 'pyobj_from_#ctype#1'}, {islong_longfunction: 'long_long'}, {islong_doublefunction: 'long_double'}], 'returnformat': {l_not(isintent_hide): '#rformat#'}, 'return': {iscomplexfunction: ',#name#_return_value_capi', l_not(l_or(iscomplexfunction, isintent_hide)): ',#name#_return_value'}, '_check': l_and(isfunction, l_not(isstringfunction), l_not(isfunction_wrap)) }, { # String function # in use for --no-wrap 'declfortranroutine': 'extern void #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);', 'routine_def': {l_not(l_or(ismoduleroutine, isintent_c)): '\t{\"#name#\",-1,{{-1}},0,(char *)#F_FUNC#(#fortranname#,#FORTRANNAME#),(f2py_init_func)#apiname#,doc_#apiname#},', l_and(l_not(ismoduleroutine), isintent_c): '\t{\"#name#\",-1,{{-1}},0,(char *)#fortranname#,(f2py_init_func)#apiname#,doc_#apiname#},' }, 'decl': ['\t#ctype# #name#_return_value = NULL;', '\tint #name#_return_value_len = 0;'], 'callfortran':'#name#_return_value,#name#_return_value_len,', 'callfortranroutine':['\t#name#_return_value_len = #rlength#;', '\tif ((#name#_return_value = (string)malloc(sizeof(char)*(#name#_return_value_len+1))) == NULL) {', '\t\tPyErr_SetString(PyExc_MemoryError, \"out of memory\");', '\t\tf2py_success = 0;', '\t} else {', "\t\t(#name#_return_value)[#name#_return_value_len] = '\\0';", '\t}', '\tif (f2py_success) {', {hasexternals: """\ \t\tif (#setjmpbuf#) { \t\t\tf2py_success = 0; \t\t} else {"""}, {isthreadsafe: '\t\tPy_BEGIN_ALLOW_THREADS'}, """\ #ifdef USESCOMPAQFORTRAN \t\t(*f2py_func)(#callcompaqfortran#); #else \t\t(*f2py_func)(#callfortran#); #endif """, {isthreadsafe: '\t\tPy_END_ALLOW_THREADS'}, {hasexternals: '\t\t}'}, {debugcapi: '\t\tfprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value_len,#name#_return_value);'}, '\t} /* if (f2py_success) after (string)malloc */', ], 'returnformat': '#rformat#', 'return': ',#name#_return_value', 'freemem': '\tSTRINGFREE(#name#_return_value);', 'need': ['F_FUNC', '#ctype#', 'STRINGFREE'], '_check':l_and(isstringfunction, l_not(isfunction_wrap)) # ???obsolete }, { # Debugging 'routdebugenter': '\tfprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#(#docsignature#)\\n");', 'routdebugleave': '\tfprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#: successful.\\n");', 'routdebugfailure': '\tfprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#: failure.\\n");', '_check': debugcapi } ] ################ Rules for arguments ################## typedef_need_dict = {islong_long: 'long_long', islong_double: 'long_double', islong_complex: 'complex_long_double', isunsigned_char: 'unsigned_char', isunsigned_short: 'unsigned_short', isunsigned: 'unsigned', isunsigned_long_long: 'unsigned_long_long', isunsigned_chararray: 'unsigned_char', isunsigned_shortarray: 'unsigned_short', isunsigned_long_longarray: 'unsigned_long_long', issigned_long_longarray: 'long_long', } aux_rules = [ { 'separatorsfor': sepdict }, { # Common 'frompyobj': ['\t/* Processing auxiliary variable #varname# */', {debugcapi: '\tfprintf(stderr,"#vardebuginfo#\\n");'}, ], 'cleanupfrompyobj': '\t/* End of cleaning variable #varname# */', 'need': typedef_need_dict, }, # Scalars (not complex) { # Common 'decl': '\t#ctype# #varname# = 0;', 'need': {hasinitvalue: 'math.h'}, 'frompyobj': {hasinitvalue: '\t#varname# = #init#;'}, '_check': l_and(isscalar, l_not(iscomplex)), }, { 'return': ',#varname#', 'docstrout': '#pydocsignout#', 'docreturn': '#outvarname#,', 'returnformat': '#varrformat#', '_check': l_and(isscalar, l_not(iscomplex), isintent_out), }, # Complex scalars { # Common 'decl': '\t#ctype# #varname#;', 'frompyobj': {hasinitvalue: '\t#varname#.r = #init.r#, #varname#.i = #init.i#;'}, '_check': iscomplex }, # String { # Common 'decl': ['\t#ctype# #varname# = NULL;', '\tint slen(#varname#);', ], 'need':['len..'], '_check':isstring }, # Array { # Common 'decl': ['\t#ctype# *#varname# = NULL;', '\tnpy_intp #varname#_Dims[#rank#] = {#rank*[-1]#};', '\tconst int #varname#_Rank = #rank#;', ], 'need':['len..', {hasinitvalue: 'forcomb'}, {hasinitvalue: 'CFUNCSMESS'}], '_check': isarray }, # Scalararray { # Common '_check': l_and(isarray, l_not(iscomplexarray)) }, { # Not hidden '_check': l_and(isarray, l_not(iscomplexarray), isintent_nothide) }, # Integer*1 array {'need': '#ctype#', '_check': isint1array, '_depend': '' }, # Integer*-1 array {'need': '#ctype#', '_check': isunsigned_chararray, '_depend': '' }, # Integer*-2 array {'need': '#ctype#', '_check': isunsigned_shortarray, '_depend': '' }, # Integer*-8 array {'need': '#ctype#', '_check': isunsigned_long_longarray, '_depend': '' }, # Complexarray {'need': '#ctype#', '_check': iscomplexarray, '_depend': '' }, # Stringarray { 'callfortranappend': {isarrayofstrings: 'flen(#varname#),'}, 'need': 'string', '_check': isstringarray } ] arg_rules = [ { 'separatorsfor': sepdict }, { # Common 'frompyobj': ['\t/* Processing variable #varname# */', {debugcapi: '\tfprintf(stderr,"#vardebuginfo#\\n");'}, ], 'cleanupfrompyobj': '\t/* End of cleaning variable #varname# */', '_depend': '', 'need': typedef_need_dict, }, # Doc signatures { 'docstropt': {l_and(isoptional, isintent_nothide): '#pydocsign#'}, 'docstrreq': {l_and(isrequired, isintent_nothide): '#pydocsign#'}, 'docstrout': {isintent_out: '#pydocsignout#'}, 'latexdocstropt': {l_and(isoptional, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}', {hasnote: '--- #note#'}]}, 'latexdocstrreq': {l_and(isrequired, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}', {hasnote: '--- #note#'}]}, 'latexdocstrout': {isintent_out: ['\\item[]{{}\\verb@#pydocsignout#@{}}', {l_and(hasnote, isintent_hide): '--- #note#', l_and(hasnote, isintent_nothide): '--- See above.'}]}, 'depend': '' }, # Required/Optional arguments { 'kwlist': '"#varname#",', 'docsign': '#varname#,', '_check': l_and(isintent_nothide, l_not(isoptional)) }, { 'kwlistopt': '"#varname#",', 'docsignopt': '#varname#=#showinit#,', 'docsignoptshort': '#varname#,', '_check': l_and(isintent_nothide, isoptional) }, # Docstring/BuildValue { 'docreturn': '#outvarname#,', 'returnformat': '#varrformat#', '_check': isintent_out }, # Externals (call-back functions) { # Common 'docsignxa': {isintent_nothide: '#varname#_extra_args=(),'}, 'docsignxashort': {isintent_nothide: '#varname#_extra_args,'}, 'docstropt': {isintent_nothide: '#varname#_extra_args : input tuple, optional\\n Default: ()'}, 'docstrcbs': '#cbdocstr#', 'latexdocstrcbs': '\\item[] #cblatexdocstr#', 'latexdocstropt': {isintent_nothide: '\\item[]{{}\\verb@#varname#_extra_args := () input tuple@{}} --- Extra arguments for call-back function {{}\\verb@#varname#@{}}.'}, 'decl': [' #cbname#_t #varname#_cb = { Py_None, NULL, 0 };', ' #cbname#_t *#varname#_cb_ptr = &#varname#_cb;', ' PyTupleObject *#varname#_xa_capi = NULL;', {l_not(isintent_callback): ' #cbname#_typedef #varname#_cptr;'} ], 'kwlistxa': {isintent_nothide: '"#varname#_extra_args",'}, 'argformat': {isrequired: 'O'}, 'keyformat': {isoptional: 'O'}, 'xaformat': {isintent_nothide: 'O!'}, 'args_capi': {isrequired: ',&#varname#_cb.capi'}, 'keys_capi': {isoptional: ',&#varname#_cb.capi'}, 'keys_xa': ',&PyTuple_Type,&#varname#_xa_capi', 'setjmpbuf': '(setjmp(#varname#_cb.jmpbuf))', 'callfortran': {l_not(isintent_callback): '#varname#_cptr,'}, 'need': ['#cbname#', 'setjmp.h'], '_check':isexternal }, { 'frompyobj': [{l_not(isintent_callback): """\ if(F2PyCapsule_Check(#varname#_cb.capi)) { #varname#_cptr = F2PyCapsule_AsVoidPtr(#varname#_cb.capi); } else { #varname#_cptr = #cbname#; } """}, {isintent_callback: """\ if (#varname#_cb.capi==Py_None) { #varname#_cb.capi = PyObject_GetAttrString(#modulename#_module,\"#varname#\"); if (#varname#_cb.capi) { if (#varname#_xa_capi==NULL) { if (PyObject_HasAttrString(#modulename#_module,\"#varname#_extra_args\")) { PyObject* capi_tmp = PyObject_GetAttrString(#modulename#_module,\"#varname#_extra_args\"); if (capi_tmp) { #varname#_xa_capi = (PyTupleObject *)PySequence_Tuple(capi_tmp); Py_DECREF(capi_tmp); } else { #varname#_xa_capi = (PyTupleObject *)Py_BuildValue(\"()\"); } if (#varname#_xa_capi==NULL) { PyErr_SetString(#modulename#_error,\"Failed to convert #modulename#.#varname#_extra_args to tuple.\\n\"); return NULL; } } } } if (#varname#_cb.capi==NULL) { PyErr_SetString(#modulename#_error,\"Callback #varname# not defined (as an argument or module #modulename# attribute).\\n\"); return NULL; } } """}, """\ if (create_cb_arglist(#varname#_cb.capi,#varname#_xa_capi,#maxnofargs#,#nofoptargs#,&#varname#_cb.nofargs,&#varname#_cb.args_capi,\"failed in processing argument list for call-back #varname#.\")) { """, {debugcapi: ["""\ fprintf(stderr,\"debug-capi:Assuming %d arguments; at most #maxnofargs#(-#nofoptargs#) is expected.\\n\",#varname#_cb.nofargs); CFUNCSMESSPY(\"for #varname#=\",#cbname#_capi);""", {l_not(isintent_callback): """ fprintf(stderr,\"#vardebugshowvalue# (call-back in C).\\n\",#cbname#);"""}]}, """\ CFUNCSMESS(\"Saving callback variables for `#varname#`.\\n\"); #varname#_cb_ptr = swap_active_#cbname#(#varname#_cb_ptr);""", ], 'cleanupfrompyobj': """\ CFUNCSMESS(\"Restoring callback variables for `#varname#`.\\n\"); #varname#_cb_ptr = swap_active_#cbname#(#varname#_cb_ptr); Py_DECREF(#varname#_cb.args_capi); }""", 'need': ['SWAP', 'create_cb_arglist'], '_check':isexternal, '_depend':'' }, # Scalars (not complex) { # Common 'decl': '\t#ctype# #varname# = 0;', 'pyobjfrom': {debugcapi: '\tfprintf(stderr,"#vardebugshowvalue#\\n",#varname#);'}, 'callfortran': {isintent_c: '#varname#,', l_not(isintent_c): '&#varname#,'}, 'return': {isintent_out: ',#varname#'}, '_check': l_and(isscalar, l_not(iscomplex)) }, { 'need': {hasinitvalue: 'math.h'}, '_check': l_and(isscalar, l_not(iscomplex)), }, { # Not hidden 'decl': '\tPyObject *#varname#_capi = Py_None;', 'argformat': {isrequired: 'O'}, 'keyformat': {isoptional: 'O'}, 'args_capi': {isrequired: ',&#varname#_capi'}, 'keys_capi': {isoptional: ',&#varname#_capi'}, 'pyobjfrom': {isintent_inout: """\ \tf2py_success = try_pyarr_from_#ctype#(#varname#_capi,&#varname#); \tif (f2py_success) {"""}, 'closepyobjfrom': {isintent_inout: "\t} /*if (f2py_success) of #varname# pyobjfrom*/"}, 'need': {isintent_inout: 'try_pyarr_from_#ctype#'}, '_check': l_and(isscalar, l_not(iscomplex), isintent_nothide) }, { 'frompyobj': [ # hasinitvalue... # if pyobj is None: # varname = init # else # from_pyobj(varname) # # isoptional and noinitvalue... # if pyobj is not None: # from_pyobj(varname) # else: # varname is uninitialized # # ... # from_pyobj(varname) # {hasinitvalue: '\tif (#varname#_capi == Py_None) #varname# = #init#; else', '_depend': ''}, {l_and(isoptional, l_not(hasinitvalue)): '\tif (#varname#_capi != Py_None)', '_depend': ''}, {l_not(islogical): '''\ \t\tf2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#pyname#() #nth# (#varname#) can\'t be converted to #ctype#"); \tif (f2py_success) {'''}, {islogical: '''\ \t\t#varname# = (#ctype#)PyObject_IsTrue(#varname#_capi); \t\tf2py_success = 1; \tif (f2py_success) {'''}, ], 'cleanupfrompyobj': '\t} /*if (f2py_success) of #varname#*/', 'need': {l_not(islogical): '#ctype#_from_pyobj'}, '_check': l_and(isscalar, l_not(iscomplex), isintent_nothide), '_depend': '' }, { # Hidden 'frompyobj': {hasinitvalue: '\t#varname# = #init#;'}, 'need': typedef_need_dict, '_check': l_and(isscalar, l_not(iscomplex), isintent_hide), '_depend': '' }, { # Common 'frompyobj': {debugcapi: '\tfprintf(stderr,"#vardebugshowvalue#\\n",#varname#);'}, '_check': l_and(isscalar, l_not(iscomplex)), '_depend': '' }, # Complex scalars { # Common 'decl': '\t#ctype# #varname#;', 'callfortran': {isintent_c: '#varname#,', l_not(isintent_c): '&#varname#,'}, 'pyobjfrom': {debugcapi: '\tfprintf(stderr,"#vardebugshowvalue#\\n",#varname#.r,#varname#.i);'}, 'return': {isintent_out: ',#varname#_capi'}, '_check': iscomplex }, { # Not hidden 'decl': '\tPyObject *#varname#_capi = Py_None;', 'argformat': {isrequired: 'O'}, 'keyformat': {isoptional: 'O'}, 'args_capi': {isrequired: ',&#varname#_capi'}, 'keys_capi': {isoptional: ',&#varname#_capi'}, 'need': {isintent_inout: 'try_pyarr_from_#ctype#'}, 'pyobjfrom': {isintent_inout: """\ \t\tf2py_success = try_pyarr_from_#ctype#(#varname#_capi,&#varname#); \t\tif (f2py_success) {"""}, 'closepyobjfrom': {isintent_inout: "\t\t} /*if (f2py_success) of #varname# pyobjfrom*/"}, '_check': l_and(iscomplex, isintent_nothide) }, { 'frompyobj': [{hasinitvalue: '\tif (#varname#_capi==Py_None) {#varname#.r = #init.r#, #varname#.i = #init.i#;} else'}, {l_and(isoptional, l_not(hasinitvalue)) : '\tif (#varname#_capi != Py_None)'}, '\t\tf2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#pyname#() #nth# (#varname#) can\'t be converted to #ctype#");' '\n\tif (f2py_success) {'], 'cleanupfrompyobj': '\t} /*if (f2py_success) of #varname# frompyobj*/', 'need': ['#ctype#_from_pyobj'], '_check': l_and(iscomplex, isintent_nothide), '_depend': '' }, { # Hidden 'decl': {isintent_out: '\tPyObject *#varname#_capi = Py_None;'}, '_check': l_and(iscomplex, isintent_hide) }, { 'frompyobj': {hasinitvalue: '\t#varname#.r = #init.r#, #varname#.i = #init.i#;'}, '_check': l_and(iscomplex, isintent_hide), '_depend': '' }, { # Common 'pyobjfrom': {isintent_out: '\t#varname#_capi = pyobj_from_#ctype#1(#varname#);'}, 'need': ['pyobj_from_#ctype#1'], '_check': iscomplex }, { 'frompyobj': {debugcapi: '\tfprintf(stderr,"#vardebugshowvalue#\\n",#varname#.r,#varname#.i);'}, '_check': iscomplex, '_depend': '' }, # String { # Common 'decl': ['\t#ctype# #varname# = NULL;', '\tint slen(#varname#);', '\tPyObject *#varname#_capi = Py_None;'], 'callfortran':'#varname#,', 'callfortranappend':'slen(#varname#),', 'pyobjfrom':{debugcapi: '\tfprintf(stderr,"#vardebugshowvalue#\\n",slen(#varname#),#varname#);'}, 'return': {isintent_out: ',#varname#'}, 'need': ['len..'], # 'STRINGFREE'], '_check':isstring }, { # Common 'frompyobj': """\ \tslen(#varname#) = #length#; \tf2py_success = #ctype#_from_pyobj(&#varname#,&slen(#varname#),#init#,#varname#_capi,\"#ctype#_from_pyobj failed in converting #nth# `#varname#\' of #pyname# to C #ctype#\"); \tif (f2py_success) {""", 'cleanupfrompyobj': """\ \t\tSTRINGFREE(#varname#); \t} /*if (f2py_success) of #varname#*/""", 'need': ['#ctype#_from_pyobj', 'len..', 'STRINGFREE'], '_check':isstring, '_depend':'' }, { # Not hidden 'argformat': {isrequired: 'O'}, 'keyformat': {isoptional: 'O'}, 'args_capi': {isrequired: ',&#varname#_capi'}, 'keys_capi': {isoptional: ',&#varname#_capi'}, 'pyobjfrom': {isintent_inout: '''\ \tf2py_success = try_pyarr_from_#ctype#(#varname#_capi,#varname#); \tif (f2py_success) {'''}, 'closepyobjfrom': {isintent_inout: '\t} /*if (f2py_success) of #varname# pyobjfrom*/'}, 'need': {isintent_inout: 'try_pyarr_from_#ctype#'}, '_check': l_and(isstring, isintent_nothide) }, { # Hidden '_check': l_and(isstring, isintent_hide) }, { 'frompyobj': {debugcapi: '\tfprintf(stderr,"#vardebugshowvalue#\\n",slen(#varname#),#varname#);'}, '_check': isstring, '_depend': '' }, # Array { # Common 'decl': ['\t#ctype# *#varname# = NULL;', '\tnpy_intp #varname#_Dims[#rank#] = {#rank*[-1]#};', '\tconst int #varname#_Rank = #rank#;', '\tPyArrayObject *capi_#varname#_tmp = NULL;', '\tint capi_#varname#_intent = 0;', ], 'callfortran':'#varname#,', 'return':{isintent_out: ',capi_#varname#_tmp'}, 'need': 'len..', '_check': isarray }, { # intent(overwrite) array 'decl': '\tint capi_overwrite_#varname# = 1;', 'kwlistxa': '"overwrite_#varname#",', 'xaformat': 'i', 'keys_xa': ',&capi_overwrite_#varname#', 'docsignxa': 'overwrite_#varname#=1,', 'docsignxashort': 'overwrite_#varname#,', 'docstropt': 'overwrite_#varname# : input int, optional\\n Default: 1', '_check': l_and(isarray, isintent_overwrite), }, { 'frompyobj': '\tcapi_#varname#_intent |= (capi_overwrite_#varname#?0:F2PY_INTENT_COPY);', '_check': l_and(isarray, isintent_overwrite), '_depend': '', }, { # intent(copy) array 'decl': '\tint capi_overwrite_#varname# = 0;', 'kwlistxa': '"overwrite_#varname#",', 'xaformat': 'i', 'keys_xa': ',&capi_overwrite_#varname#', 'docsignxa': 'overwrite_#varname#=0,', 'docsignxashort': 'overwrite_#varname#,', 'docstropt': 'overwrite_#varname# : input int, optional\\n Default: 0', '_check': l_and(isarray, isintent_copy), }, { 'frompyobj': '\tcapi_#varname#_intent |= (capi_overwrite_#varname#?0:F2PY_INTENT_COPY);', '_check': l_and(isarray, isintent_copy), '_depend': '', }, { 'need': [{hasinitvalue: 'forcomb'}, {hasinitvalue: 'CFUNCSMESS'}], '_check': isarray, '_depend': '' }, { # Not hidden 'decl': '\tPyObject *#varname#_capi = Py_None;', 'argformat': {isrequired: 'O'}, 'keyformat': {isoptional: 'O'}, 'args_capi': {isrequired: ',&#varname#_capi'}, 'keys_capi': {isoptional: ',&#varname#_capi'}, '_check': l_and(isarray, isintent_nothide) }, { 'frompyobj': ['\t#setdims#;', '\tcapi_#varname#_intent |= #intent#;', {isintent_hide: '\tcapi_#varname#_tmp = array_from_pyobj(#atype#,#varname#_Dims,#varname#_Rank,capi_#varname#_intent,Py_None);'}, {isintent_nothide: '\tcapi_#varname#_tmp = array_from_pyobj(#atype#,#varname#_Dims,#varname#_Rank,capi_#varname#_intent,#varname#_capi);'}, """\ \tif (capi_#varname#_tmp == NULL) { \t\tPyObject *exc, *val, *tb; \t\tPyErr_Fetch(&exc, &val, &tb); \t\tPyErr_SetString(exc ? exc : #modulename#_error,\"failed in converting #nth# `#varname#\' of #pyname# to C/Fortran array\" ); \t\tnpy_PyErr_ChainExceptionsCause(exc, val, tb); \t} else { \t\t#varname# = (#ctype# *)(PyArray_DATA(capi_#varname#_tmp)); """, {hasinitvalue: [ {isintent_nothide: '\tif (#varname#_capi == Py_None) {'}, {isintent_hide: '\t{'}, {iscomplexarray: '\t\t#ctype# capi_c;'}, """\ \t\tint *_i,capi_i=0; \t\tCFUNCSMESS(\"#name#: Initializing #varname#=#init#\\n\"); \t\tif (initforcomb(PyArray_DIMS(capi_#varname#_tmp),PyArray_NDIM(capi_#varname#_tmp),1)) { \t\t\twhile ((_i = nextforcomb())) \t\t\t\t#varname#[capi_i++] = #init#; /* fortran way */ \t\t} else { \t\t\tPyObject *exc, *val, *tb; \t\t\tPyErr_Fetch(&exc, &val, &tb); \t\t\tPyErr_SetString(exc ? exc : #modulename#_error,\"Initialization of #nth# #varname# failed (initforcomb).\"); \t\t\tnpy_PyErr_ChainExceptionsCause(exc, val, tb); \t\t\tf2py_success = 0; \t\t} \t} \tif (f2py_success) {"""]}, ], 'cleanupfrompyobj': [ # note that this list will be reversed '\t} /*if (capi_#varname#_tmp == NULL) ... else of #varname#*/', {l_not(l_or(isintent_out, isintent_hide)): """\ \tif((PyObject *)capi_#varname#_tmp!=#varname#_capi) { \t\tPy_XDECREF(capi_#varname#_tmp); }"""}, {l_and(isintent_hide, l_not(isintent_out)) : """\t\tPy_XDECREF(capi_#varname#_tmp);"""}, {hasinitvalue: '\t} /*if (f2py_success) of #varname# init*/'}, ], '_check': isarray, '_depend': '' }, # Scalararray { # Common '_check': l_and(isarray, l_not(iscomplexarray)) }, { # Not hidden '_check': l_and(isarray, l_not(iscomplexarray), isintent_nothide) }, # Integer*1 array {'need': '#ctype#', '_check': isint1array, '_depend': '' }, # Integer*-1 array {'need': '#ctype#', '_check': isunsigned_chararray, '_depend': '' }, # Integer*-2 array {'need': '#ctype#', '_check': isunsigned_shortarray, '_depend': '' }, # Integer*-8 array {'need': '#ctype#', '_check': isunsigned_long_longarray, '_depend': '' }, # Complexarray {'need': '#ctype#', '_check': iscomplexarray, '_depend': '' }, # Stringarray { 'callfortranappend': {isarrayofstrings: 'flen(#varname#),'}, 'need': 'string', '_check': isstringarray } ] ################# Rules for checking ############### check_rules = [ { 'frompyobj': {debugcapi: '\tfprintf(stderr,\"debug-capi:Checking `#check#\'\\n\");'}, 'need': 'len..' }, { 'frompyobj': '\tCHECKSCALAR(#check#,\"#check#\",\"#nth# #varname#\",\"#varshowvalue#\",#varname#) {', 'cleanupfrompyobj': '\t} /*CHECKSCALAR(#check#)*/', 'need': 'CHECKSCALAR', '_check': l_and(isscalar, l_not(iscomplex)), '_break': '' }, { 'frompyobj': '\tCHECKSTRING(#check#,\"#check#\",\"#nth# #varname#\",\"#varshowvalue#\",#varname#) {', 'cleanupfrompyobj': '\t} /*CHECKSTRING(#check#)*/', 'need': 'CHECKSTRING', '_check': isstring, '_break': '' }, { 'need': 'CHECKARRAY', 'frompyobj': '\tCHECKARRAY(#check#,\"#check#\",\"#nth# #varname#\") {', 'cleanupfrompyobj': '\t} /*CHECKARRAY(#check#)*/', '_check': isarray, '_break': '' }, { 'need': 'CHECKGENERIC', 'frompyobj': '\tCHECKGENERIC(#check#,\"#check#\",\"#nth# #varname#\") {', 'cleanupfrompyobj': '\t} /*CHECKGENERIC(#check#)*/', } ] ########## Applying the rules. No need to modify what follows ############# #################### Build C/API module ####################### def buildmodule(m, um): """ Return """ outmess('\tBuilding module "%s"...\n' % (m['name'])) ret = {} mod_rules = defmod_rules[:] vrd = capi_maps.modsign2map(m) rd = dictappend({'f2py_version': f2py_version}, vrd) funcwrappers = [] funcwrappers2 = [] # F90 codes for n in m['interfaced']: nb = None for bi in m['body']: if not bi['block'] == 'interface': errmess('buildmodule: Expected interface block. Skipping.\n') continue for b in bi['body']: if b['name'] == n: nb = b break if not nb: errmess( 'buildmodule: Could not found the body of interfaced routine "%s". Skipping.\n' % (n)) continue nb_list = [nb] if 'entry' in nb: for k, a in nb['entry'].items(): nb1 = copy.deepcopy(nb) del nb1['entry'] nb1['name'] = k nb1['args'] = a nb_list.append(nb1) for nb in nb_list: # requiresf90wrapper must be called before buildapi as it # rewrites assumed shape arrays as automatic arrays. isf90 = requiresf90wrapper(nb) api, wrap = buildapi(nb) if wrap: if isf90: funcwrappers2.append(wrap) else: funcwrappers.append(wrap) ar = applyrules(api, vrd) rd = dictappend(rd, ar) # Construct COMMON block support cr, wrap = common_rules.buildhooks(m) if wrap: funcwrappers.append(wrap) ar = applyrules(cr, vrd) rd = dictappend(rd, ar) # Construct F90 module support mr, wrap = f90mod_rules.buildhooks(m) if wrap: funcwrappers2.append(wrap) ar = applyrules(mr, vrd) rd = dictappend(rd, ar) for u in um: ar = use_rules.buildusevars(u, m['use'][u['name']]) rd = dictappend(rd, ar) needs = cfuncs.get_needs() code = {} for n in needs.keys(): code[n] = [] for k in needs[n]: c = '' if k in cfuncs.includes0: c = cfuncs.includes0[k] elif k in cfuncs.includes: c = cfuncs.includes[k] elif k in cfuncs.userincludes: c = cfuncs.userincludes[k] elif k in cfuncs.typedefs: c = cfuncs.typedefs[k] elif k in cfuncs.typedefs_generated: c = cfuncs.typedefs_generated[k] elif k in cfuncs.cppmacros: c = cfuncs.cppmacros[k] elif k in cfuncs.cfuncs: c = cfuncs.cfuncs[k] elif k in cfuncs.callbacks: c = cfuncs.callbacks[k] elif k in cfuncs.f90modhooks: c = cfuncs.f90modhooks[k] elif k in cfuncs.commonhooks: c = cfuncs.commonhooks[k] else: errmess('buildmodule: unknown need %s.\n' % (repr(k))) continue code[n].append(c) mod_rules.append(code) for r in mod_rules: if ('_check' in r and r['_check'](m)) or ('_check' not in r): ar = applyrules(r, vrd, m) rd = dictappend(rd, ar) ar = applyrules(module_rules, rd) fn = os.path.join(options['buildpath'], vrd['coutput']) ret['csrc'] = fn with open(fn, 'w') as f: f.write(ar['modulebody'].replace('\t', 2 * ' ')) outmess('\tWrote C/API module "%s" to file "%s"\n' % (m['name'], fn)) if options['dorestdoc']: fn = os.path.join( options['buildpath'], vrd['modulename'] + 'module.rest') with open(fn, 'w') as f: f.write('.. -*- rest -*-\n') f.write('\n'.join(ar['restdoc'])) outmess('\tReST Documentation is saved to file "%s/%smodule.rest"\n' % (options['buildpath'], vrd['modulename'])) if options['dolatexdoc']: fn = os.path.join( options['buildpath'], vrd['modulename'] + 'module.tex') ret['ltx'] = fn with open(fn, 'w') as f: f.write( '%% This file is auto-generated with f2py (version:%s)\n' % (f2py_version)) if 'shortlatex' not in options: f.write( '\\documentclass{article}\n\\usepackage{a4wide}\n\\begin{document}\n\\tableofcontents\n\n') f.write('\n'.join(ar['latexdoc'])) if 'shortlatex' not in options: f.write('\\end{document}') outmess('\tDocumentation is saved to file "%s/%smodule.tex"\n' % (options['buildpath'], vrd['modulename'])) if funcwrappers: wn = os.path.join(options['buildpath'], vrd['f2py_wrapper_output']) ret['fsrc'] = wn with open(wn, 'w') as f: f.write('C -*- fortran -*-\n') f.write( 'C This file is autogenerated with f2py (version:%s)\n' % (f2py_version)) f.write( 'C It contains Fortran 77 wrappers to fortran functions.\n') lines = [] for l in ('\n\n'.join(funcwrappers) + '\n').split('\n'): if 0 <= l.find('!') < 66: # don't split comment lines lines.append(l + '\n') elif l and l[0] == ' ': while len(l) >= 66: lines.append(l[:66] + '\n &') l = l[66:] lines.append(l + '\n') else: lines.append(l + '\n') lines = ''.join(lines).replace('\n &\n', '\n') f.write(lines) outmess('\tFortran 77 wrappers are saved to "%s"\n' % (wn)) if funcwrappers2: wn = os.path.join( options['buildpath'], '%s-f2pywrappers2.f90' % (vrd['modulename'])) ret['fsrc'] = wn with open(wn, 'w') as f: f.write('! -*- f90 -*-\n') f.write( '! This file is autogenerated with f2py (version:%s)\n' % (f2py_version)) f.write( '! It contains Fortran 90 wrappers to fortran functions.\n') lines = [] for l in ('\n\n'.join(funcwrappers2) + '\n').split('\n'): if 0 <= l.find('!') < 72: # don't split comment lines lines.append(l + '\n') elif len(l) > 72 and l[0] == ' ': lines.append(l[:72] + '&\n &') l = l[72:] while len(l) > 66: lines.append(l[:66] + '&\n &') l = l[66:] lines.append(l + '\n') else: lines.append(l + '\n') lines = ''.join(lines).replace('\n &\n', '\n') f.write(lines) outmess('\tFortran 90 wrappers are saved to "%s"\n' % (wn)) return ret ################## Build C/API function ############# stnd = {1: 'st', 2: 'nd', 3: 'rd', 4: 'th', 5: 'th', 6: 'th', 7: 'th', 8: 'th', 9: 'th', 0: 'th'} def buildapi(rout): rout, wrap = func2subr.assubr(rout) args, depargs = getargs2(rout) capi_maps.depargs = depargs var = rout['vars'] if ismoduleroutine(rout): outmess('\t\t\tConstructing wrapper function "%s.%s"...\n' % (rout['modulename'], rout['name'])) else: outmess('\t\tConstructing wrapper function "%s"...\n' % (rout['name'])) # Routine vrd = capi_maps.routsign2map(rout) rd = dictappend({}, vrd) for r in rout_rules: if ('_check' in r and r['_check'](rout)) or ('_check' not in r): ar = applyrules(r, vrd, rout) rd = dictappend(rd, ar) # Args nth, nthk = 0, 0 savevrd = {} for a in args: vrd = capi_maps.sign2map(a, var[a]) if isintent_aux(var[a]): _rules = aux_rules else: _rules = arg_rules if not isintent_hide(var[a]): if not isoptional(var[a]): nth = nth + 1 vrd['nth'] = repr(nth) + stnd[nth % 10] + ' argument' else: nthk = nthk + 1 vrd['nth'] = repr(nthk) + stnd[nthk % 10] + ' keyword' else: vrd['nth'] = 'hidden' savevrd[a] = vrd for r in _rules: if '_depend' in r: continue if ('_check' in r and r['_check'](var[a])) or ('_check' not in r): ar = applyrules(r, vrd, var[a]) rd = dictappend(rd, ar) if '_break' in r: break for a in depargs: if isintent_aux(var[a]): _rules = aux_rules else: _rules = arg_rules vrd = savevrd[a] for r in _rules: if '_depend' not in r: continue if ('_check' in r and r['_check'](var[a])) or ('_check' not in r): ar = applyrules(r, vrd, var[a]) rd = dictappend(rd, ar) if '_break' in r: break if 'check' in var[a]: for c in var[a]['check']: vrd['check'] = c ar = applyrules(check_rules, vrd, var[a]) rd = dictappend(rd, ar) if isinstance(rd['cleanupfrompyobj'], list): rd['cleanupfrompyobj'].reverse() if isinstance(rd['closepyobjfrom'], list): rd['closepyobjfrom'].reverse() rd['docsignature'] = stripcomma(replace('#docsign##docsignopt##docsignxa#', {'docsign': rd['docsign'], 'docsignopt': rd['docsignopt'], 'docsignxa': rd['docsignxa']})) optargs = stripcomma(replace('#docsignopt##docsignxa#', {'docsignxa': rd['docsignxashort'], 'docsignopt': rd['docsignoptshort']} )) if optargs == '': rd['docsignatureshort'] = stripcomma( replace('#docsign#', {'docsign': rd['docsign']})) else: rd['docsignatureshort'] = replace('#docsign#[#docsignopt#]', {'docsign': rd['docsign'], 'docsignopt': optargs, }) rd['latexdocsignatureshort'] = rd['docsignatureshort'].replace('_', '\\_') rd['latexdocsignatureshort'] = rd[ 'latexdocsignatureshort'].replace(',', ', ') cfs = stripcomma(replace('#callfortran##callfortranappend#', { 'callfortran': rd['callfortran'], 'callfortranappend': rd['callfortranappend']})) if len(rd['callfortranappend']) > 1: rd['callcompaqfortran'] = stripcomma(replace('#callfortran# 0,#callfortranappend#', { 'callfortran': rd['callfortran'], 'callfortranappend': rd['callfortranappend']})) else: rd['callcompaqfortran'] = cfs rd['callfortran'] = cfs if isinstance(rd['docreturn'], list): rd['docreturn'] = stripcomma( replace('#docreturn#', {'docreturn': rd['docreturn']})) + ' = ' rd['docstrsigns'] = [] rd['latexdocstrsigns'] = [] for k in ['docstrreq', 'docstropt', 'docstrout', 'docstrcbs']: if k in rd and isinstance(rd[k], list): rd['docstrsigns'] = rd['docstrsigns'] + rd[k] k = 'latex' + k if k in rd and isinstance(rd[k], list): rd['latexdocstrsigns'] = rd['latexdocstrsigns'] + rd[k][0:1] +\ ['\\begin{description}'] + rd[k][1:] +\ ['\\end{description}'] ar = applyrules(routine_rules, rd) if ismoduleroutine(rout): outmess('\t\t\t %s\n' % (ar['docshort'])) else: outmess('\t\t %s\n' % (ar['docshort'])) return ar, wrap #################### EOF rules.py #######################
#!/usr/bin/env python3 """ Rules for building C/API module with f2py2e. Here is a skeleton of a new wrapper function (13Dec2001): wrapper_function(args) declarations get_python_arguments, say, `a' and `b' get_a_from_python if (successful) { get_b_from_python if (successful) { callfortran if (successful) { put_a_to_python if (successful) { put_b_to_python if (successful) { buildvalue = ... } } } } cleanup_b } cleanup_a return buildvalue Copyright 1999,2000 Pearu Peterson all rights reserved, Pearu Peterson <pearu@ioc.ee> Permission to use, modify, and distribute this software is given under the terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/08/30 08:58:42 $ Pearu Peterson """ __version__ = "$Revision: 1.129 $"[10:-1] from . import __version__ f2py_version = __version__.version from .. import version as _numpy_version numpy_version = _numpy_version.version import os import time import copy from .auxfuncs import ( applyrules, debugcapi, dictappend, errmess, gentitle, getargs2, hascallstatement, hasexternals, hasinitvalue, hasnote, hasresultnote, isarray, isarrayofstrings, iscomplex, iscomplexarray, iscomplexfunction, iscomplexfunction_warn, isdummyroutine, isexternal, isfunction, isfunction_wrap, isint1array, isintent_aux, isintent_c, isintent_callback, isintent_copy, isintent_hide, isintent_inout, isintent_nothide, isintent_out, isintent_overwrite, islogical, islong_complex, islong_double, islong_doublefunction, islong_long, islong_longfunction, ismoduleroutine, isoptional, isrequired, isscalar, issigned_long_longarray, isstring, isstringarray, isstringfunction, issubroutine, issubroutine_wrap, isthreadsafe, isunsigned, isunsigned_char, isunsigned_chararray, isunsigned_long_long, isunsigned_long_longarray, isunsigned_short, isunsigned_shortarray, l_and, l_not, l_or, outmess, replace, stripcomma, requiresf90wrapper ) from . import capi_maps from . import cfuncs from . import common_rules from . import use_rules from . import f90mod_rules from . import func2subr options = {} sepdict = {} #for k in ['need_cfuncs']: sepdict[k]=',' for k in ['decl', 'frompyobj', 'cleanupfrompyobj', 'topyarr', 'method', 'pyobjfrom', 'closepyobjfrom', 'freemem', 'userincludes', 'includes0', 'includes', 'typedefs', 'typedefs_generated', 'cppmacros', 'cfuncs', 'callbacks', 'latexdoc', 'restdoc', 'routine_defs', 'externroutines', 'initf2pywraphooks', 'commonhooks', 'initcommonhooks', 'f90modhooks', 'initf90modhooks']: sepdict[k] = '\n' #################### Rules for C/API module ################# generationtime = int(os.environ.get('SOURCE_DATE_EPOCH', time.time())) module_rules = { 'modulebody': """\ /* File: #modulename#module.c * This file is auto-generated with f2py (version:#f2py_version#). * f2py is a Fortran to Python Interface Generator (FPIG), Second Edition, * written by Pearu Peterson <pearu@cens.ioc.ee>. * Generation date: """ + time.asctime(time.gmtime(generationtime)) + """ * Do not edit this file directly unless you know what you are doing!!! */ #ifdef __cplusplus extern \"C\" { #endif """ + gentitle("See f2py2e/cfuncs.py: includes") + """ #includes# #includes0# """ + gentitle("See f2py2e/rules.py: mod_rules['modulebody']") + """ static PyObject *#modulename#_error; static PyObject *#modulename#_module; """ + gentitle("See f2py2e/cfuncs.py: typedefs") + """ #typedefs# """ + gentitle("See f2py2e/cfuncs.py: typedefs_generated") + """ #typedefs_generated# """ + gentitle("See f2py2e/cfuncs.py: cppmacros") + """ #cppmacros# """ + gentitle("See f2py2e/cfuncs.py: cfuncs") + """ #cfuncs# """ + gentitle("See f2py2e/cfuncs.py: userincludes") + """ #userincludes# """ + gentitle("See f2py2e/capi_rules.py: usercode") + """ #usercode# /* See f2py2e/rules.py */ #externroutines# """ + gentitle("See f2py2e/capi_rules.py: usercode1") + """ #usercode1# """ + gentitle("See f2py2e/cb_rules.py: buildcallback") + """ #callbacks# """ + gentitle("See f2py2e/rules.py: buildapi") + """ #body# """ + gentitle("See f2py2e/f90mod_rules.py: buildhooks") + """ #f90modhooks# """ + gentitle("See f2py2e/rules.py: module_rules['modulebody']") + """ """ + gentitle("See f2py2e/common_rules.py: buildhooks") + """ #commonhooks# """ + gentitle("See f2py2e/rules.py") + """ static FortranDataDef f2py_routine_defs[] = { #routine_defs# \t{NULL} }; static PyMethodDef f2py_module_methods[] = { #pymethoddef# \t{NULL,NULL} }; static struct PyModuleDef moduledef = { \tPyModuleDef_HEAD_INIT, \t"#modulename#", \tNULL, \t-1, \tf2py_module_methods, \tNULL, \tNULL, \tNULL, \tNULL }; PyMODINIT_FUNC PyInit_#modulename#(void) { \tint i; \tPyObject *m,*d, *s, *tmp; \tm = #modulename#_module = PyModule_Create(&moduledef); \tPy_SET_TYPE(&PyFortran_Type, &PyType_Type); \timport_array(); \tif (PyErr_Occurred()) \t\t{PyErr_SetString(PyExc_ImportError, \"can't initialize module #modulename# (failed to import numpy)\"); return m;} \td = PyModule_GetDict(m); \ts = PyUnicode_FromString(\"$R""" + """evision: $\"); \tPyDict_SetItemString(d, \"__version__\", s); \tPy_DECREF(s); \ts = PyUnicode_FromString( \t\t\"This module '#modulename#' is auto-generated with f2py (version:#f2py_version#).\\nFunctions:\\n\"\n#docs#\".\"); \tPyDict_SetItemString(d, \"__doc__\", s); \tPy_DECREF(s); \ts = PyUnicode_FromString(\"""" + numpy_version + """\"); \tPyDict_SetItemString(d, \"__f2py_numpy_version__\", s); \tPy_DECREF(s); \t#modulename#_error = PyErr_NewException (\"#modulename#.error\", NULL, NULL); \t/* \t * Store the error object inside the dict, so that it could get deallocated. \t * (in practice, this is a module, so it likely will not and cannot.) \t */ \tPyDict_SetItemString(d, \"_#modulename#_error\", #modulename#_error); \tPy_DECREF(#modulename#_error); \tfor(i=0;f2py_routine_defs[i].name!=NULL;i++) { \t\ttmp = PyFortranObject_NewAsAttr(&f2py_routine_defs[i]); \t\tPyDict_SetItemString(d, f2py_routine_defs[i].name, tmp); \t\tPy_DECREF(tmp); \t} #initf2pywraphooks# #initf90modhooks# #initcommonhooks# #interface_usercode# #ifdef F2PY_REPORT_ATEXIT \tif (! PyErr_Occurred()) \t\ton_exit(f2py_report_on_exit,(void*)\"#modulename#\"); #endif \treturn m; } #ifdef __cplusplus } #endif """, 'separatorsfor': {'latexdoc': '\n\n', 'restdoc': '\n\n'}, 'latexdoc': ['\\section{Module \\texttt{#texmodulename#}}\n', '#modnote#\n', '#latexdoc#'], 'restdoc': ['Module #modulename#\n' + '=' * 80, '\n#restdoc#'] } defmod_rules = [ {'body': '/*eof body*/', 'method': '/*eof method*/', 'externroutines': '/*eof externroutines*/', 'routine_defs': '/*eof routine_defs*/', 'initf90modhooks': '/*eof initf90modhooks*/', 'initf2pywraphooks': '/*eof initf2pywraphooks*/', 'initcommonhooks': '/*eof initcommonhooks*/', 'latexdoc': '', 'restdoc': '', 'modnote': {hasnote: '#note#', l_not(hasnote): ''}, } ] routine_rules = { 'separatorsfor': sepdict, 'body': """ #begintitle# static char doc_#apiname#[] = \"\\\n#docreturn##name#(#docsignatureshort#)\\n\\nWrapper for ``#name#``.\\\n\\n#docstrsigns#\"; /* #declfortranroutine# */ static PyObject *#apiname#(const PyObject *capi_self, PyObject *capi_args, PyObject *capi_keywds, #functype# (*f2py_func)(#callprotoargument#)) { PyObject * volatile capi_buildvalue = NULL; volatile int f2py_success = 1; #decl# static char *capi_kwlist[] = {#kwlist##kwlistopt##kwlistxa#NULL}; #usercode# #routdebugenter# #ifdef F2PY_REPORT_ATEXIT f2py_start_clock(); #endif if (!PyArg_ParseTupleAndKeywords(capi_args,capi_keywds,\\ \"#argformat#|#keyformat##xaformat#:#pyname#\",\\ capi_kwlist#args_capi##keys_capi##keys_xa#))\n return NULL; #frompyobj# /*end of frompyobj*/ #ifdef F2PY_REPORT_ATEXIT f2py_start_call_clock(); #endif #callfortranroutine# if (PyErr_Occurred()) f2py_success = 0; #ifdef F2PY_REPORT_ATEXIT f2py_stop_call_clock(); #endif /*end of callfortranroutine*/ if (f2py_success) { #pyobjfrom# /*end of pyobjfrom*/ CFUNCSMESS(\"Building return value.\\n\"); capi_buildvalue = Py_BuildValue(\"#returnformat#\"#return#); /*closepyobjfrom*/ #closepyobjfrom# } /*if (f2py_success) after callfortranroutine*/ /*cleanupfrompyobj*/ #cleanupfrompyobj# if (capi_buildvalue == NULL) { #routdebugfailure# } else { #routdebugleave# } CFUNCSMESS(\"Freeing memory.\\n\"); #freemem# #ifdef F2PY_REPORT_ATEXIT f2py_stop_clock(); #endif return capi_buildvalue; } #endtitle# """, 'routine_defs': '#routine_def#', 'initf2pywraphooks': '#initf2pywraphook#', 'externroutines': '#declfortranroutine#', 'doc': '#docreturn##name#(#docsignature#)', 'docshort': '#docreturn##name#(#docsignatureshort#)', 'docs': '"\t#docreturn##name#(#docsignature#)\\n"\n', 'need': ['arrayobject.h', 'CFUNCSMESS', 'MINMAX'], 'cppmacros': {debugcapi: '#define DEBUGCFUNCS'}, 'latexdoc': ['\\subsection{Wrapper function \\texttt{#texname#}}\n', """ \\noindent{{}\\verb@#docreturn##name#@{}}\\texttt{(#latexdocsignatureshort#)} #routnote# #latexdocstrsigns# """], 'restdoc': ['Wrapped function ``#name#``\n' + '-' * 80, ] } ################## Rules for C/API function ############## rout_rules = [ { # Init 'separatorsfor': {'callfortranroutine': '\n', 'routdebugenter': '\n', 'decl': '\n', 'routdebugleave': '\n', 'routdebugfailure': '\n', 'setjmpbuf': ' || ', 'docstrreq': '\n', 'docstropt': '\n', 'docstrout': '\n', 'docstrcbs': '\n', 'docstrsigns': '\\n"\n"', 'latexdocstrsigns': '\n', 'latexdocstrreq': '\n', 'latexdocstropt': '\n', 'latexdocstrout': '\n', 'latexdocstrcbs': '\n', }, 'kwlist': '', 'kwlistopt': '', 'callfortran': '', 'callfortranappend': '', 'docsign': '', 'docsignopt': '', 'decl': '/*decl*/', 'freemem': '/*freemem*/', 'docsignshort': '', 'docsignoptshort': '', 'docstrsigns': '', 'latexdocstrsigns': '', 'docstrreq': '\\nParameters\\n----------', 'docstropt': '\\nOther Parameters\\n----------------', 'docstrout': '\\nReturns\\n-------', 'docstrcbs': '\\nNotes\\n-----\\nCall-back functions::\\n', 'latexdocstrreq': '\\noindent Required arguments:', 'latexdocstropt': '\\noindent Optional arguments:', 'latexdocstrout': '\\noindent Return objects:', 'latexdocstrcbs': '\\noindent Call-back functions:', 'args_capi': '', 'keys_capi': '', 'functype': '', 'frompyobj': '/*frompyobj*/', # this list will be reversed 'cleanupfrompyobj': ['/*end of cleanupfrompyobj*/'], 'pyobjfrom': '/*pyobjfrom*/', # this list will be reversed 'closepyobjfrom': ['/*end of closepyobjfrom*/'], 'topyarr': '/*topyarr*/', 'routdebugleave': '/*routdebugleave*/', 'routdebugenter': '/*routdebugenter*/', 'routdebugfailure': '/*routdebugfailure*/', 'callfortranroutine': '/*callfortranroutine*/', 'argformat': '', 'keyformat': '', 'need_cfuncs': '', 'docreturn': '', 'return': '', 'returnformat': '', 'rformat': '', 'kwlistxa': '', 'keys_xa': '', 'xaformat': '', 'docsignxa': '', 'docsignxashort': '', 'initf2pywraphook': '', 'routnote': {hasnote: '--- #note#', l_not(hasnote): ''}, }, { 'apiname': 'f2py_rout_#modulename#_#name#', 'pyname': '#modulename#.#name#', 'decl': '', '_check': l_not(ismoduleroutine) }, { 'apiname': 'f2py_rout_#modulename#_#f90modulename#_#name#', 'pyname': '#modulename#.#f90modulename#.#name#', 'decl': '', '_check': ismoduleroutine }, { # Subroutine 'functype': 'void', 'declfortranroutine': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'extern void #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);', l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): 'extern void #fortranname#(#callprotoargument#);', ismoduleroutine: '', isdummyroutine: '' }, 'routine_def': {l_not(l_or(ismoduleroutine, isintent_c, isdummyroutine)): '\t{\"#name#\",-1,{{-1}},0,(char *)#F_FUNC#(#fortranname#,#FORTRANNAME#),(f2py_init_func)#apiname#,doc_#apiname#},', l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): '\t{\"#name#\",-1,{{-1}},0,(char *)#fortranname#,(f2py_init_func)#apiname#,doc_#apiname#},', l_and(l_not(ismoduleroutine), isdummyroutine): '\t{\"#name#\",-1,{{-1}},0,NULL,(f2py_init_func)#apiname#,doc_#apiname#},', }, 'need': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'F_FUNC'}, 'callfortranroutine': [ {debugcapi: [ """\tfprintf(stderr,\"debug-capi:Fortran subroutine `#fortranname#(#callfortran#)\'\\n\");"""]}, {hasexternals: """\ \t\tif (#setjmpbuf#) { \t\t\tf2py_success = 0; \t\t} else {"""}, {isthreadsafe: '\t\t\tPy_BEGIN_ALLOW_THREADS'}, {hascallstatement: '''\t\t\t\t#callstatement#; \t\t\t\t/*(*f2py_func)(#callfortran#);*/'''}, {l_not(l_or(hascallstatement, isdummyroutine)) : '\t\t\t\t(*f2py_func)(#callfortran#);'}, {isthreadsafe: '\t\t\tPy_END_ALLOW_THREADS'}, {hasexternals: """\t\t}"""} ], '_check': l_and(issubroutine, l_not(issubroutine_wrap)), }, { # Wrapped function 'functype': 'void', 'declfortranroutine': {l_not(l_or(ismoduleroutine, isdummyroutine)): 'extern void #F_WRAPPEDFUNC#(#name_lower#,#NAME#)(#callprotoargument#);', isdummyroutine: '', }, 'routine_def': {l_not(l_or(ismoduleroutine, isdummyroutine)): '\t{\"#name#\",-1,{{-1}},0,(char *)#F_WRAPPEDFUNC#(#name_lower#,#NAME#),(f2py_init_func)#apiname#,doc_#apiname#},', isdummyroutine: '\t{\"#name#\",-1,{{-1}},0,NULL,(f2py_init_func)#apiname#,doc_#apiname#},', }, 'initf2pywraphook': {l_not(l_or(ismoduleroutine, isdummyroutine)): ''' { extern #ctype# #F_FUNC#(#name_lower#,#NAME#)(void); PyObject* o = PyDict_GetItemString(d,"#name#"); tmp = F2PyCapsule_FromVoidPtr((void*)#F_FUNC#(#name_lower#,#NAME#),NULL); PyObject_SetAttrString(o,"_cpointer", tmp); Py_DECREF(tmp); s = PyUnicode_FromString("#name#"); PyObject_SetAttrString(o,"__name__", s); Py_DECREF(s); } '''}, 'need': {l_not(l_or(ismoduleroutine, isdummyroutine)): ['F_WRAPPEDFUNC', 'F_FUNC']}, 'callfortranroutine': [ {debugcapi: [ """\tfprintf(stderr,\"debug-capi:Fortran subroutine `f2pywrap#name_lower#(#callfortran#)\'\\n\");"""]}, {hasexternals: """\ \tif (#setjmpbuf#) { \t\tf2py_success = 0; \t} else {"""}, {isthreadsafe: '\tPy_BEGIN_ALLOW_THREADS'}, {l_not(l_or(hascallstatement, isdummyroutine)) : '\t(*f2py_func)(#callfortran#);'}, {hascallstatement: '\t#callstatement#;\n\t/*(*f2py_func)(#callfortran#);*/'}, {isthreadsafe: '\tPy_END_ALLOW_THREADS'}, {hasexternals: '\t}'} ], '_check': isfunction_wrap, }, { # Wrapped subroutine 'functype': 'void', 'declfortranroutine': {l_not(l_or(ismoduleroutine, isdummyroutine)): 'extern void #F_WRAPPEDFUNC#(#name_lower#,#NAME#)(#callprotoargument#);', isdummyroutine: '', }, 'routine_def': {l_not(l_or(ismoduleroutine, isdummyroutine)): '\t{\"#name#\",-1,{{-1}},0,(char *)#F_WRAPPEDFUNC#(#name_lower#,#NAME#),(f2py_init_func)#apiname#,doc_#apiname#},', isdummyroutine: '\t{\"#name#\",-1,{{-1}},0,NULL,(f2py_init_func)#apiname#,doc_#apiname#},', }, 'initf2pywraphook': {l_not(l_or(ismoduleroutine, isdummyroutine)): ''' { extern void #F_FUNC#(#name_lower#,#NAME#)(void); PyObject* o = PyDict_GetItemString(d,"#name#"); tmp = F2PyCapsule_FromVoidPtr((void*)#F_FUNC#(#name_lower#,#NAME#),NULL); PyObject_SetAttrString(o,"_cpointer", tmp); Py_DECREF(tmp); s = PyUnicode_FromString("#name#"); PyObject_SetAttrString(o,"__name__", s); Py_DECREF(s); } '''}, 'need': {l_not(l_or(ismoduleroutine, isdummyroutine)): ['F_WRAPPEDFUNC', 'F_FUNC']}, 'callfortranroutine': [ {debugcapi: [ """\tfprintf(stderr,\"debug-capi:Fortran subroutine `f2pywrap#name_lower#(#callfortran#)\'\\n\");"""]}, {hasexternals: """\ \tif (#setjmpbuf#) { \t\tf2py_success = 0; \t} else {"""}, {isthreadsafe: '\tPy_BEGIN_ALLOW_THREADS'}, {l_not(l_or(hascallstatement, isdummyroutine)) : '\t(*f2py_func)(#callfortran#);'}, {hascallstatement: '\t#callstatement#;\n\t/*(*f2py_func)(#callfortran#);*/'}, {isthreadsafe: '\tPy_END_ALLOW_THREADS'}, {hasexternals: '\t}'} ], '_check': issubroutine_wrap, }, { # Function 'functype': '#ctype#', 'docreturn': {l_not(isintent_hide): '#rname#,'}, 'docstrout': '#pydocsignout#', 'latexdocstrout': ['\\item[]{{}\\verb@#pydocsignout#@{}}', {hasresultnote: '--- #resultnote#'}], 'callfortranroutine': [{l_and(debugcapi, isstringfunction): """\ #ifdef USESCOMPAQFORTRAN \tfprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callcompaqfortran#)\\n\"); #else \tfprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callfortran#)\\n\"); #endif """}, {l_and(debugcapi, l_not(isstringfunction)): """\ \tfprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callfortran#)\\n\"); """} ], '_check': l_and(isfunction, l_not(isfunction_wrap)) }, { # Scalar function 'declfortranroutine': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'extern #ctype# #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);', l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): 'extern #ctype# #fortranname#(#callprotoargument#);', isdummyroutine: '' }, 'routine_def': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): '\t{\"#name#\",-1,{{-1}},0,(char *)#F_FUNC#(#fortranname#,#FORTRANNAME#),(f2py_init_func)#apiname#,doc_#apiname#},', l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): '\t{\"#name#\",-1,{{-1}},0,(char *)#fortranname#,(f2py_init_func)#apiname#,doc_#apiname#},', isdummyroutine: '\t{\"#name#\",-1,{{-1}},0,NULL,(f2py_init_func)#apiname#,doc_#apiname#},', }, 'decl': [{iscomplexfunction_warn: '\t#ctype# #name#_return_value={0,0};', l_not(iscomplexfunction): '\t#ctype# #name#_return_value=0;'}, {iscomplexfunction: '\tPyObject *#name#_return_value_capi = Py_None;'} ], 'callfortranroutine': [ {hasexternals: """\ \tif (#setjmpbuf#) { \t\tf2py_success = 0; \t} else {"""}, {isthreadsafe: '\tPy_BEGIN_ALLOW_THREADS'}, {hascallstatement: '''\t#callstatement#; /*\t#name#_return_value = (*f2py_func)(#callfortran#);*/ '''}, {l_not(l_or(hascallstatement, isdummyroutine)) : '\t#name#_return_value = (*f2py_func)(#callfortran#);'}, {isthreadsafe: '\tPy_END_ALLOW_THREADS'}, {hasexternals: '\t}'}, {l_and(debugcapi, iscomplexfunction) : '\tfprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value.r,#name#_return_value.i);'}, {l_and(debugcapi, l_not(iscomplexfunction)): '\tfprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value);'}], 'pyobjfrom': {iscomplexfunction: '\t#name#_return_value_capi = pyobj_from_#ctype#1(#name#_return_value);'}, 'need': [{l_not(isdummyroutine): 'F_FUNC'}, {iscomplexfunction: 'pyobj_from_#ctype#1'}, {islong_longfunction: 'long_long'}, {islong_doublefunction: 'long_double'}], 'returnformat': {l_not(isintent_hide): '#rformat#'}, 'return': {iscomplexfunction: ',#name#_return_value_capi', l_not(l_or(iscomplexfunction, isintent_hide)): ',#name#_return_value'}, '_check': l_and(isfunction, l_not(isstringfunction), l_not(isfunction_wrap)) }, { # String function # in use for --no-wrap 'declfortranroutine': 'extern void #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);', 'routine_def': {l_not(l_or(ismoduleroutine, isintent_c)): '\t{\"#name#\",-1,{{-1}},0,(char *)#F_FUNC#(#fortranname#,#FORTRANNAME#),(f2py_init_func)#apiname#,doc_#apiname#},', l_and(l_not(ismoduleroutine), isintent_c): '\t{\"#name#\",-1,{{-1}},0,(char *)#fortranname#,(f2py_init_func)#apiname#,doc_#apiname#},' }, 'decl': ['\t#ctype# #name#_return_value = NULL;', '\tint #name#_return_value_len = 0;'], 'callfortran':'#name#_return_value,#name#_return_value_len,', 'callfortranroutine':['\t#name#_return_value_len = #rlength#;', '\tif ((#name#_return_value = (string)malloc(sizeof(char)*(#name#_return_value_len+1))) == NULL) {', '\t\tPyErr_SetString(PyExc_MemoryError, \"out of memory\");', '\t\tf2py_success = 0;', '\t} else {', "\t\t(#name#_return_value)[#name#_return_value_len] = '\\0';", '\t}', '\tif (f2py_success) {', {hasexternals: """\ \t\tif (#setjmpbuf#) { \t\t\tf2py_success = 0; \t\t} else {"""}, {isthreadsafe: '\t\tPy_BEGIN_ALLOW_THREADS'}, """\ #ifdef USESCOMPAQFORTRAN \t\t(*f2py_func)(#callcompaqfortran#); #else \t\t(*f2py_func)(#callfortran#); #endif """, {isthreadsafe: '\t\tPy_END_ALLOW_THREADS'}, {hasexternals: '\t\t}'}, {debugcapi: '\t\tfprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value_len,#name#_return_value);'}, '\t} /* if (f2py_success) after (string)malloc */', ], 'returnformat': '#rformat#', 'return': ',#name#_return_value', 'freemem': '\tSTRINGFREE(#name#_return_value);', 'need': ['F_FUNC', '#ctype#', 'STRINGFREE'], '_check':l_and(isstringfunction, l_not(isfunction_wrap)) # ???obsolete }, { # Debugging 'routdebugenter': '\tfprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#(#docsignature#)\\n");', 'routdebugleave': '\tfprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#: successful.\\n");', 'routdebugfailure': '\tfprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#: failure.\\n");', '_check': debugcapi } ] ################ Rules for arguments ################## typedef_need_dict = {islong_long: 'long_long', islong_double: 'long_double', islong_complex: 'complex_long_double', isunsigned_char: 'unsigned_char', isunsigned_short: 'unsigned_short', isunsigned: 'unsigned', isunsigned_long_long: 'unsigned_long_long', isunsigned_chararray: 'unsigned_char', isunsigned_shortarray: 'unsigned_short', isunsigned_long_longarray: 'unsigned_long_long', issigned_long_longarray: 'long_long', } aux_rules = [ { 'separatorsfor': sepdict }, { # Common 'frompyobj': ['\t/* Processing auxiliary variable #varname# */', {debugcapi: '\tfprintf(stderr,"#vardebuginfo#\\n");'}, ], 'cleanupfrompyobj': '\t/* End of cleaning variable #varname# */', 'need': typedef_need_dict, }, # Scalars (not complex) { # Common 'decl': '\t#ctype# #varname# = 0;', 'need': {hasinitvalue: 'math.h'}, 'frompyobj': {hasinitvalue: '\t#varname# = #init#;'}, '_check': l_and(isscalar, l_not(iscomplex)), }, { 'return': ',#varname#', 'docstrout': '#pydocsignout#', 'docreturn': '#outvarname#,', 'returnformat': '#varrformat#', '_check': l_and(isscalar, l_not(iscomplex), isintent_out), }, # Complex scalars { # Common 'decl': '\t#ctype# #varname#;', 'frompyobj': {hasinitvalue: '\t#varname#.r = #init.r#, #varname#.i = #init.i#;'}, '_check': iscomplex }, # String { # Common 'decl': ['\t#ctype# #varname# = NULL;', '\tint slen(#varname#);', ], 'need':['len..'], '_check':isstring }, # Array { # Common 'decl': ['\t#ctype# *#varname# = NULL;', '\tnpy_intp #varname#_Dims[#rank#] = {#rank*[-1]#};', '\tconst int #varname#_Rank = #rank#;', ], 'need':['len..', {hasinitvalue: 'forcomb'}, {hasinitvalue: 'CFUNCSMESS'}], '_check': isarray }, # Scalararray { # Common '_check': l_and(isarray, l_not(iscomplexarray)) }, { # Not hidden '_check': l_and(isarray, l_not(iscomplexarray), isintent_nothide) }, # Integer*1 array {'need': '#ctype#', '_check': isint1array, '_depend': '' }, # Integer*-1 array {'need': '#ctype#', '_check': isunsigned_chararray, '_depend': '' }, # Integer*-2 array {'need': '#ctype#', '_check': isunsigned_shortarray, '_depend': '' }, # Integer*-8 array {'need': '#ctype#', '_check': isunsigned_long_longarray, '_depend': '' }, # Complexarray {'need': '#ctype#', '_check': iscomplexarray, '_depend': '' }, # Stringarray { 'callfortranappend': {isarrayofstrings: 'flen(#varname#),'}, 'need': 'string', '_check': isstringarray } ] arg_rules = [ { 'separatorsfor': sepdict }, { # Common 'frompyobj': ['\t/* Processing variable #varname# */', {debugcapi: '\tfprintf(stderr,"#vardebuginfo#\\n");'}, ], 'cleanupfrompyobj': '\t/* End of cleaning variable #varname# */', '_depend': '', 'need': typedef_need_dict, }, # Doc signatures { 'docstropt': {l_and(isoptional, isintent_nothide): '#pydocsign#'}, 'docstrreq': {l_and(isrequired, isintent_nothide): '#pydocsign#'}, 'docstrout': {isintent_out: '#pydocsignout#'}, 'latexdocstropt': {l_and(isoptional, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}', {hasnote: '--- #note#'}]}, 'latexdocstrreq': {l_and(isrequired, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}', {hasnote: '--- #note#'}]}, 'latexdocstrout': {isintent_out: ['\\item[]{{}\\verb@#pydocsignout#@{}}', {l_and(hasnote, isintent_hide): '--- #note#', l_and(hasnote, isintent_nothide): '--- See above.'}]}, 'depend': '' }, # Required/Optional arguments { 'kwlist': '"#varname#",', 'docsign': '#varname#,', '_check': l_and(isintent_nothide, l_not(isoptional)) }, { 'kwlistopt': '"#varname#",', 'docsignopt': '#varname#=#showinit#,', 'docsignoptshort': '#varname#,', '_check': l_and(isintent_nothide, isoptional) }, # Docstring/BuildValue { 'docreturn': '#outvarname#,', 'returnformat': '#varrformat#', '_check': isintent_out }, # Externals (call-back functions) { # Common 'docsignxa': {isintent_nothide: '#varname#_extra_args=(),'}, 'docsignxashort': {isintent_nothide: '#varname#_extra_args,'}, 'docstropt': {isintent_nothide: '#varname#_extra_args : input tuple, optional\\n Default: ()'}, 'docstrcbs': '#cbdocstr#', 'latexdocstrcbs': '\\item[] #cblatexdocstr#', 'latexdocstropt': {isintent_nothide: '\\item[]{{}\\verb@#varname#_extra_args := () input tuple@{}} --- Extra arguments for call-back function {{}\\verb@#varname#@{}}.'}, 'decl': [' #cbname#_t #varname#_cb = { Py_None, NULL, 0 };', ' #cbname#_t *#varname#_cb_ptr = &#varname#_cb;', ' PyTupleObject *#varname#_xa_capi = NULL;', {l_not(isintent_callback): ' #cbname#_typedef #varname#_cptr;'} ], 'kwlistxa': {isintent_nothide: '"#varname#_extra_args",'}, 'argformat': {isrequired: 'O'}, 'keyformat': {isoptional: 'O'}, 'xaformat': {isintent_nothide: 'O!'}, 'args_capi': {isrequired: ',&#varname#_cb.capi'}, 'keys_capi': {isoptional: ',&#varname#_cb.capi'}, 'keys_xa': ',&PyTuple_Type,&#varname#_xa_capi', 'setjmpbuf': '(setjmp(#varname#_cb.jmpbuf))', 'callfortran': {l_not(isintent_callback): '#varname#_cptr,'}, 'need': ['#cbname#', 'setjmp.h'], '_check':isexternal }, { 'frompyobj': [{l_not(isintent_callback): """\ if(F2PyCapsule_Check(#varname#_cb.capi)) { #varname#_cptr = F2PyCapsule_AsVoidPtr(#varname#_cb.capi); } else { #varname#_cptr = #cbname#; } """}, {isintent_callback: """\ if (#varname#_cb.capi==Py_None) { #varname#_cb.capi = PyObject_GetAttrString(#modulename#_module,\"#varname#\"); if (#varname#_cb.capi) { if (#varname#_xa_capi==NULL) { if (PyObject_HasAttrString(#modulename#_module,\"#varname#_extra_args\")) { PyObject* capi_tmp = PyObject_GetAttrString(#modulename#_module,\"#varname#_extra_args\"); if (capi_tmp) { #varname#_xa_capi = (PyTupleObject *)PySequence_Tuple(capi_tmp); Py_DECREF(capi_tmp); } else { #varname#_xa_capi = (PyTupleObject *)Py_BuildValue(\"()\"); } if (#varname#_xa_capi==NULL) { PyErr_SetString(#modulename#_error,\"Failed to convert #modulename#.#varname#_extra_args to tuple.\\n\"); return NULL; } } } } if (#varname#_cb.capi==NULL) { PyErr_SetString(#modulename#_error,\"Callback #varname# not defined (as an argument or module #modulename# attribute).\\n\"); return NULL; } } """}, """\ if (create_cb_arglist(#varname#_cb.capi,#varname#_xa_capi,#maxnofargs#,#nofoptargs#,&#varname#_cb.nofargs,&#varname#_cb.args_capi,\"failed in processing argument list for call-back #varname#.\")) { """, {debugcapi: ["""\ fprintf(stderr,\"debug-capi:Assuming %d arguments; at most #maxnofargs#(-#nofoptargs#) is expected.\\n\",#varname#_cb.nofargs); CFUNCSMESSPY(\"for #varname#=\",#cbname#_capi);""", {l_not(isintent_callback): """ fprintf(stderr,\"#vardebugshowvalue# (call-back in C).\\n\",#cbname#);"""}]}, """\ CFUNCSMESS(\"Saving callback variables for `#varname#`.\\n\"); #varname#_cb_ptr = swap_active_#cbname#(#varname#_cb_ptr);""", ], 'cleanupfrompyobj': """\ CFUNCSMESS(\"Restoring callback variables for `#varname#`.\\n\"); #varname#_cb_ptr = swap_active_#cbname#(#varname#_cb_ptr); Py_DECREF(#varname#_cb.args_capi); }""", 'need': ['SWAP', 'create_cb_arglist'], '_check':isexternal, '_depend':'' }, # Scalars (not complex) { # Common 'decl': '\t#ctype# #varname# = 0;', 'pyobjfrom': {debugcapi: '\tfprintf(stderr,"#vardebugshowvalue#\\n",#varname#);'}, 'callfortran': {isintent_c: '#varname#,', l_not(isintent_c): '&#varname#,'}, 'return': {isintent_out: ',#varname#'}, '_check': l_and(isscalar, l_not(iscomplex)) }, { 'need': {hasinitvalue: 'math.h'}, '_check': l_and(isscalar, l_not(iscomplex)), }, { # Not hidden 'decl': '\tPyObject *#varname#_capi = Py_None;', 'argformat': {isrequired: 'O'}, 'keyformat': {isoptional: 'O'}, 'args_capi': {isrequired: ',&#varname#_capi'}, 'keys_capi': {isoptional: ',&#varname#_capi'}, 'pyobjfrom': {isintent_inout: """\ \tf2py_success = try_pyarr_from_#ctype#(#varname#_capi,&#varname#); \tif (f2py_success) {"""}, 'closepyobjfrom': {isintent_inout: "\t} /*if (f2py_success) of #varname# pyobjfrom*/"}, 'need': {isintent_inout: 'try_pyarr_from_#ctype#'}, '_check': l_and(isscalar, l_not(iscomplex), isintent_nothide) }, { 'frompyobj': [ # hasinitvalue... # if pyobj is None: # varname = init # else # from_pyobj(varname) # # isoptional and noinitvalue... # if pyobj is not None: # from_pyobj(varname) # else: # varname is uninitialized # # ... # from_pyobj(varname) # {hasinitvalue: '\tif (#varname#_capi == Py_None) #varname# = #init#; else', '_depend': ''}, {l_and(isoptional, l_not(hasinitvalue)): '\tif (#varname#_capi != Py_None)', '_depend': ''}, {l_not(islogical): '''\ \t\tf2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#pyname#() #nth# (#varname#) can\'t be converted to #ctype#"); \tif (f2py_success) {'''}, {islogical: '''\ \t\t#varname# = (#ctype#)PyObject_IsTrue(#varname#_capi); \t\tf2py_success = 1; \tif (f2py_success) {'''}, ], 'cleanupfrompyobj': '\t} /*if (f2py_success) of #varname#*/', 'need': {l_not(islogical): '#ctype#_from_pyobj'}, '_check': l_and(isscalar, l_not(iscomplex), isintent_nothide), '_depend': '' }, { # Hidden 'frompyobj': {hasinitvalue: '\t#varname# = #init#;'}, 'need': typedef_need_dict, '_check': l_and(isscalar, l_not(iscomplex), isintent_hide), '_depend': '' }, { # Common 'frompyobj': {debugcapi: '\tfprintf(stderr,"#vardebugshowvalue#\\n",#varname#);'}, '_check': l_and(isscalar, l_not(iscomplex)), '_depend': '' }, # Complex scalars { # Common 'decl': '\t#ctype# #varname#;', 'callfortran': {isintent_c: '#varname#,', l_not(isintent_c): '&#varname#,'}, 'pyobjfrom': {debugcapi: '\tfprintf(stderr,"#vardebugshowvalue#\\n",#varname#.r,#varname#.i);'}, 'return': {isintent_out: ',#varname#_capi'}, '_check': iscomplex }, { # Not hidden 'decl': '\tPyObject *#varname#_capi = Py_None;', 'argformat': {isrequired: 'O'}, 'keyformat': {isoptional: 'O'}, 'args_capi': {isrequired: ',&#varname#_capi'}, 'keys_capi': {isoptional: ',&#varname#_capi'}, 'need': {isintent_inout: 'try_pyarr_from_#ctype#'}, 'pyobjfrom': {isintent_inout: """\ \t\tf2py_success = try_pyarr_from_#ctype#(#varname#_capi,&#varname#); \t\tif (f2py_success) {"""}, 'closepyobjfrom': {isintent_inout: "\t\t} /*if (f2py_success) of #varname# pyobjfrom*/"}, '_check': l_and(iscomplex, isintent_nothide) }, { 'frompyobj': [{hasinitvalue: '\tif (#varname#_capi==Py_None) {#varname#.r = #init.r#, #varname#.i = #init.i#;} else'}, {l_and(isoptional, l_not(hasinitvalue)) : '\tif (#varname#_capi != Py_None)'}, '\t\tf2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#pyname#() #nth# (#varname#) can\'t be converted to #ctype#");' '\n\tif (f2py_success) {'], 'cleanupfrompyobj': '\t} /*if (f2py_success) of #varname# frompyobj*/', 'need': ['#ctype#_from_pyobj'], '_check': l_and(iscomplex, isintent_nothide), '_depend': '' }, { # Hidden 'decl': {isintent_out: '\tPyObject *#varname#_capi = Py_None;'}, '_check': l_and(iscomplex, isintent_hide) }, { 'frompyobj': {hasinitvalue: '\t#varname#.r = #init.r#, #varname#.i = #init.i#;'}, '_check': l_and(iscomplex, isintent_hide), '_depend': '' }, { # Common 'pyobjfrom': {isintent_out: '\t#varname#_capi = pyobj_from_#ctype#1(#varname#);'}, 'need': ['pyobj_from_#ctype#1'], '_check': iscomplex }, { 'frompyobj': {debugcapi: '\tfprintf(stderr,"#vardebugshowvalue#\\n",#varname#.r,#varname#.i);'}, '_check': iscomplex, '_depend': '' }, # String { # Common 'decl': ['\t#ctype# #varname# = NULL;', '\tint slen(#varname#);', '\tPyObject *#varname#_capi = Py_None;'], 'callfortran':'#varname#,', 'callfortranappend':'slen(#varname#),', 'pyobjfrom':{debugcapi: '\tfprintf(stderr,"#vardebugshowvalue#\\n",slen(#varname#),#varname#);'}, 'return': {isintent_out: ',#varname#'}, 'need': ['len..'], # 'STRINGFREE'], '_check':isstring }, { # Common 'frompyobj': """\ \tslen(#varname#) = #length#; \tf2py_success = #ctype#_from_pyobj(&#varname#,&slen(#varname#),#init#,#varname#_capi,\"#ctype#_from_pyobj failed in converting #nth# `#varname#\' of #pyname# to C #ctype#\"); \tif (f2py_success) {""", 'cleanupfrompyobj': """\ \t\tSTRINGFREE(#varname#); \t} /*if (f2py_success) of #varname#*/""", 'need': ['#ctype#_from_pyobj', 'len..', 'STRINGFREE'], '_check':isstring, '_depend':'' }, { # Not hidden 'argformat': {isrequired: 'O'}, 'keyformat': {isoptional: 'O'}, 'args_capi': {isrequired: ',&#varname#_capi'}, 'keys_capi': {isoptional: ',&#varname#_capi'}, 'pyobjfrom': {isintent_inout: '''\ \tf2py_success = try_pyarr_from_#ctype#(#varname#_capi,#varname#); \tif (f2py_success) {'''}, 'closepyobjfrom': {isintent_inout: '\t} /*if (f2py_success) of #varname# pyobjfrom*/'}, 'need': {isintent_inout: 'try_pyarr_from_#ctype#'}, '_check': l_and(isstring, isintent_nothide) }, { # Hidden '_check': l_and(isstring, isintent_hide) }, { 'frompyobj': {debugcapi: '\tfprintf(stderr,"#vardebugshowvalue#\\n",slen(#varname#),#varname#);'}, '_check': isstring, '_depend': '' }, # Array { # Common 'decl': ['\t#ctype# *#varname# = NULL;', '\tnpy_intp #varname#_Dims[#rank#] = {#rank*[-1]#};', '\tconst int #varname#_Rank = #rank#;', '\tPyArrayObject *capi_#varname#_tmp = NULL;', '\tint capi_#varname#_intent = 0;', ], 'callfortran':'#varname#,', 'return':{isintent_out: ',capi_#varname#_tmp'}, 'need': 'len..', '_check': isarray }, { # intent(overwrite) array 'decl': '\tint capi_overwrite_#varname# = 1;', 'kwlistxa': '"overwrite_#varname#",', 'xaformat': 'i', 'keys_xa': ',&capi_overwrite_#varname#', 'docsignxa': 'overwrite_#varname#=1,', 'docsignxashort': 'overwrite_#varname#,', 'docstropt': 'overwrite_#varname# : input int, optional\\n Default: 1', '_check': l_and(isarray, isintent_overwrite), }, { 'frompyobj': '\tcapi_#varname#_intent |= (capi_overwrite_#varname#?0:F2PY_INTENT_COPY);', '_check': l_and(isarray, isintent_overwrite), '_depend': '', }, { # intent(copy) array 'decl': '\tint capi_overwrite_#varname# = 0;', 'kwlistxa': '"overwrite_#varname#",', 'xaformat': 'i', 'keys_xa': ',&capi_overwrite_#varname#', 'docsignxa': 'overwrite_#varname#=0,', 'docsignxashort': 'overwrite_#varname#,', 'docstropt': 'overwrite_#varname# : input int, optional\\n Default: 0', '_check': l_and(isarray, isintent_copy), }, { 'frompyobj': '\tcapi_#varname#_intent |= (capi_overwrite_#varname#?0:F2PY_INTENT_COPY);', '_check': l_and(isarray, isintent_copy), '_depend': '', }, { 'need': [{hasinitvalue: 'forcomb'}, {hasinitvalue: 'CFUNCSMESS'}], '_check': isarray, '_depend': '' }, { # Not hidden 'decl': '\tPyObject *#varname#_capi = Py_None;', 'argformat': {isrequired: 'O'}, 'keyformat': {isoptional: 'O'}, 'args_capi': {isrequired: ',&#varname#_capi'}, 'keys_capi': {isoptional: ',&#varname#_capi'}, '_check': l_and(isarray, isintent_nothide) }, { 'frompyobj': ['\t#setdims#;', '\tcapi_#varname#_intent |= #intent#;', {isintent_hide: '\tcapi_#varname#_tmp = array_from_pyobj(#atype#,#varname#_Dims,#varname#_Rank,capi_#varname#_intent,Py_None);'}, {isintent_nothide: '\tcapi_#varname#_tmp = array_from_pyobj(#atype#,#varname#_Dims,#varname#_Rank,capi_#varname#_intent,#varname#_capi);'}, """\ \tif (capi_#varname#_tmp == NULL) { \t\tPyObject *exc, *val, *tb; \t\tPyErr_Fetch(&exc, &val, &tb); \t\tPyErr_SetString(exc ? exc : #modulename#_error,\"failed in converting #nth# `#varname#\' of #pyname# to C/Fortran array\" ); \t\tnpy_PyErr_ChainExceptionsCause(exc, val, tb); \t} else { \t\t#varname# = (#ctype# *)(PyArray_DATA(capi_#varname#_tmp)); """, {hasinitvalue: [ {isintent_nothide: '\tif (#varname#_capi == Py_None) {'}, {isintent_hide: '\t{'}, {iscomplexarray: '\t\t#ctype# capi_c;'}, """\ \t\tint *_i,capi_i=0; \t\tCFUNCSMESS(\"#name#: Initializing #varname#=#init#\\n\"); \t\tif (initforcomb(PyArray_DIMS(capi_#varname#_tmp),PyArray_NDIM(capi_#varname#_tmp),1)) { \t\t\twhile ((_i = nextforcomb())) \t\t\t\t#varname#[capi_i++] = #init#; /* fortran way */ \t\t} else { \t\t\tPyObject *exc, *val, *tb; \t\t\tPyErr_Fetch(&exc, &val, &tb); \t\t\tPyErr_SetString(exc ? exc : #modulename#_error,\"Initialization of #nth# #varname# failed (initforcomb).\"); \t\t\tnpy_PyErr_ChainExceptionsCause(exc, val, tb); \t\t\tf2py_success = 0; \t\t} \t} \tif (f2py_success) {"""]}, ], 'cleanupfrompyobj': [ # note that this list will be reversed '\t} /*if (capi_#varname#_tmp == NULL) ... else of #varname#*/', {l_not(l_or(isintent_out, isintent_hide)): """\ \tif((PyObject *)capi_#varname#_tmp!=#varname#_capi) { \t\tPy_XDECREF(capi_#varname#_tmp); }"""}, {l_and(isintent_hide, l_not(isintent_out)) : """\t\tPy_XDECREF(capi_#varname#_tmp);"""}, {hasinitvalue: '\t} /*if (f2py_success) of #varname# init*/'}, ], '_check': isarray, '_depend': '' }, # Scalararray { # Common '_check': l_and(isarray, l_not(iscomplexarray)) }, { # Not hidden '_check': l_and(isarray, l_not(iscomplexarray), isintent_nothide) }, # Integer*1 array {'need': '#ctype#', '_check': isint1array, '_depend': '' }, # Integer*-1 array {'need': '#ctype#', '_check': isunsigned_chararray, '_depend': '' }, # Integer*-2 array {'need': '#ctype#', '_check': isunsigned_shortarray, '_depend': '' }, # Integer*-8 array {'need': '#ctype#', '_check': isunsigned_long_longarray, '_depend': '' }, # Complexarray {'need': '#ctype#', '_check': iscomplexarray, '_depend': '' }, # Stringarray { 'callfortranappend': {isarrayofstrings: 'flen(#varname#),'}, 'need': 'string', '_check': isstringarray } ] ################# Rules for checking ############### check_rules = [ { 'frompyobj': {debugcapi: '\tfprintf(stderr,\"debug-capi:Checking `#check#\'\\n\");'}, 'need': 'len..' }, { 'frompyobj': '\tCHECKSCALAR(#check#,\"#check#\",\"#nth# #varname#\",\"#varshowvalue#\",#varname#) {', 'cleanupfrompyobj': '\t} /*CHECKSCALAR(#check#)*/', 'need': 'CHECKSCALAR', '_check': l_and(isscalar, l_not(iscomplex)), '_break': '' }, { 'frompyobj': '\tCHECKSTRING(#check#,\"#check#\",\"#nth# #varname#\",\"#varshowvalue#\",#varname#) {', 'cleanupfrompyobj': '\t} /*CHECKSTRING(#check#)*/', 'need': 'CHECKSTRING', '_check': isstring, '_break': '' }, { 'need': 'CHECKARRAY', 'frompyobj': '\tCHECKARRAY(#check#,\"#check#\",\"#nth# #varname#\") {', 'cleanupfrompyobj': '\t} /*CHECKARRAY(#check#)*/', '_check': isarray, '_break': '' }, { 'need': 'CHECKGENERIC', 'frompyobj': '\tCHECKGENERIC(#check#,\"#check#\",\"#nth# #varname#\") {', 'cleanupfrompyobj': '\t} /*CHECKGENERIC(#check#)*/', } ] ########## Applying the rules. No need to modify what follows ############# #################### Build C/API module ####################### def buildmodule(m, um): """ Return """ outmess('\tBuilding module "%s"...\n' % (m['name'])) ret = {} mod_rules = defmod_rules[:] vrd = capi_maps.modsign2map(m) rd = dictappend({'f2py_version': f2py_version}, vrd) funcwrappers = [] funcwrappers2 = [] # F90 codes for n in m['interfaced']: nb = None for bi in m['body']: if not bi['block'] == 'interface': errmess('buildmodule: Expected interface block. Skipping.\n') continue for b in bi['body']: if b['name'] == n: nb = b break if not nb: errmess( 'buildmodule: Could not found the body of interfaced routine "%s". Skipping.\n' % (n)) continue nb_list = [nb] if 'entry' in nb: for k, a in nb['entry'].items(): nb1 = copy.deepcopy(nb) del nb1['entry'] nb1['name'] = k nb1['args'] = a nb_list.append(nb1) for nb in nb_list: # requiresf90wrapper must be called before buildapi as it # rewrites assumed shape arrays as automatic arrays. isf90 = requiresf90wrapper(nb) api, wrap = buildapi(nb) if wrap: if isf90: funcwrappers2.append(wrap) else: funcwrappers.append(wrap) ar = applyrules(api, vrd) rd = dictappend(rd, ar) # Construct COMMON block support cr, wrap = common_rules.buildhooks(m) if wrap: funcwrappers.append(wrap) ar = applyrules(cr, vrd) rd = dictappend(rd, ar) # Construct F90 module support mr, wrap = f90mod_rules.buildhooks(m) if wrap: funcwrappers2.append(wrap) ar = applyrules(mr, vrd) rd = dictappend(rd, ar) for u in um: ar = use_rules.buildusevars(u, m['use'][u['name']]) rd = dictappend(rd, ar) needs = cfuncs.get_needs() code = {} for n in needs.keys(): code[n] = [] for k in needs[n]: c = '' if k in cfuncs.includes0: c = cfuncs.includes0[k] elif k in cfuncs.includes: c = cfuncs.includes[k] elif k in cfuncs.userincludes: c = cfuncs.userincludes[k] elif k in cfuncs.typedefs: c = cfuncs.typedefs[k] elif k in cfuncs.typedefs_generated: c = cfuncs.typedefs_generated[k] elif k in cfuncs.cppmacros: c = cfuncs.cppmacros[k] elif k in cfuncs.cfuncs: c = cfuncs.cfuncs[k] elif k in cfuncs.callbacks: c = cfuncs.callbacks[k] elif k in cfuncs.f90modhooks: c = cfuncs.f90modhooks[k] elif k in cfuncs.commonhooks: c = cfuncs.commonhooks[k] else: errmess('buildmodule: unknown need %s.\n' % (repr(k))) continue code[n].append(c) mod_rules.append(code) for r in mod_rules: if ('_check' in r and r['_check'](m)) or ('_check' not in r): ar = applyrules(r, vrd, m) rd = dictappend(rd, ar) ar = applyrules(module_rules, rd) fn = os.path.join(options['buildpath'], vrd['coutput']) ret['csrc'] = fn with open(fn, 'w') as f: f.write(ar['modulebody'].replace('\t', 2 * ' ')) outmess('\tWrote C/API module "%s" to file "%s"\n' % (m['name'], fn)) if options['dorestdoc']: fn = os.path.join( options['buildpath'], vrd['modulename'] + 'module.rest') with open(fn, 'w') as f: f.write('.. -*- rest -*-\n') f.write('\n'.join(ar['restdoc'])) outmess('\tReST Documentation is saved to file "%s/%smodule.rest"\n' % (options['buildpath'], vrd['modulename'])) if options['dolatexdoc']: fn = os.path.join( options['buildpath'], vrd['modulename'] + 'module.tex') ret['ltx'] = fn with open(fn, 'w') as f: f.write( '%% This file is auto-generated with f2py (version:%s)\n' % (f2py_version)) if 'shortlatex' not in options: f.write( '\\documentclass{article}\n\\usepackage{a4wide}\n\\begin{document}\n\\tableofcontents\n\n') f.write('\n'.join(ar['latexdoc'])) if 'shortlatex' not in options: f.write('\\end{document}') outmess('\tDocumentation is saved to file "%s/%smodule.tex"\n' % (options['buildpath'], vrd['modulename'])) if funcwrappers: wn = os.path.join(options['buildpath'], vrd['f2py_wrapper_output']) ret['fsrc'] = wn with open(wn, 'w') as f: f.write('C -*- fortran -*-\n') f.write( 'C This file is autogenerated with f2py (version:%s)\n' % (f2py_version)) f.write( 'C It contains Fortran 77 wrappers to fortran functions.\n') lines = [] for l in ('\n\n'.join(funcwrappers) + '\n').split('\n'): if 0 <= l.find('!') < 66: # don't split comment lines lines.append(l + '\n') elif l and l[0] == ' ': while len(l) >= 66: lines.append(l[:66] + '\n &') l = l[66:] lines.append(l + '\n') else: lines.append(l + '\n') lines = ''.join(lines).replace('\n &\n', '\n') f.write(lines) outmess('\tFortran 77 wrappers are saved to "%s"\n' % (wn)) if funcwrappers2: wn = os.path.join( options['buildpath'], '%s-f2pywrappers2.f90' % (vrd['modulename'])) ret['fsrc'] = wn with open(wn, 'w') as f: f.write('! -*- f90 -*-\n') f.write( '! This file is autogenerated with f2py (version:%s)\n' % (f2py_version)) f.write( '! It contains Fortran 90 wrappers to fortran functions.\n') lines = [] for l in ('\n\n'.join(funcwrappers2) + '\n').split('\n'): if 0 <= l.find('!') < 72: # don't split comment lines lines.append(l + '\n') elif len(l) > 72 and l[0] == ' ': lines.append(l[:72] + '&\n &') l = l[72:] while len(l) > 66: lines.append(l[:66] + '&\n &') l = l[66:] lines.append(l + '\n') else: lines.append(l + '\n') lines = ''.join(lines).replace('\n &\n', '\n') f.write(lines) outmess('\tFortran 90 wrappers are saved to "%s"\n' % (wn)) return ret ################## Build C/API function ############# stnd = {1: 'st', 2: 'nd', 3: 'rd', 4: 'th', 5: 'th', 6: 'th', 7: 'th', 8: 'th', 9: 'th', 0: 'th'} def buildapi(rout): rout, wrap = func2subr.assubr(rout) args, depargs = getargs2(rout) capi_maps.depargs = depargs var = rout['vars'] if ismoduleroutine(rout): outmess('\t\t\tConstructing wrapper function "%s.%s"...\n' % (rout['modulename'], rout['name'])) else: outmess('\t\tConstructing wrapper function "%s"...\n' % (rout['name'])) # Routine vrd = capi_maps.routsign2map(rout) rd = dictappend({}, vrd) for r in rout_rules: if ('_check' in r and r['_check'](rout)) or ('_check' not in r): ar = applyrules(r, vrd, rout) rd = dictappend(rd, ar) # Args nth, nthk = 0, 0 savevrd = {} for a in args: vrd = capi_maps.sign2map(a, var[a]) if isintent_aux(var[a]): _rules = aux_rules else: _rules = arg_rules if not isintent_hide(var[a]): if not isoptional(var[a]): nth = nth + 1 vrd['nth'] = repr(nth) + stnd[nth % 10] + ' argument' else: nthk = nthk + 1 vrd['nth'] = repr(nthk) + stnd[nthk % 10] + ' keyword' else: vrd['nth'] = 'hidden' savevrd[a] = vrd for r in _rules: if '_depend' in r: continue if ('_check' in r and r['_check'](var[a])) or ('_check' not in r): ar = applyrules(r, vrd, var[a]) rd = dictappend(rd, ar) if '_break' in r: break for a in depargs: if isintent_aux(var[a]): _rules = aux_rules else: _rules = arg_rules vrd = savevrd[a] for r in _rules: if '_depend' not in r: continue if ('_check' in r and r['_check'](var[a])) or ('_check' not in r): ar = applyrules(r, vrd, var[a]) rd = dictappend(rd, ar) if '_break' in r: break if 'check' in var[a]: for c in var[a]['check']: vrd['check'] = c ar = applyrules(check_rules, vrd, var[a]) rd = dictappend(rd, ar) if isinstance(rd['cleanupfrompyobj'], list): rd['cleanupfrompyobj'].reverse() if isinstance(rd['closepyobjfrom'], list): rd['closepyobjfrom'].reverse() rd['docsignature'] = stripcomma(replace('#docsign##docsignopt##docsignxa#', {'docsign': rd['docsign'], 'docsignopt': rd['docsignopt'], 'docsignxa': rd['docsignxa']})) optargs = stripcomma(replace('#docsignopt##docsignxa#', {'docsignxa': rd['docsignxashort'], 'docsignopt': rd['docsignoptshort']} )) if optargs == '': rd['docsignatureshort'] = stripcomma( replace('#docsign#', {'docsign': rd['docsign']})) else: rd['docsignatureshort'] = replace('#docsign#[#docsignopt#]', {'docsign': rd['docsign'], 'docsignopt': optargs, }) rd['latexdocsignatureshort'] = rd['docsignatureshort'].replace('_', '\\_') rd['latexdocsignatureshort'] = rd[ 'latexdocsignatureshort'].replace(',', ', ') cfs = stripcomma(replace('#callfortran##callfortranappend#', { 'callfortran': rd['callfortran'], 'callfortranappend': rd['callfortranappend']})) if len(rd['callfortranappend']) > 1: rd['callcompaqfortran'] = stripcomma(replace('#callfortran# 0,#callfortranappend#', { 'callfortran': rd['callfortran'], 'callfortranappend': rd['callfortranappend']})) else: rd['callcompaqfortran'] = cfs rd['callfortran'] = cfs if isinstance(rd['docreturn'], list): rd['docreturn'] = stripcomma( replace('#docreturn#', {'docreturn': rd['docreturn']})) + ' = ' rd['docstrsigns'] = [] rd['latexdocstrsigns'] = [] for k in ['docstrreq', 'docstropt', 'docstrout', 'docstrcbs']: if k in rd and isinstance(rd[k], list): rd['docstrsigns'] = rd['docstrsigns'] + rd[k] k = 'latex' + k if k in rd and isinstance(rd[k], list): rd['latexdocstrsigns'] = rd['latexdocstrsigns'] + rd[k][0:1] +\ ['\\begin{description}'] + rd[k][1:] +\ ['\\end{description}'] ar = applyrules(routine_rules, rd) if ismoduleroutine(rout): outmess('\t\t\t %s\n' % (ar['docshort'])) else: outmess('\t\t %s\n' % (ar['docshort'])) return ar, wrap #################### EOF rules.py #######################
# Copyright 2020 The TensorTrade Authors. # # 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 import os import sys import logging import importlib from abc import abstractmethod from datetime import datetime from typing import Union, Tuple from collections import OrderedDict import numpy as np import pandas as pd from IPython.display import display, clear_output from pandas.plotting import register_matplotlib_converters from tensortrade.oms.orders import TradeSide from tensortrade.env.generic import Renderer, TradingEnv if importlib.util.find_spec("matplotlib"): import matplotlib.pyplot as plt from matplotlib import style style.use("ggplot") register_matplotlib_converters() if importlib.util.find_spec("plotly"): import plotly.graph_objects as go from plotly.subplots import make_subplots def _create_auto_file_name(filename_prefix: str, ext: str, timestamp_format: str = '%Y%m%d_%H%M%S') -> str: timestamp = datetime.now().strftime(timestamp_format) filename = filename_prefix + timestamp + '.' + ext return filename def _check_path(path: str, auto_create: bool = True) -> None: if not path or os.path.exists(path): return if auto_create: os.mkdir(path) else: raise OSError(f"Path '{path}' not found.") def _check_valid_format(valid_formats: list, save_format: str) -> None: if save_format not in valid_formats: raise ValueError("Acceptable formats are '{}'. Found '{}'".format("', '".join(valid_formats), save_format)) class BaseRenderer(Renderer): """The abstract base renderer to be subclassed when making a renderer the incorporates a `Portfolio`. """ def __init__(self): super().__init__() self._max_episodes = None self._max_steps = None @staticmethod def _create_log_entry(episode: int = None, max_episodes: int = None, step: int = None, max_steps: int = None, date_format: str = "%Y-%m-%d %H:%M:%S %p") -> str: """ Creates a log entry to be used by a renderer. Parameters ---------- episode : int The current episode. max_episodes : int The maximum number of episodes that can occur. step : int The current step of the current episode. max_steps : int The maximum number of steps within an episode that can occur. date_format : str The format for logging the date. Returns ------- str a log entry """ log_entry = f"[{datetime.now().strftime(date_format)}]" if episode is not None: log_entry += f" Episode: {episode + 1}/{max_episodes if max_episodes else ""}" if step is not None: log_entry += f" Step: {step}/{max_steps if max_steps else ""}" return log_entry def render(self, env: 'TradingEnv', **kwargs): price_history = None if len(env.observer.renderer_history) > 0: price_history = pd.DataFrame(env.observer.renderer_history) performance = pd.DataFrame.from_dict(env.action_scheme.portfolio.performance, orient='index') self.render_env( episode=kwargs.get("episode", None), max_episodes=kwargs.get("max_episodes", None), step=env.clock.step, max_steps=kwargs.get("max_steps", None), price_history=price_history, net_worth=performance.net_worth, performance=performance.drop(columns=['base_symbol']), trades=env.action_scheme.broker.trades ) @abstractmethod def render_env(self, episode: int = None, max_episodes: int = None, step: int = None, max_steps: int = None, price_history: 'pd.DataFrame' = None, net_worth: 'pd.Series' = None, performance: 'pd.DataFrame' = None, trades: 'OrderedDict' = None) -> None: """Renderers the current state of the environment. Parameters ---------- episode : int The episode that the environment is being rendered for. max_episodes : int The maximum number of episodes that will occur. step : int The step of the current episode that is happening. max_steps : int The maximum number of steps that will occur in an episode. price_history : `pd.DataFrame` The history of instrument involved with the environment. The required columns are: date, open, high, low, close, and volume. net_worth : `pd.Series` The history of the net worth of the `portfolio`. performance : `pd.Series` The history of performance of the `portfolio`. trades : `OrderedDict` The history of trades for the current episode. """ raise NotImplementedError() def save(self) -> None: """Saves the rendering of the `TradingEnv`. """ pass def reset(self) -> None: """Resets the renderer. """ pass class EmptyRenderer(Renderer): """A renderer that does renders nothing. Needed to make sure that environment can function without requiring a renderer. """ def render(self, env, **kwargs): pass class ScreenLogger(BaseRenderer): """Logs information the screen of the user. Parameters ---------- date_format : str The format for logging the date. """ DEFAULT_FORMAT: str = "[%(asctime)-15s] %(message)s" def __init__(self, date_format: str = "%Y-%m-%d %-I:%M:%S %p"): super().__init__() self._date_format = date_format def render_env(self, episode: int = None, max_episodes: int = None, step: int = None, max_steps: int = None, price_history: pd.DataFrame = None, net_worth: pd.Series = None, performance: pd.DataFrame = None, trades: 'OrderedDict' = None): print(self._create_log_entry(episode, max_episodes, step, max_steps, date_format=self._date_format)) class FileLogger(BaseRenderer): """Logs information to a file. Parameters ---------- filename : str The file name of the log file. If omitted, a file name will be created automatically. path : str The path to save the log files to. None to save to same script directory. log_format : str The log entry format as per Python logging. None for default. For more details, refer to https://docs.python.org/3/library/logging.html timestamp_format : str The format of the timestamp of the log entry. Node for default. """ DEFAULT_LOG_FORMAT: str = '[%(asctime)-15s] %(message)s' DEFAULT_TIMESTAMP_FORMAT: str = '%Y-%m-%d %H:%M:%S' def __init__(self, filename: str = None, path: str = 'log', log_format: str = None, timestamp_format: str = None) -> None: super().__init__() _check_path(path) if not filename: filename = _create_auto_file_name('log_', 'log') self._logger = logging.getLogger(self.id) self._logger.setLevel(logging.INFO) if path: filename = os.path.join(path, filename) handler = logging.FileHandler(filename) handler.setFormatter( logging.Formatter( log_format if log_format is not None else self.DEFAULT_LOG_FORMAT, datefmt=timestamp_format if timestamp_format is not None else self.DEFAULT_TIMESTAMP_FORMAT ) ) self._logger.addHandler(handler) @property def log_file(self) -> str: """The filename information is being logged to. (str, read-only) """ return self._logger.handlers[0].baseFilename def render_env(self, episode: int = None, max_episodes: int = None, step: int = None, max_steps: int = None, price_history: pd.DataFrame = None, net_worth: pd.Series = None, performance: pd.DataFrame = None, trades: 'OrderedDict' = None) -> None: log_entry = self._create_log_entry(episode, max_episodes, step, max_steps) self._logger.info(f"{log_entry} - Performance:\n{performance}") class PlotlyTradingChart(BaseRenderer): """Trading visualization for TensorTrade using Plotly. Parameters ---------- display : bool True to display the chart on the screen, False for not. height : int Chart height in pixels. Affects both display and saved file charts. Set to None for 100% height. Default is None. save_format : str A format to save the chart to. Acceptable formats are html, png, jpeg, webp, svg, pdf, eps. All the formats except for 'html' require Orca. Default is None for no saving. path : str The path to save the char to if save_format is not None. The folder will be created if not found. filename_prefix : str A string that precedes automatically-created file name when charts are saved. Default 'chart_'. timestamp_format : str The format of the date shown in the chart title. auto_open_html : bool Works for save_format='html' only. True to automatically open the saved chart HTML file in the default browser, False otherwise. include_plotlyjs : Union[bool, str] Whether to include/load the plotly.js library in the saved file. 'cdn' results in a smaller file by loading the library online but requires an Internet connect while True includes the library resulting in much larger file sizes. False to not include the library. For more details, refer to https://plot.ly/python-api-reference/generated/plotly.graph_objects.Figure.html Notes ----- Possible Future Enhancements: - Saving images without using Orca. - Limit displayed step range for the case of a large number of steps and let the shown part of the chart slide after filling that range to keep showing recent data as it's being added. References ---------- .. [1] https://plot.ly/python-api-reference/generated/plotly.graph_objects.Figure.html .. [2] https://plot.ly/python/figurewidget/ .. [3] https://plot.ly/python/subplots/ .. [4] https://plot.ly/python/reference/#candlestick .. [5] https://plot.ly/python/#chart-events """ def __init__(self, display: bool = True, height: int = None, timestamp_format: str = '%Y-%m-%d %H:%M:%S', save_format: str = None, path: str = 'charts', filename_prefix: str = 'chart_', auto_open_html: bool = False, include_plotlyjs: Union[bool, str] = 'cdn') -> None: super().__init__() self._height = height self._timestamp_format = timestamp_format self._save_format = save_format self._path = path self._filename_prefix = filename_prefix self._include_plotlyjs = include_plotlyjs self._auto_open_html = auto_open_html if self._save_format and self._path and not os.path.exists(path): os.mkdir(path) self.fig = None self._price_chart = None self._volume_chart = None self._performance_chart = None self._net_worth_chart = None self._base_annotations = None self._last_trade_step = 0 self._show_chart = display def _create_figure(self, performance_keys: dict) -> None: fig = make_subplots( rows=4, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights=[0.55, 0.15, 0.15, 0.15], ) fig.add_trace(go.Candlestick(name='Price', xaxis='x1', yaxis='y1', showlegend=False), row=1, col=1) fig.update_layout(xaxis_rangeslider_visible=False) fig.add_trace(go.Bar(name='Volume', showlegend=False, marker={'color': 'DodgerBlue'}), row=2, col=1) for k in performance_keys: fig.add_trace(go.Scatter(mode='lines', name=k), row=3, col=1) fig.add_trace(go.Scatter(mode='lines', name='Net Worth', marker={'color': 'DarkGreen'}), row=4, col=1) fig.update_xaxes(linecolor='Grey', gridcolor='Gainsboro') fig.update_yaxes(linecolor='Grey', gridcolor='Gainsboro') fig.update_xaxes(title_text='Price', row=1) fig.update_xaxes(title_text='Volume', row=2) fig.update_xaxes(title_text='Performance', row=3) fig.update_xaxes(title_text='Net Worth', row=4) fig.update_xaxes(title_standoff=7, title_font=dict(size=12)) self.fig = go.FigureWidget(fig) self._price_chart = self.fig.data[0] self._volume_chart = self.fig.data[1] self._performance_chart = self.fig.data[2] self._net_worth_chart = self.fig.data[-1] self.fig.update_annotations({'font': {'size': 12}}) self.fig.update_layout(template='plotly_white', height=self._height, margin=dict(t=50)) self._base_annotations = self.fig.layout.annotations def _create_trade_annotations(self, trades: 'OrderedDict', price_history: 'pd.DataFrame') -> 'Tuple[go.layout.Annotation]': """Creates annotations of the new trades after the last one in the chart. Parameters ---------- trades : `OrderedDict` The history of trades for the current episode. price_history : `pd.DataFrame` The price history of the current episode. Returns ------- `Tuple[go.layout.Annotation]` A tuple of annotations used in the renderering process. """ annotations = [] for trade in reversed(trades.values()): trade = trade[0] tp = float(trade.price) ts = float(trade.size) if trade.step <= self._last_trade_step: break if trade.side.value == 'buy': color = 'DarkGreen' ay = 15 qty = round(ts / tp, trade.quote_instrument.precision) text_info = dict( step=trade.step, datetime=price_history.iloc[trade.step - 1]['date'], side=trade.side.value.upper(), qty=qty, size=ts, quote_instrument=trade.quote_instrument, price=tp, base_instrument=trade.base_instrument, type=trade.type.value.upper(), commission=trade.commission ) elif trade.side.value == 'sell': color = 'FireBrick' ay = -15 # qty = round(ts * tp, trade.quote_instrument.precision) text_info = dict( step=trade.step, datetime=price_history.iloc[trade.step - 1]['date'], side=trade.side.value.upper(), qty=ts, size=round(ts * tp, trade.base_instrument.precision), quote_instrument=trade.quote_instrument, price=tp, base_instrument=trade.base_instrument, type=trade.type.value.upper(), commission=trade.commission ) else: raise ValueError(f"Valid trade side values are 'buy' and 'sell'. Found '{trade.side.value}'.") hovertext = 'Step {step} [{datetime}]<br>' \ '{side} {qty} {quote_instrument} @ {price} {base_instrument} {type}<br>' \ 'Total: {size} {base_instrument} - Comm.: {commission}'.format(**text_info) annotations += [go.layout.Annotation( x=trade.step - 1, y=tp, ax=0, ay=ay, xref='x1', yref='y1', showarrow=True, arrowhead=2, arrowcolor=color, arrowwidth=4, arrowsize=0.8, hovertext=hovertext, opacity=0.6, hoverlabel=dict(bgcolor=color) )] if trades: self._last_trade_step = trades[list(trades)[-1]][0].step return tuple(annotations) def render_env(self, episode: int = None, max_episodes: int = None, step: int = None, max_steps: int = None, price_history: pd.DataFrame = None, net_worth: pd.Series = None, performance: pd.DataFrame = None, trades: 'OrderedDict' = None) -> None: if price_history is None: raise ValueError("renderers() is missing required positional argument 'price_history'.") if net_worth is None: raise ValueError("renderers() is missing required positional argument 'net_worth'.") if performance is None: raise ValueError("renderers() is missing required positional argument 'performance'.") if trades is None: raise ValueError("renderers() is missing required positional argument 'trades'.") if not self.fig: self._create_figure(performance.keys()) if self._show_chart: # ensure chart visibility through notebook cell reruns display(self.fig) self.fig.layout.title = self._create_log_entry(episode, max_episodes, step, max_steps) self._price_chart.update(dict( open=price_history['open'], high=price_history['high'], low=price_history['low'], close=price_history['close'] )) self.fig.layout.annotations += self._create_trade_annotations(trades, price_history) self._volume_chart.update({'y': price_history['volume']}) for trace in self.fig.select_traces(row=3): trace.update({'y': performance[trace.name]}) self._net_worth_chart.update({'y': net_worth}) if self._show_chart: self.fig.show() def save(self) -> None: """Saves the current chart to a file. Notes ----- All formats other than HTML require Orca installed and server running. """ if not self._save_format: return else: valid_formats = ['html', 'png', 'jpeg', 'webp', 'svg', 'pdf', 'eps'] _check_valid_format(valid_formats, self._save_format) _check_path(self._path) filename = _create_auto_file_name(self._filename_prefix, self._save_format) filename = os.path.join(self._path, filename) if self._save_format == 'html': self.fig.write_html(file=filename, include_plotlyjs='cdn', auto_open=self._auto_open_html) else: self.fig.write_image(filename) def reset(self) -> None: self._last_trade_step = 0 if self.fig is None: return self.fig.layout.annotations = self._base_annotations clear_output(wait=True) class MatplotlibTradingChart(BaseRenderer): """ Trading visualization for TensorTrade using Matplotlib Parameters --------- display : bool True to display the chart on the screen, False for not. save_format : str A format to save the chart to. Acceptable formats are png, jpg, svg, pdf. path : str The path to save the char to if save_format is not None. The folder will be created if not found. filename_prefix : str A string that precedes automatically-created file name when charts are saved. Default 'chart_'. """ def __init__(self, display: bool = True, save_format: str = None, path: str = 'charts', filename_prefix: str = 'chart_') -> None: super().__init__() self._volume_chart_height = 0.33 self._df = None self.fig = None self._price_ax = None self._volume_ax = None self.net_worth_ax = None self._show_chart = display self._save_format = save_format self._path = path self._filename_prefix = filename_prefix if self._save_format and self._path and not os.path.exists(path): os.mkdir(path) def _create_figure(self) -> None: self.fig = plt.figure() self.net_worth_ax = plt.subplot2grid((6, 1), (0, 0), rowspan=2, colspan=1) self.price_ax = plt.subplot2grid((6, 1), (2, 0), rowspan=8, colspan=1, sharex=self.net_worth_ax) self.volume_ax = self.price_ax.twinx() plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90, wspace=0.2, hspace=0) def _render_trades(self, step_range, trades) -> None: trades = [trade for sublist in trades.values() for trade in sublist] for trade in trades: if trade.step in range(sys.maxsize)[step_range]: date = self._df.index.values[trade.step] close = self._df['close'].values[trade.step] color = 'green' if trade.side is TradeSide.SELL: color = 'red' self.price_ax.annotate(' ', (date, close), xytext=(date, close), size="large", arrowprops=dict(arrowstyle='simple', facecolor=color)) def _render_volume(self, step_range, times) -> None: self.volume_ax.clear() volume = np.array(self._df['volume'].values[step_range]) self.volume_ax.plot(times, volume, color='blue') self.volume_ax.fill_between(times, volume, color='blue', alpha=0.5) self.volume_ax.set_ylim(0, max(volume) / self._volume_chart_height) self.volume_ax.yaxis.set_ticks([]) def _render_price(self, step_range, times, current_step) -> None: self.price_ax.clear() self.price_ax.plot(times, self._df['close'].values[step_range], color="black") last_time = self._df.index.values[current_step] last_close = self._df['close'].values[current_step] last_high = self._df['high'].values[current_step] self.price_ax.annotate('{0:.2f}'.format(last_close), (last_time, last_close), xytext=(last_time, last_high), bbox=dict(boxstyle='round', fc='w', ec='k', lw=1), color="black", fontsize="small") ylim = self.price_ax.get_ylim() self.price_ax.set_ylim(ylim[0] - (ylim[1] - ylim[0]) * self._volume_chart_height, ylim[1]) # def _render_net_worth(self, step_range, times, current_step, net_worths, benchmarks): def _render_net_worth(self, step_range, times, current_step, net_worths) -> None: self.net_worth_ax.clear() self.net_worth_ax.plot(times, net_worths[step_range], label='Net Worth', color="g") self.net_worth_ax.legend() legend = self.net_worth_ax.legend(loc=2, ncol=2, prop={'size': 8}) legend.get_frame().set_alpha(0.4) last_time = times[-1] last_net_worth = list(net_worths[step_range])[-1] self.net_worth_ax.annotate('{0:.2f}'.format(last_net_worth), (last_time, last_net_worth), xytext=(last_time, last_net_worth), bbox=dict(boxstyle='round', fc='w', ec='k', lw=1), color="black", fontsize="small") self.net_worth_ax.set_ylim(min(net_worths) / 1.25, max(net_worths) * 1.25) def render_env(self, episode: int = None, max_episodes: int = None, step: int = None, max_steps: int = None, price_history: 'pd.DataFrame' = None, net_worth: 'pd.Series' = None, performance: 'pd.DataFrame' = None, trades: 'OrderedDict' = None) -> None: if price_history is None: raise ValueError("renderers() is missing required positional argument 'price_history'.") if net_worth is None: raise ValueError("renderers() is missing required positional argument 'net_worth'.") if performance is None: raise ValueError("renderers() is missing required positional argument 'performance'.") if trades is None: raise ValueError("renderers() is missing required positional argument 'trades'.") if not self.fig: self._create_figure() if self._show_chart: plt.show(block=False) current_step = step -1 self._df = price_history if max_steps: window_size=max_steps else: window_size=20 current_net_worth = round(net_worth[len(net_worth)-1], 1) initial_net_worth = round(net_worth[0], 1) profit_percent = round((current_net_worth - initial_net_worth) / initial_net_worth * 100, 2) self.fig.suptitle('Net worth: $' + str(current_net_worth) + ' | Profit: ' + str(profit_percent) + '%') window_start = max(current_step - window_size, 0) step_range = slice(window_start, current_step) times = self._df.index.values[step_range] if len(times) > 0: # self._render_net_worth(step_range, times, current_step, net_worths, benchmarks) self._render_net_worth(step_range, times, current_step, net_worth) self._render_price(step_range, times, current_step) self._render_volume(step_range, times) self._render_trades(step_range, trades) self.price_ax.set_xticklabels(times, rotation=45, horizontalalignment='right') plt.setp(self.net_worth_ax.get_xticklabels(), visible=False) plt.pause(0.001) def save(self) -> None: """Saves the rendering of the `TradingEnv`. """ if not self._save_format: return else: valid_formats = ['png', 'jpeg', 'svg', 'pdf'] _check_valid_format(valid_formats, self._save_format) _check_path(self._path) filename = _create_auto_file_name(self._filename_prefix, self._save_format) filename = os.path.join(self._path, filename) self.fig.savefig(filename, format=self._save_format) def reset(self) -> None: """Resets the renderer. """ self.fig = None self._price_ax = None self._volume_ax = None self.net_worth_ax = None self._df = None _registry = { "screen-log": ScreenLogger, "file-log": FileLogger, "plotly": PlotlyTradingChart, "matplot": MatplotlibTradingChart } def get(identifier: str) -> 'BaseRenderer': """Gets the `BaseRenderer` that matches the identifier. Parameters ---------- identifier : str The identifier for the `BaseRenderer` Returns ------- `BaseRenderer` The renderer associated with the `identifier`. Raises ------ KeyError: Raised if identifier is not associated with any `BaseRenderer` """ if identifier not in _registry.keys(): msg = f"Identifier {identifier} is not associated with any `BaseRenderer`." raise KeyError(msg) return _registry[identifier]()
# Copyright 2020 The TensorTrade Authors. # # 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 import os import sys import logging import importlib from abc import abstractmethod from datetime import datetime from typing import Union, Tuple from collections import OrderedDict import numpy as np import pandas as pd from IPython.display import display, clear_output from pandas.plotting import register_matplotlib_converters from tensortrade.oms.orders import TradeSide from tensortrade.env.generic import Renderer, TradingEnv if importlib.util.find_spec("matplotlib"): import matplotlib.pyplot as plt from matplotlib import style style.use("ggplot") register_matplotlib_converters() if importlib.util.find_spec("plotly"): import plotly.graph_objects as go from plotly.subplots import make_subplots def _create_auto_file_name(filename_prefix: str, ext: str, timestamp_format: str = '%Y%m%d_%H%M%S') -> str: timestamp = datetime.now().strftime(timestamp_format) filename = filename_prefix + timestamp + '.' + ext return filename def _check_path(path: str, auto_create: bool = True) -> None: if not path or os.path.exists(path): return if auto_create: os.mkdir(path) else: raise OSError(f"Path '{path}' not found.") def _check_valid_format(valid_formats: list, save_format: str) -> None: if save_format not in valid_formats: raise ValueError("Acceptable formats are '{}'. Found '{}'".format("', '".join(valid_formats), save_format)) class BaseRenderer(Renderer): """The abstract base renderer to be subclassed when making a renderer the incorporates a `Portfolio`. """ def __init__(self): super().__init__() self._max_episodes = None self._max_steps = None @staticmethod def _create_log_entry(episode: int = None, max_episodes: int = None, step: int = None, max_steps: int = None, date_format: str = "%Y-%m-%d %H:%M:%S %p") -> str: """ Creates a log entry to be used by a renderer. Parameters ---------- episode : int The current episode. max_episodes : int The maximum number of episodes that can occur. step : int The current step of the current episode. max_steps : int The maximum number of steps within an episode that can occur. date_format : str The format for logging the date. Returns ------- str a log entry """ log_entry = f"[{datetime.now().strftime(date_format)}]" if episode is not None: log_entry += f" Episode: {episode + 1}/{max_episodes if max_episodes else ''}" if step is not None: log_entry += f" Step: {step}/{max_steps if max_steps else ''}" return log_entry def render(self, env: 'TradingEnv', **kwargs): price_history = None if len(env.observer.renderer_history) > 0: price_history = pd.DataFrame(env.observer.renderer_history) performance = pd.DataFrame.from_dict(env.action_scheme.portfolio.performance, orient='index') self.render_env( episode=kwargs.get("episode", None), max_episodes=kwargs.get("max_episodes", None), step=env.clock.step, max_steps=kwargs.get("max_steps", None), price_history=price_history, net_worth=performance.net_worth, performance=performance.drop(columns=['base_symbol']), trades=env.action_scheme.broker.trades ) @abstractmethod def render_env(self, episode: int = None, max_episodes: int = None, step: int = None, max_steps: int = None, price_history: 'pd.DataFrame' = None, net_worth: 'pd.Series' = None, performance: 'pd.DataFrame' = None, trades: 'OrderedDict' = None) -> None: """Renderers the current state of the environment. Parameters ---------- episode : int The episode that the environment is being rendered for. max_episodes : int The maximum number of episodes that will occur. step : int The step of the current episode that is happening. max_steps : int The maximum number of steps that will occur in an episode. price_history : `pd.DataFrame` The history of instrument involved with the environment. The required columns are: date, open, high, low, close, and volume. net_worth : `pd.Series` The history of the net worth of the `portfolio`. performance : `pd.Series` The history of performance of the `portfolio`. trades : `OrderedDict` The history of trades for the current episode. """ raise NotImplementedError() def save(self) -> None: """Saves the rendering of the `TradingEnv`. """ pass def reset(self) -> None: """Resets the renderer. """ pass class EmptyRenderer(Renderer): """A renderer that does renders nothing. Needed to make sure that environment can function without requiring a renderer. """ def render(self, env, **kwargs): pass class ScreenLogger(BaseRenderer): """Logs information the screen of the user. Parameters ---------- date_format : str The format for logging the date. """ DEFAULT_FORMAT: str = "[%(asctime)-15s] %(message)s" def __init__(self, date_format: str = "%Y-%m-%d %-I:%M:%S %p"): super().__init__() self._date_format = date_format def render_env(self, episode: int = None, max_episodes: int = None, step: int = None, max_steps: int = None, price_history: pd.DataFrame = None, net_worth: pd.Series = None, performance: pd.DataFrame = None, trades: 'OrderedDict' = None): print(self._create_log_entry(episode, max_episodes, step, max_steps, date_format=self._date_format)) class FileLogger(BaseRenderer): """Logs information to a file. Parameters ---------- filename : str The file name of the log file. If omitted, a file name will be created automatically. path : str The path to save the log files to. None to save to same script directory. log_format : str The log entry format as per Python logging. None for default. For more details, refer to https://docs.python.org/3/library/logging.html timestamp_format : str The format of the timestamp of the log entry. Node for default. """ DEFAULT_LOG_FORMAT: str = '[%(asctime)-15s] %(message)s' DEFAULT_TIMESTAMP_FORMAT: str = '%Y-%m-%d %H:%M:%S' def __init__(self, filename: str = None, path: str = 'log', log_format: str = None, timestamp_format: str = None) -> None: super().__init__() _check_path(path) if not filename: filename = _create_auto_file_name('log_', 'log') self._logger = logging.getLogger(self.id) self._logger.setLevel(logging.INFO) if path: filename = os.path.join(path, filename) handler = logging.FileHandler(filename) handler.setFormatter( logging.Formatter( log_format if log_format is not None else self.DEFAULT_LOG_FORMAT, datefmt=timestamp_format if timestamp_format is not None else self.DEFAULT_TIMESTAMP_FORMAT ) ) self._logger.addHandler(handler) @property def log_file(self) -> str: """The filename information is being logged to. (str, read-only) """ return self._logger.handlers[0].baseFilename def render_env(self, episode: int = None, max_episodes: int = None, step: int = None, max_steps: int = None, price_history: pd.DataFrame = None, net_worth: pd.Series = None, performance: pd.DataFrame = None, trades: 'OrderedDict' = None) -> None: log_entry = self._create_log_entry(episode, max_episodes, step, max_steps) self._logger.info(f"{log_entry} - Performance:\n{performance}") class PlotlyTradingChart(BaseRenderer): """Trading visualization for TensorTrade using Plotly. Parameters ---------- display : bool True to display the chart on the screen, False for not. height : int Chart height in pixels. Affects both display and saved file charts. Set to None for 100% height. Default is None. save_format : str A format to save the chart to. Acceptable formats are html, png, jpeg, webp, svg, pdf, eps. All the formats except for 'html' require Orca. Default is None for no saving. path : str The path to save the char to if save_format is not None. The folder will be created if not found. filename_prefix : str A string that precedes automatically-created file name when charts are saved. Default 'chart_'. timestamp_format : str The format of the date shown in the chart title. auto_open_html : bool Works for save_format='html' only. True to automatically open the saved chart HTML file in the default browser, False otherwise. include_plotlyjs : Union[bool, str] Whether to include/load the plotly.js library in the saved file. 'cdn' results in a smaller file by loading the library online but requires an Internet connect while True includes the library resulting in much larger file sizes. False to not include the library. For more details, refer to https://plot.ly/python-api-reference/generated/plotly.graph_objects.Figure.html Notes ----- Possible Future Enhancements: - Saving images without using Orca. - Limit displayed step range for the case of a large number of steps and let the shown part of the chart slide after filling that range to keep showing recent data as it's being added. References ---------- .. [1] https://plot.ly/python-api-reference/generated/plotly.graph_objects.Figure.html .. [2] https://plot.ly/python/figurewidget/ .. [3] https://plot.ly/python/subplots/ .. [4] https://plot.ly/python/reference/#candlestick .. [5] https://plot.ly/python/#chart-events """ def __init__(self, display: bool = True, height: int = None, timestamp_format: str = '%Y-%m-%d %H:%M:%S', save_format: str = None, path: str = 'charts', filename_prefix: str = 'chart_', auto_open_html: bool = False, include_plotlyjs: Union[bool, str] = 'cdn') -> None: super().__init__() self._height = height self._timestamp_format = timestamp_format self._save_format = save_format self._path = path self._filename_prefix = filename_prefix self._include_plotlyjs = include_plotlyjs self._auto_open_html = auto_open_html if self._save_format and self._path and not os.path.exists(path): os.mkdir(path) self.fig = None self._price_chart = None self._volume_chart = None self._performance_chart = None self._net_worth_chart = None self._base_annotations = None self._last_trade_step = 0 self._show_chart = display def _create_figure(self, performance_keys: dict) -> None: fig = make_subplots( rows=4, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights=[0.55, 0.15, 0.15, 0.15], ) fig.add_trace(go.Candlestick(name='Price', xaxis='x1', yaxis='y1', showlegend=False), row=1, col=1) fig.update_layout(xaxis_rangeslider_visible=False) fig.add_trace(go.Bar(name='Volume', showlegend=False, marker={'color': 'DodgerBlue'}), row=2, col=1) for k in performance_keys: fig.add_trace(go.Scatter(mode='lines', name=k), row=3, col=1) fig.add_trace(go.Scatter(mode='lines', name='Net Worth', marker={'color': 'DarkGreen'}), row=4, col=1) fig.update_xaxes(linecolor='Grey', gridcolor='Gainsboro') fig.update_yaxes(linecolor='Grey', gridcolor='Gainsboro') fig.update_xaxes(title_text='Price', row=1) fig.update_xaxes(title_text='Volume', row=2) fig.update_xaxes(title_text='Performance', row=3) fig.update_xaxes(title_text='Net Worth', row=4) fig.update_xaxes(title_standoff=7, title_font=dict(size=12)) self.fig = go.FigureWidget(fig) self._price_chart = self.fig.data[0] self._volume_chart = self.fig.data[1] self._performance_chart = self.fig.data[2] self._net_worth_chart = self.fig.data[-1] self.fig.update_annotations({'font': {'size': 12}}) self.fig.update_layout(template='plotly_white', height=self._height, margin=dict(t=50)) self._base_annotations = self.fig.layout.annotations def _create_trade_annotations(self, trades: 'OrderedDict', price_history: 'pd.DataFrame') -> 'Tuple[go.layout.Annotation]': """Creates annotations of the new trades after the last one in the chart. Parameters ---------- trades : `OrderedDict` The history of trades for the current episode. price_history : `pd.DataFrame` The price history of the current episode. Returns ------- `Tuple[go.layout.Annotation]` A tuple of annotations used in the renderering process. """ annotations = [] for trade in reversed(trades.values()): trade = trade[0] tp = float(trade.price) ts = float(trade.size) if trade.step <= self._last_trade_step: break if trade.side.value == 'buy': color = 'DarkGreen' ay = 15 qty = round(ts / tp, trade.quote_instrument.precision) text_info = dict( step=trade.step, datetime=price_history.iloc[trade.step - 1]['date'], side=trade.side.value.upper(), qty=qty, size=ts, quote_instrument=trade.quote_instrument, price=tp, base_instrument=trade.base_instrument, type=trade.type.value.upper(), commission=trade.commission ) elif trade.side.value == 'sell': color = 'FireBrick' ay = -15 # qty = round(ts * tp, trade.quote_instrument.precision) text_info = dict( step=trade.step, datetime=price_history.iloc[trade.step - 1]['date'], side=trade.side.value.upper(), qty=ts, size=round(ts * tp, trade.base_instrument.precision), quote_instrument=trade.quote_instrument, price=tp, base_instrument=trade.base_instrument, type=trade.type.value.upper(), commission=trade.commission ) else: raise ValueError(f"Valid trade side values are 'buy' and 'sell'. Found '{trade.side.value}'.") hovertext = 'Step {step} [{datetime}]<br>' \ '{side} {qty} {quote_instrument} @ {price} {base_instrument} {type}<br>' \ 'Total: {size} {base_instrument} - Comm.: {commission}'.format(**text_info) annotations += [go.layout.Annotation( x=trade.step - 1, y=tp, ax=0, ay=ay, xref='x1', yref='y1', showarrow=True, arrowhead=2, arrowcolor=color, arrowwidth=4, arrowsize=0.8, hovertext=hovertext, opacity=0.6, hoverlabel=dict(bgcolor=color) )] if trades: self._last_trade_step = trades[list(trades)[-1]][0].step return tuple(annotations) def render_env(self, episode: int = None, max_episodes: int = None, step: int = None, max_steps: int = None, price_history: pd.DataFrame = None, net_worth: pd.Series = None, performance: pd.DataFrame = None, trades: 'OrderedDict' = None) -> None: if price_history is None: raise ValueError("renderers() is missing required positional argument 'price_history'.") if net_worth is None: raise ValueError("renderers() is missing required positional argument 'net_worth'.") if performance is None: raise ValueError("renderers() is missing required positional argument 'performance'.") if trades is None: raise ValueError("renderers() is missing required positional argument 'trades'.") if not self.fig: self._create_figure(performance.keys()) if self._show_chart: # ensure chart visibility through notebook cell reruns display(self.fig) self.fig.layout.title = self._create_log_entry(episode, max_episodes, step, max_steps) self._price_chart.update(dict( open=price_history['open'], high=price_history['high'], low=price_history['low'], close=price_history['close'] )) self.fig.layout.annotations += self._create_trade_annotations(trades, price_history) self._volume_chart.update({'y': price_history['volume']}) for trace in self.fig.select_traces(row=3): trace.update({'y': performance[trace.name]}) self._net_worth_chart.update({'y': net_worth}) if self._show_chart: self.fig.show() def save(self) -> None: """Saves the current chart to a file. Notes ----- All formats other than HTML require Orca installed and server running. """ if not self._save_format: return else: valid_formats = ['html', 'png', 'jpeg', 'webp', 'svg', 'pdf', 'eps'] _check_valid_format(valid_formats, self._save_format) _check_path(self._path) filename = _create_auto_file_name(self._filename_prefix, self._save_format) filename = os.path.join(self._path, filename) if self._save_format == 'html': self.fig.write_html(file=filename, include_plotlyjs='cdn', auto_open=self._auto_open_html) else: self.fig.write_image(filename) def reset(self) -> None: self._last_trade_step = 0 if self.fig is None: return self.fig.layout.annotations = self._base_annotations clear_output(wait=True) class MatplotlibTradingChart(BaseRenderer): """ Trading visualization for TensorTrade using Matplotlib Parameters --------- display : bool True to display the chart on the screen, False for not. save_format : str A format to save the chart to. Acceptable formats are png, jpg, svg, pdf. path : str The path to save the char to if save_format is not None. The folder will be created if not found. filename_prefix : str A string that precedes automatically-created file name when charts are saved. Default 'chart_'. """ def __init__(self, display: bool = True, save_format: str = None, path: str = 'charts', filename_prefix: str = 'chart_') -> None: super().__init__() self._volume_chart_height = 0.33 self._df = None self.fig = None self._price_ax = None self._volume_ax = None self.net_worth_ax = None self._show_chart = display self._save_format = save_format self._path = path self._filename_prefix = filename_prefix if self._save_format and self._path and not os.path.exists(path): os.mkdir(path) def _create_figure(self) -> None: self.fig = plt.figure() self.net_worth_ax = plt.subplot2grid((6, 1), (0, 0), rowspan=2, colspan=1) self.price_ax = plt.subplot2grid((6, 1), (2, 0), rowspan=8, colspan=1, sharex=self.net_worth_ax) self.volume_ax = self.price_ax.twinx() plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90, wspace=0.2, hspace=0) def _render_trades(self, step_range, trades) -> None: trades = [trade for sublist in trades.values() for trade in sublist] for trade in trades: if trade.step in range(sys.maxsize)[step_range]: date = self._df.index.values[trade.step] close = self._df['close'].values[trade.step] color = 'green' if trade.side is TradeSide.SELL: color = 'red' self.price_ax.annotate(' ', (date, close), xytext=(date, close), size="large", arrowprops=dict(arrowstyle='simple', facecolor=color)) def _render_volume(self, step_range, times) -> None: self.volume_ax.clear() volume = np.array(self._df['volume'].values[step_range]) self.volume_ax.plot(times, volume, color='blue') self.volume_ax.fill_between(times, volume, color='blue', alpha=0.5) self.volume_ax.set_ylim(0, max(volume) / self._volume_chart_height) self.volume_ax.yaxis.set_ticks([]) def _render_price(self, step_range, times, current_step) -> None: self.price_ax.clear() self.price_ax.plot(times, self._df['close'].values[step_range], color="black") last_time = self._df.index.values[current_step] last_close = self._df['close'].values[current_step] last_high = self._df['high'].values[current_step] self.price_ax.annotate('{0:.2f}'.format(last_close), (last_time, last_close), xytext=(last_time, last_high), bbox=dict(boxstyle='round', fc='w', ec='k', lw=1), color="black", fontsize="small") ylim = self.price_ax.get_ylim() self.price_ax.set_ylim(ylim[0] - (ylim[1] - ylim[0]) * self._volume_chart_height, ylim[1]) # def _render_net_worth(self, step_range, times, current_step, net_worths, benchmarks): def _render_net_worth(self, step_range, times, current_step, net_worths) -> None: self.net_worth_ax.clear() self.net_worth_ax.plot(times, net_worths[step_range], label='Net Worth', color="g") self.net_worth_ax.legend() legend = self.net_worth_ax.legend(loc=2, ncol=2, prop={'size': 8}) legend.get_frame().set_alpha(0.4) last_time = times[-1] last_net_worth = list(net_worths[step_range])[-1] self.net_worth_ax.annotate('{0:.2f}'.format(last_net_worth), (last_time, last_net_worth), xytext=(last_time, last_net_worth), bbox=dict(boxstyle='round', fc='w', ec='k', lw=1), color="black", fontsize="small") self.net_worth_ax.set_ylim(min(net_worths) / 1.25, max(net_worths) * 1.25) def render_env(self, episode: int = None, max_episodes: int = None, step: int = None, max_steps: int = None, price_history: 'pd.DataFrame' = None, net_worth: 'pd.Series' = None, performance: 'pd.DataFrame' = None, trades: 'OrderedDict' = None) -> None: if price_history is None: raise ValueError("renderers() is missing required positional argument 'price_history'.") if net_worth is None: raise ValueError("renderers() is missing required positional argument 'net_worth'.") if performance is None: raise ValueError("renderers() is missing required positional argument 'performance'.") if trades is None: raise ValueError("renderers() is missing required positional argument 'trades'.") if not self.fig: self._create_figure() if self._show_chart: plt.show(block=False) current_step = step -1 self._df = price_history if max_steps: window_size=max_steps else: window_size=20 current_net_worth = round(net_worth[len(net_worth)-1], 1) initial_net_worth = round(net_worth[0], 1) profit_percent = round((current_net_worth - initial_net_worth) / initial_net_worth * 100, 2) self.fig.suptitle('Net worth: $' + str(current_net_worth) + ' | Profit: ' + str(profit_percent) + '%') window_start = max(current_step - window_size, 0) step_range = slice(window_start, current_step) times = self._df.index.values[step_range] if len(times) > 0: # self._render_net_worth(step_range, times, current_step, net_worths, benchmarks) self._render_net_worth(step_range, times, current_step, net_worth) self._render_price(step_range, times, current_step) self._render_volume(step_range, times) self._render_trades(step_range, trades) self.price_ax.set_xticklabels(times, rotation=45, horizontalalignment='right') plt.setp(self.net_worth_ax.get_xticklabels(), visible=False) plt.pause(0.001) def save(self) -> None: """Saves the rendering of the `TradingEnv`. """ if not self._save_format: return else: valid_formats = ['png', 'jpeg', 'svg', 'pdf'] _check_valid_format(valid_formats, self._save_format) _check_path(self._path) filename = _create_auto_file_name(self._filename_prefix, self._save_format) filename = os.path.join(self._path, filename) self.fig.savefig(filename, format=self._save_format) def reset(self) -> None: """Resets the renderer. """ self.fig = None self._price_ax = None self._volume_ax = None self.net_worth_ax = None self._df = None _registry = { "screen-log": ScreenLogger, "file-log": FileLogger, "plotly": PlotlyTradingChart, "matplot": MatplotlibTradingChart } def get(identifier: str) -> 'BaseRenderer': """Gets the `BaseRenderer` that matches the identifier. Parameters ---------- identifier : str The identifier for the `BaseRenderer` Returns ------- `BaseRenderer` The renderer associated with the `identifier`. Raises ------ KeyError: Raised if identifier is not associated with any `BaseRenderer` """ if identifier not in _registry.keys(): msg = f"Identifier {identifier} is not associated with any `BaseRenderer`." raise KeyError(msg) return _registry[identifier]()
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.core.goals.package import OutputPathField from pants.engine.target import ( COMMON_TARGET_FIELDS, DictStringToStringField, Sources, SpecialCasedDependencies, StringField, Target, ) from pants.util.docutil import doc_url class DebianControlFile(Sources): required = True expected_num_files = 1 help = ( "Path to a Debian control file for the package to be produced.\n\n" "Paths are relative to the BUILD file's directory." ) class DebianSymlinks(DictStringToStringField): alias = "symlinks" help = ( "Symlinks to create for each target being packaged.\n\n" "For example, you could set symlinks={'command-name': 'entrypoint-name'}." ) class DebianInstallPrefix(StringField): alias = "install_prefix" default = "/opt" help = "Absolute path to a directory where Debian package will be installed to." class DebianPackageDependencies(SpecialCasedDependencies): alias = "packages" required = True help = ( "Addresses to any targets that can be built with `./pants package`, e.g. " '`["project:app"]`.\n\nPants will build the assets as if you had run `./pants package`. ' "It will include the results in your Debian package using the same name they would normally have, " "but without the `--distdir` prefix (e.g. `dist/`).\n\nYou can include anything that can " "be built by `./pants package`, e.g. a `pex_binary`, a `python_distribution`, or an `archive`." ) class DebianPackage(Target): alias = "debian_package" core_fields = ( *COMMON_TARGET_FIELDS, OutputPathField, DebianControlFile, DebianSymlinks, DebianInstallPrefix, DebianPackageDependencies, ) help = ( "A Debian package containing an artifact.\n\n" "This will not install the package, only create a .deb file " "that you can then distribute and install, e.g. via dpkg.\n\n" f"See {doc_url("debian-package")}." )
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.core.goals.package import OutputPathField from pants.engine.target import ( COMMON_TARGET_FIELDS, DictStringToStringField, Sources, SpecialCasedDependencies, StringField, Target, ) from pants.util.docutil import doc_url class DebianControlFile(Sources): required = True expected_num_files = 1 help = ( "Path to a Debian control file for the package to be produced.\n\n" "Paths are relative to the BUILD file's directory." ) class DebianSymlinks(DictStringToStringField): alias = "symlinks" help = ( "Symlinks to create for each target being packaged.\n\n" "For example, you could set symlinks={'command-name': 'entrypoint-name'}." ) class DebianInstallPrefix(StringField): alias = "install_prefix" default = "/opt" help = "Absolute path to a directory where Debian package will be installed to." class DebianPackageDependencies(SpecialCasedDependencies): alias = "packages" required = True help = ( "Addresses to any targets that can be built with `./pants package`, e.g. " '`["project:app"]`.\n\nPants will build the assets as if you had run `./pants package`. ' "It will include the results in your Debian package using the same name they would normally have, " "but without the `--distdir` prefix (e.g. `dist/`).\n\nYou can include anything that can " "be built by `./pants package`, e.g. a `pex_binary`, a `python_distribution`, or an `archive`." ) class DebianPackage(Target): alias = "debian_package" core_fields = ( *COMMON_TARGET_FIELDS, OutputPathField, DebianControlFile, DebianSymlinks, DebianInstallPrefix, DebianPackageDependencies, ) help = ( "A Debian package containing an artifact.\n\n" "This will not install the package, only create a .deb file " "that you can then distribute and install, e.g. via dpkg.\n\n" f"See {doc_url('debian-package')}." )
import asyncio import dataclasses import logging import random import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union import aiosqlite from blspy import AugSchemeMPL import staidelta.server.ws_connection as ws # lgtm [py/import-and-import-from] from staidelta.consensus.block_creation import unfinished_block_to_full_block from staidelta.consensus.block_record import BlockRecord from staidelta.consensus.blockchain import Blockchain, ReceiveBlockResult from staidelta.consensus.blockchain_interface import BlockchainInterface from staidelta.consensus.constants import ConsensusConstants from staidelta.consensus.cost_calculator import NPCResult from staidelta.consensus.difficulty_adjustment import get_next_sub_slot_iters_and_difficulty from staidelta.consensus.make_sub_epoch_summary import next_sub_epoch_summary from staidelta.consensus.multiprocess_validation import PreValidationResult from staidelta.consensus.pot_iterations import calculate_sp_iters from staidelta.full_node.block_store import BlockStore from staidelta.full_node.lock_queue import LockQueue, LockClient from staidelta.full_node.bundle_tools import detect_potential_template_generator from staidelta.full_node.coin_store import CoinStore from staidelta.full_node.full_node_store import FullNodeStore, FullNodeStorePeakResult from staidelta.full_node.hint_store import HintStore from staidelta.full_node.mempool_manager import MempoolManager from staidelta.full_node.signage_point import SignagePoint from staidelta.full_node.sync_store import SyncStore from staidelta.full_node.weight_proof import WeightProofHandler from staidelta.protocols import farmer_protocol, full_node_protocol, timelord_protocol, wallet_protocol from staidelta.protocols.full_node_protocol import ( RequestBlocks, RespondBlock, RespondBlocks, RespondSignagePoint, ) from staidelta.protocols.protocol_message_types import ProtocolMessageTypes from staidelta.protocols.wallet_protocol import CoinState, CoinStateUpdate from staidelta.server.node_discovery import FullNodePeers from staidelta.server.outbound_message import Message, NodeType, make_msg from staidelta.server.server import StaiDeltaServer from staidelta.types.blockchain_format.classgroup import ClassgroupElement from staidelta.types.blockchain_format.pool_target import PoolTarget from staidelta.types.blockchain_format.sized_bytes import bytes32 from staidelta.types.blockchain_format.sub_epoch_summary import SubEpochSummary from staidelta.types.blockchain_format.vdf import CompressibleVDFField, VDFInfo, VDFProof from staidelta.types.coin_record import CoinRecord from staidelta.types.end_of_slot_bundle import EndOfSubSlotBundle from staidelta.types.full_block import FullBlock from staidelta.types.generator_types import BlockGenerator from staidelta.types.header_block import HeaderBlock from staidelta.types.mempool_inclusion_status import MempoolInclusionStatus from staidelta.types.spend_bundle import SpendBundle from staidelta.types.transaction_queue_entry import TransactionQueueEntry from staidelta.types.unfinished_block import UnfinishedBlock from staidelta.util import cached_bls from staidelta.util.bech32m import encode_puzzle_hash from staidelta.util.check_fork_next_block import check_fork_next_block from staidelta.util.condition_tools import pkm_pairs from staidelta.util.db_wrapper import DBWrapper from staidelta.util.errors import ConsensusError, Err, ValidationError from staidelta.util.ints import uint8, uint32, uint64, uint128 from staidelta.util.path import mkdir, path_from_root from staidelta.util.safe_cancel_task import cancel_task_safe from staidelta.util.profiler import profile_task from datetime import datetime from staidelta.util.db_synchronous import db_synchronous_on class FullNode: block_store: BlockStore full_node_store: FullNodeStore full_node_peers: Optional[FullNodePeers] sync_store: Any coin_store: CoinStore mempool_manager: MempoolManager connection: aiosqlite.Connection _sync_task: Optional[asyncio.Task] _init_weight_proof: Optional[asyncio.Task] = None blockchain: Blockchain config: Dict server: Any log: logging.Logger constants: ConsensusConstants _shut_down: bool root_path: Path state_changed_callback: Optional[Callable] timelord_lock: asyncio.Lock initialized: bool weight_proof_handler: Optional[WeightProofHandler] _ui_tasks: Set[asyncio.Task] _blockchain_lock_queue: LockQueue _blockchain_lock_ultra_priority: LockClient _blockchain_lock_high_priority: LockClient _blockchain_lock_low_priority: LockClient def __init__( self, config: Dict, root_path: Path, consensus_constants: ConsensusConstants, name: str = None, ): self.initialized = False self.root_path = root_path self.config = config self.server = None self._shut_down = False # Set to true to close all infinite loops self.constants = consensus_constants self.pow_creation: Dict[uint32, asyncio.Event] = {} self.state_changed_callback: Optional[Callable] = None self.full_node_peers = None self.sync_store = None self.signage_point_times = [time.time() for _ in range(self.constants.NUM_SPS_SUB_SLOT)] self.full_node_store = FullNodeStore(self.constants) self.uncompact_task = None self.compact_vdf_requests: Set[bytes32] = set() self.log = logging.getLogger(name if name else __name__) # Used for metrics self.dropped_tx: Set[bytes32] = set() self.not_dropped_tx = 0 self._ui_tasks = set() db_path_replaced: str = config["database_path"].replace("CHALLENGE", config["selected_network"]) self.db_path = path_from_root(root_path, db_path_replaced) self.coin_subscriptions: Dict[bytes32, Set[bytes32]] = {} # Puzzle Hash : Set[Peer ID] self.ph_subscriptions: Dict[bytes32, Set[bytes32]] = {} # Puzzle Hash : Set[Peer ID] self.peer_coin_ids: Dict[bytes32, Set[bytes32]] = {} # Peer ID: Set[Coin ids] self.peer_puzzle_hash: Dict[bytes32, Set[bytes32]] = {} # Peer ID: Set[puzzle_hash] self.peer_sub_counter: Dict[bytes32, int] = {} # Peer ID: int (subscription count) mkdir(self.db_path.parent) def _set_state_changed_callback(self, callback: Callable): self.state_changed_callback = callback async def _start(self): self.timelord_lock = asyncio.Lock() self.compact_vdf_sem = asyncio.Semaphore(4) # We don't want to run too many concurrent new_peak instances, because it would fetch the same block from # multiple peers and re-validate. self.new_peak_sem = asyncio.Semaphore(2) # These many respond_transaction tasks can be active at any point in time self.respond_transaction_semaphore = asyncio.Semaphore(200) # create the store (db) and full node instance self.connection = await aiosqlite.connect(self.db_path) await self.connection.execute("pragma journal_mode=wal") # Never use pragma synchronous=OFF in StaiDelta. # await self.connection.execute( # "pragma synchronous={}".format(db_synchronous_on(self.config.get("db_sync", "auto"), self.db_path)) # ) if self.config.get("log_sqlite_cmds", False): sql_log_path = path_from_root(self.root_path, "log/sql.log") self.log.info(f"logging SQL commands to {sql_log_path}") def sql_trace_callback(req: str): timestamp = datetime.now().strftime("%H:%M:%S.%f") log = open(sql_log_path, "a") log.write(timestamp + " " + req + "\n") log.close() await self.connection.set_trace_callback(sql_trace_callback) self.db_wrapper = DBWrapper(self.connection) self.block_store = await BlockStore.create(self.db_wrapper) self.sync_store = await SyncStore.create() self.hint_store = await HintStore.create(self.db_wrapper) self.coin_store = await CoinStore.create(self.db_wrapper) self.log.info("Initializing blockchain from disk") start_time = time.time() self.blockchain = await Blockchain.create(self.coin_store, self.block_store, self.constants, self.hint_store) self.mempool_manager = MempoolManager(self.coin_store, self.constants) # Blocks are validated under high priority, and transactions under low priority. This guarantees blocks will # be validated first. self._blockchain_lock_queue = LockQueue(self.blockchain.lock) self._blockchain_lock_ultra_priority = LockClient(0, self._blockchain_lock_queue) self._blockchain_lock_high_priority = LockClient(1, self._blockchain_lock_queue) self._blockchain_lock_low_priority = LockClient(2, self._blockchain_lock_queue) # Transactions go into this queue from the server, and get sent to respond_transaction self.transaction_queue = asyncio.PriorityQueue(10000) self._transaction_queue_task = asyncio.create_task(self._handle_transactions()) self.transaction_responses: List[Tuple[bytes32, MempoolInclusionStatus, Optional[Err]]] = [] self.weight_proof_handler = None self._init_weight_proof = asyncio.create_task(self.initialize_weight_proof()) if self.config.get("enable_profiler", False): asyncio.create_task(profile_task(self.root_path, "node", self.log)) self._sync_task = None self._segment_task = None time_taken = time.time() - start_time if self.blockchain.get_peak() is None: self.log.info(f"Initialized with empty blockchain time taken: {int(time_taken)}s") else: self.log.info( f"Blockchain initialized to peak {self.blockchain.get_peak().header_hash} height" f" {self.blockchain.get_peak().height}, " f"time taken: {int(time_taken)}s" ) async with self._blockchain_lock_high_priority: pending_tx = await self.mempool_manager.new_peak(self.blockchain.get_peak(), []) assert len(pending_tx) == 0 # no pending transactions when starting up peak: Optional[BlockRecord] = self.blockchain.get_peak() if peak is not None: full_peak = await self.blockchain.get_full_peak() mempool_new_peak_result, fns_peak_result = await self.peak_post_processing( full_peak, peak, max(peak.height - 1, 0), None, [] ) await self.peak_post_processing_2( full_peak, peak, max(peak.height - 1, 0), None, ([], {}), mempool_new_peak_result, fns_peak_result ) if self.config["send_uncompact_interval"] != 0: sanitize_weight_proof_only = False if "sanitize_weight_proof_only" in self.config: sanitize_weight_proof_only = self.config["sanitize_weight_proof_only"] assert self.config["target_uncompact_proofs"] != 0 self.uncompact_task = asyncio.create_task( self.broadcast_uncompact_blocks( self.config["send_uncompact_interval"], self.config["target_uncompact_proofs"], sanitize_weight_proof_only, ) ) self.initialized = True if self.full_node_peers is not None: asyncio.create_task(self.full_node_peers.start()) async def _handle_one_transaction(self, entry: TransactionQueueEntry): peer = entry.peer try: inc_status, err = await self.respond_transaction(entry.transaction, entry.spend_name, peer, entry.test) self.transaction_responses.append((entry.spend_name, inc_status, err)) if len(self.transaction_responses) > 50: self.transaction_responses = self.transaction_responses[1:] except asyncio.CancelledError: error_stack = traceback.format_exc() self.log.debug(f"Cancelling _handle_one_transaction, closing: {error_stack}") except Exception: error_stack = traceback.format_exc() self.log.error(f"Error in _handle_one_transaction, closing: {error_stack}") if peer is not None: await peer.close() finally: self.respond_transaction_semaphore.release() async def _handle_transactions(self): try: while not self._shut_down: # We use a semaphore to make sure we don't send more than 200 concurrent calls of respond_transaction. # However doing them one at a time would be slow, because they get sent to other processes. await self.respond_transaction_semaphore.acquire() item: TransactionQueueEntry = (await self.transaction_queue.get())[1] asyncio.create_task(self._handle_one_transaction(item)) except asyncio.CancelledError: raise async def initialize_weight_proof(self): self.weight_proof_handler = WeightProofHandler(self.constants, self.blockchain) peak = self.blockchain.get_peak() if peak is not None: await self.weight_proof_handler.create_sub_epoch_segments() def set_server(self, server: StaiDeltaServer): self.server = server dns_servers = [] try: network_name = self.config["selected_network"] default_port = self.config["network_overrides"]["config"][network_name]["default_full_node_port"] except Exception: self.log.info("Default port field not found in config.") default_port = None if "dns_servers" in self.config: dns_servers = self.config["dns_servers"] elif self.config["port"] == 3100: # If `dns_servers` misses from the `config`, hardcode it if we're running mainnet. dns_servers.append("dns-introducer.staidelta-network.net") try: self.full_node_peers = FullNodePeers( self.server, self.root_path, self.config["target_peer_count"] - self.config["target_outbound_peer_count"], self.config["target_outbound_peer_count"], self.config["peer_db_path"], self.config["introducer_peer"], dns_servers, self.config["peer_connect_interval"], self.config["selected_network"], default_port, self.log, ) except Exception as e: error_stack = traceback.format_exc() self.log.error(f"Exception: {e}") self.log.error(f"Exception in peer discovery: {e}") self.log.error(f"Exception Stack: {error_stack}") def _state_changed(self, change: str): if self.state_changed_callback is not None: self.state_changed_callback(change) async def short_sync_batch(self, peer: ws.WSStaiDeltaConnection, start_height: uint32, target_height: uint32) -> bool: """ Tries to sync to a chain which is not too far in the future, by downloading batches of blocks. If the first block that we download is not connected to our chain, we return False and do an expensive long sync instead. Long sync is not preferred because it requires downloading and validating a weight proof. Args: peer: peer to sync from start_height: height that we should start downloading at. (Our peak is higher) target_height: target to sync to Returns: False if the fork point was not found, and we need to do a long sync. True otherwise. """ # Don't trigger multiple batch syncs to the same peer if ( peer.peer_node_id in self.sync_store.backtrack_syncing and self.sync_store.backtrack_syncing[peer.peer_node_id] > 0 ): return True # Don't batch sync, we are already in progress of a backtrack sync if peer.peer_node_id in self.sync_store.batch_syncing: return True # Don't trigger a long sync self.sync_store.batch_syncing.add(peer.peer_node_id) self.log.info(f"Starting batch short sync from {start_height} to height {target_height}") if start_height > 0: first = await peer.request_block(full_node_protocol.RequestBlock(uint32(start_height), False)) if first is None or not isinstance(first, full_node_protocol.RespondBlock): self.sync_store.batch_syncing.remove(peer.peer_node_id) raise ValueError(f"Error short batch syncing, could not fetch block at height {start_height}") if not self.blockchain.contains_block(first.block.prev_header_hash): self.log.info("Batch syncing stopped, this is a deep chain") self.sync_store.batch_syncing.remove(peer.peer_node_id) # First sb not connected to our blockchain, do a long sync instead return False batch_size = self.constants.MAX_BLOCK_COUNT_PER_REQUESTS if self._segment_task is not None and (not self._segment_task.done()): try: self._segment_task.cancel() except Exception as e: self.log.warning(f"failed to cancel segment task {e}") self._segment_task = None try: for height in range(start_height, target_height, batch_size): end_height = min(target_height, height + batch_size) request = RequestBlocks(uint32(height), uint32(end_height), True) response = await peer.request_blocks(request) if not response: raise ValueError(f"Error short batch syncing, invalid/no response for {height}-{end_height}") async with self._blockchain_lock_high_priority: for block in response.blocks: success, advanced_peak, fork_height, coin_changes = await self.receive_block_batch( [block], peer, None ) if not success: raise ValueError( f"Error short batch syncing, failed to validate blocks {height}-{end_height}" ) if advanced_peak: peak = self.blockchain.get_peak() try: peak_fb: Optional[FullBlock] = await self.blockchain.get_full_peak() assert peak is not None and peak_fb is not None and fork_height is not None mempool_new_peak_result, fns_peak_result = await self.peak_post_processing( peak_fb, peak, fork_height, peer, coin_changes[0] ) await self.peak_post_processing_2( peak_fb, peak, fork_height, peer, coin_changes, mempool_new_peak_result, fns_peak_result, ) except asyncio.CancelledError: # Still do post processing after cancel peak_fb = await self.blockchain.get_full_peak() assert peak is not None and peak_fb is not None and fork_height is not None await self.peak_post_processing(peak_fb, peak, fork_height, peer, coin_changes[0]) raise finally: self.log.info(f"Added blocks {height}-{end_height}") except (asyncio.CancelledError, Exception) as e: self.sync_store.batch_syncing.remove(peer.peer_node_id) raise e self.sync_store.batch_syncing.remove(peer.peer_node_id) return True async def short_sync_backtrack( self, peer: ws.WSStaiDeltaConnection, peak_height: uint32, target_height: uint32, target_unf_hash: bytes32 ): """ Performs a backtrack sync, where blocks are downloaded one at a time from newest to oldest. If we do not find the fork point 5 deeper than our peak, we return False and do a long sync instead. Args: peer: peer to sync from peak_height: height of our peak target_height: target height target_unf_hash: partial hash of the unfinished block of the target Returns: True iff we found the fork point, and we do not need to long sync. """ try: if peer.peer_node_id not in self.sync_store.backtrack_syncing: self.sync_store.backtrack_syncing[peer.peer_node_id] = 0 self.sync_store.backtrack_syncing[peer.peer_node_id] += 1 unfinished_block: Optional[UnfinishedBlock] = self.full_node_store.get_unfinished_block(target_unf_hash) curr_height: int = target_height found_fork_point = False responses = [] while curr_height > peak_height - 5: # If we already have the unfinished block, don't fetch the transactions. In the normal case, we will # already have the unfinished block, from when it was broadcast, so we just need to download the header, # but not the transactions fetch_tx: bool = unfinished_block is None or curr_height != target_height curr = await peer.request_block(full_node_protocol.RequestBlock(uint32(curr_height), fetch_tx)) if curr is None: raise ValueError(f"Failed to fetch block {curr_height} from {peer.get_peer_logging()}, timed out") if curr is None or not isinstance(curr, full_node_protocol.RespondBlock): raise ValueError( f"Failed to fetch block {curr_height} from {peer.get_peer_logging()}, wrong type {type(curr)}" ) responses.append(curr) if self.blockchain.contains_block(curr.block.prev_header_hash) or curr_height == 0: found_fork_point = True break curr_height -= 1 if found_fork_point: for response in reversed(responses): await self.respond_block(response, peer) except (asyncio.CancelledError, Exception) as e: self.sync_store.backtrack_syncing[peer.peer_node_id] -= 1 raise e self.sync_store.backtrack_syncing[peer.peer_node_id] -= 1 return found_fork_point async def _refresh_ui_connections(self, sleep_before: float = 0): if sleep_before > 0: await asyncio.sleep(sleep_before) self._state_changed("peer_changed_peak") async def new_peak(self, request: full_node_protocol.NewPeak, peer: ws.WSStaiDeltaConnection): """ We have received a notification of a new peak from a peer. This happens either when we have just connected, or when the peer has updated their peak. Args: request: information about the new peak peer: peer that sent the message """ try: seen_header_hash = self.sync_store.seen_header_hash(request.header_hash) # Updates heights in the UI. Sleeps 1.5s before, so other peers have time to update their peaks as well. # Limit to 3 refreshes. if not seen_header_hash and len(self._ui_tasks) < 3: self._ui_tasks.add(asyncio.create_task(self._refresh_ui_connections(1.5))) # Prune completed connect tasks self._ui_tasks = set(filter(lambda t: not t.done(), self._ui_tasks)) except Exception as e: self.log.warning(f"Exception UI refresh task: {e}") # Store this peak/peer combination in case we want to sync to it, and to keep track of peers self.sync_store.peer_has_block(request.header_hash, peer.peer_node_id, request.weight, request.height, True) if self.blockchain.contains_block(request.header_hash): return None # Not interested in less heavy peaks peak: Optional[BlockRecord] = self.blockchain.get_peak() curr_peak_height = uint32(0) if peak is None else peak.height if peak is not None and peak.weight > request.weight: return None if self.sync_store.get_sync_mode(): # If peer connects while we are syncing, check if they have the block we are syncing towards peak_sync_hash = self.sync_store.get_sync_target_hash() peak_sync_height = self.sync_store.get_sync_target_height() if peak_sync_hash is not None and request.header_hash != peak_sync_hash and peak_sync_height is not None: peak_peers: Set[bytes32] = self.sync_store.get_peers_that_have_peak([peak_sync_hash]) # Don't ask if we already know this peer has the peak if peer.peer_node_id not in peak_peers: target_peak_response: Optional[RespondBlock] = await peer.request_block( full_node_protocol.RequestBlock(uint32(peak_sync_height), False), timeout=10 ) if target_peak_response is not None and isinstance(target_peak_response, RespondBlock): self.sync_store.peer_has_block( peak_sync_hash, peer.peer_node_id, target_peak_response.block.weight, peak_sync_height, False, ) else: if request.height <= curr_peak_height + self.config["short_sync_blocks_behind_threshold"]: # This is the normal case of receiving the next block if await self.short_sync_backtrack( peer, curr_peak_height, request.height, request.unfinished_reward_block_hash ): return None if request.height < self.constants.WEIGHT_PROOF_RECENT_BLOCKS: # This is the case of syncing up more than a few blocks, at the start of the chain self.log.debug("Doing batch sync, no backup") await self.short_sync_batch(peer, uint32(0), request.height) return None if request.height < curr_peak_height + self.config["sync_blocks_behind_threshold"]: # This case of being behind but not by so much if await self.short_sync_batch(peer, uint32(max(curr_peak_height - 6, 0)), request.height): return None # This is the either the case where we were not able to sync successfully (for example, due to the fork # point being in the past), or we are very far behind. Performs a long sync. self._sync_task = asyncio.create_task(self._sync()) async def send_peak_to_timelords( self, peak_block: Optional[FullBlock] = None, peer: Optional[ws.WSStaiDeltaConnection] = None ): """ Sends current peak to timelords """ if peak_block is None: peak_block = await self.blockchain.get_full_peak() if peak_block is not None: peak = self.blockchain.block_record(peak_block.header_hash) self.log.info(f"send_peak_to_timelords {peak.height} {peak.required_iters}") difficulty = self.blockchain.get_next_difficulty(peak.header_hash, False) difficulty_coeff = await self.blockchain.get_farmer_difficulty_coeff( peak.farmer_public_key, peak.height - 1 if peak.height > 0 else 0 ) ses: Optional[SubEpochSummary] = next_sub_epoch_summary( self.constants, self.blockchain, peak.required_iters, peak_block, True, ) recent_rc = self.blockchain.get_recent_reward_challenges() curr = peak while not curr.is_challenge_block(self.constants) and not curr.first_in_sub_slot: curr = self.blockchain.block_record(curr.prev_hash) if curr.is_challenge_block(self.constants): last_csb_or_eos = curr.total_iters else: last_csb_or_eos = curr.ip_sub_slot_total_iters(self.constants) curr = peak passed_ses_height_but_not_yet_included = True while (curr.height % self.constants.SUB_EPOCH_BLOCKS) != 0: if curr.sub_epoch_summary_included: passed_ses_height_but_not_yet_included = False curr = self.blockchain.block_record(curr.prev_hash) if curr.sub_epoch_summary_included or curr.height == 0: passed_ses_height_but_not_yet_included = False timelord_new_peak: timelord_protocol.NewPeakTimelord = timelord_protocol.NewPeakTimelord( peak_block.reward_chain_block, difficulty, str(difficulty_coeff), peak.deficit, peak.sub_slot_iters, ses, recent_rc, last_csb_or_eos, passed_ses_height_but_not_yet_included, ) msg = make_msg(ProtocolMessageTypes.new_peak_timelord, timelord_new_peak) if peer is None: await self.server.send_to_all([msg], NodeType.TIMELORD) else: await self.server.send_to_specific([msg], peer.peer_node_id) async def synced(self) -> bool: curr: Optional[BlockRecord] = self.blockchain.get_peak() if curr is None: return False while curr is not None and not curr.is_transaction_block: curr = self.blockchain.try_block_record(curr.prev_hash) now = time.time() if ( curr is None or curr.timestamp is None or curr.timestamp < uint64(int(now - 60 * 7)) or self.sync_store.get_sync_mode() ): return False else: return True async def on_connect(self, connection: ws.WSStaiDeltaConnection): """ Whenever we connect to another node / wallet, send them our current heads. Also send heads to farmers and challenges to timelords. """ self._state_changed("add_connection") self._state_changed("sync_mode") if self.full_node_peers is not None: asyncio.create_task(self.full_node_peers.on_connect(connection)) if self.initialized is False: return None if connection.connection_type is NodeType.FULL_NODE: # Send filter to node and request mempool items that are not in it (Only if we are currently synced) synced = await self.synced() peak_height = self.blockchain.get_peak_height() if synced and peak_height is not None: my_filter = self.mempool_manager.get_filter() mempool_request = full_node_protocol.RequestMempoolTransactions(my_filter) msg = make_msg(ProtocolMessageTypes.request_mempool_transactions, mempool_request) await connection.send_message(msg) peak_full: Optional[FullBlock] = await self.blockchain.get_full_peak() if peak_full is not None: peak: BlockRecord = self.blockchain.block_record(peak_full.header_hash) if connection.connection_type is NodeType.FULL_NODE: request_node = full_node_protocol.NewPeak( peak.header_hash, peak.height, peak.weight, peak.height, peak_full.reward_chain_block.get_unfinished().get_hash(), ) await connection.send_message(make_msg(ProtocolMessageTypes.new_peak, request_node)) elif connection.connection_type is NodeType.WALLET: # If connected to a wallet, send the Peak request_wallet = wallet_protocol.NewPeakWallet( peak.header_hash, peak.height, peak.weight, peak.height, ) await connection.send_message(make_msg(ProtocolMessageTypes.new_peak_wallet, request_wallet)) elif connection.connection_type is NodeType.TIMELORD: await self.send_peak_to_timelords() def on_disconnect(self, connection: ws.WSStaiDeltaConnection): self.log.info(f"peer disconnected {connection.get_peer_logging()}") self._state_changed("close_connection") self._state_changed("sync_mode") if self.sync_store is not None: self.sync_store.peer_disconnected(connection.peer_node_id) self.remove_subscriptions(connection) def remove_subscriptions(self, peer: ws.WSStaiDeltaConnection): # Remove all ph | coin id subscription for this peer node_id = peer.peer_node_id if node_id in self.peer_puzzle_hash: puzzle_hashes = self.peer_puzzle_hash[node_id] for ph in puzzle_hashes: if ph in self.ph_subscriptions: if node_id in self.ph_subscriptions[ph]: self.ph_subscriptions[ph].remove(node_id) if node_id in self.peer_coin_ids: coin_ids = self.peer_coin_ids[node_id] for coin_id in coin_ids: if coin_id in self.coin_subscriptions: if node_id in self.coin_subscriptions[coin_id]: self.coin_subscriptions[coin_id].remove(node_id) if peer.peer_node_id in self.peer_sub_counter: self.peer_sub_counter.pop(peer.peer_node_id) def _num_needed_peers(self) -> int: assert self.server is not None assert self.server.all_connections is not None diff = self.config["target_peer_count"] - len(self.server.all_connections) return diff if diff >= 0 else 0 def _close(self): self._shut_down = True if self._init_weight_proof is not None: self._init_weight_proof.cancel() # blockchain is created in _start and in certain cases it may not exist here during _close if hasattr(self, "blockchain"): self.blockchain.shut_down() # same for mempool_manager if hasattr(self, "mempool_manager"): self.mempool_manager.shut_down() if self.full_node_peers is not None: asyncio.create_task(self.full_node_peers.close()) if self.uncompact_task is not None: self.uncompact_task.cancel() self._transaction_queue_task.cancel() self._blockchain_lock_queue.close() async def _await_closed(self): cancel_task_safe(self._sync_task, self.log) for task_id, task in list(self.full_node_store.tx_fetch_tasks.items()): cancel_task_safe(task, self.log) await self.connection.close() if self._init_weight_proof is not None: await asyncio.wait([self._init_weight_proof]) await self._blockchain_lock_queue.await_closed() async def _sync(self): """ Performs a full sync of the blockchain up to the peak. - Wait a few seconds for peers to send us their peaks - Select the heaviest peak, and request a weight proof from a peer with that peak - Validate the weight proof, and disconnect from the peer if invalid - Find the fork point to see where to start downloading blocks - Download blocks in batch (and in parallel) and verify them one at a time - Disconnect peers that provide invalid blocks or don't have the blocks """ if self.weight_proof_handler is None: return None # Ensure we are only syncing once and not double calling this method if self.sync_store.get_sync_mode(): return None if self.sync_store.get_long_sync(): self.log.debug("already in long sync") return None self.sync_store.set_long_sync(True) self.log.debug("long sync started") try: self.log.info("Starting to perform sync.") self.log.info("Waiting to receive peaks from peers.") # Wait until we have 3 peaks or up to a max of 30 seconds peaks = [] for i in range(300): peaks = [tup[0] for tup in self.sync_store.get_peak_of_each_peer().values()] if len(self.sync_store.get_peers_that_have_peak(peaks)) < 3: if self._shut_down: return None await asyncio.sleep(0.1) self.log.info(f"Collected a total of {len(peaks)} peaks.") self.sync_peers_handler = None # Based on responses from peers about the current peaks, see which peak is the heaviest # (similar to longest chain rule). target_peak = self.sync_store.get_heaviest_peak() if target_peak is None: raise RuntimeError("Not performing sync, no peaks collected") heaviest_peak_hash, heaviest_peak_height, heaviest_peak_weight = target_peak self.sync_store.set_peak_target(heaviest_peak_hash, heaviest_peak_height) self.log.info(f"Selected peak {heaviest_peak_height}, {heaviest_peak_hash}") # Check which peers are updated to this height peers = [] coroutines = [] for peer in self.server.all_connections.values(): if peer.connection_type == NodeType.FULL_NODE: peers.append(peer.peer_node_id) coroutines.append( peer.request_block( full_node_protocol.RequestBlock(uint32(heaviest_peak_height), True), timeout=10 ) ) for i, target_peak_response in enumerate(await asyncio.gather(*coroutines)): if target_peak_response is not None and isinstance(target_peak_response, RespondBlock): self.sync_store.peer_has_block( heaviest_peak_hash, peers[i], heaviest_peak_weight, heaviest_peak_height, False ) # TODO: disconnect from peer which gave us the heaviest_peak, if nobody has the peak peer_ids: Set[bytes32] = self.sync_store.get_peers_that_have_peak([heaviest_peak_hash]) peers_with_peak: List = [c for c in self.server.all_connections.values() if c.peer_node_id in peer_ids] # Request weight proof from a random peer self.log.info(f"Total of {len(peers_with_peak)} peers with peak {heaviest_peak_height}") weight_proof_peer = random.choice(peers_with_peak) self.log.info( f"Requesting weight proof from peer {weight_proof_peer.peer_host} up to height" f" {heaviest_peak_height}" ) if self.blockchain.get_peak() is not None and heaviest_peak_weight <= self.blockchain.get_peak().weight: raise ValueError("Not performing sync, already caught up.") wp_timeout = 360 if "weight_proof_timeout" in self.config: wp_timeout = self.config["weight_proof_timeout"] self.log.debug(f"weight proof timeout is {wp_timeout} sec") request = full_node_protocol.RequestProofOfWeight(heaviest_peak_height, heaviest_peak_hash) response = await weight_proof_peer.request_proof_of_weight(request, timeout=wp_timeout) # Disconnect from this peer, because they have not behaved properly if response is None or not isinstance(response, full_node_protocol.RespondProofOfWeight): await weight_proof_peer.close(600) raise RuntimeError(f"Weight proof did not arrive in time from peer: {weight_proof_peer.peer_host}") if response.wp.recent_chain_data[-1].reward_chain_block.height != heaviest_peak_height: await weight_proof_peer.close(600) raise RuntimeError(f"Weight proof had the wrong height: {weight_proof_peer.peer_host}") if response.wp.recent_chain_data[-1].reward_chain_block.weight != heaviest_peak_weight: await weight_proof_peer.close(600) raise RuntimeError(f"Weight proof had the wrong weight: {weight_proof_peer.peer_host}") # dont sync to wp if local peak is heavier, # dont ban peer, we asked for this peak current_peak = self.blockchain.get_peak() if current_peak is not None: if response.wp.recent_chain_data[-1].reward_chain_block.weight <= current_peak.weight: raise RuntimeError(f"current peak is heavier than Weight proof peek: {weight_proof_peer.peer_host}") try: validated, fork_point, summaries = await self.weight_proof_handler.validate_weight_proof(response.wp) except Exception as e: await weight_proof_peer.close(600) raise ValueError(f"Weight proof validation threw an error {e}") if not validated: await weight_proof_peer.close(600) raise ValueError("Weight proof validation failed") self.log.info(f"Re-checked peers: total of {len(peers_with_peak)} peers with peak {heaviest_peak_height}") self.sync_store.set_sync_mode(True) self._state_changed("sync_mode") # Ensures that the fork point does not change async with self._blockchain_lock_high_priority: await self.blockchain.warmup(fork_point) await self.sync_from_fork_point(fork_point, heaviest_peak_height, heaviest_peak_hash, summaries) except asyncio.CancelledError: self.log.warning("Syncing failed, CancelledError") except Exception as e: tb = traceback.format_exc() self.log.error(f"Error with syncing: {type(e)}{tb}") finally: if self._shut_down: return None await self._finish_sync() async def sync_from_fork_point( self, fork_point_height: uint32, target_peak_sb_height: uint32, peak_hash: bytes32, summaries: List[SubEpochSummary], ): buffer_size = 4 self.log.info(f"Start syncing from fork point at {fork_point_height} up to {target_peak_sb_height}") peers_with_peak = self.get_peers_with_peak(peak_hash) fork_point_height = await check_fork_next_block( self.blockchain, fork_point_height, peers_with_peak, node_next_block_check ) batch_size = self.constants.MAX_BLOCK_COUNT_PER_REQUESTS async def fetch_block_batches(batch_queue, peers_with_peak: List[ws.WSStaiDeltaConnection]): try: for start_height in range(fork_point_height, target_peak_sb_height, batch_size): end_height = min(target_peak_sb_height, start_height + batch_size) request = RequestBlocks(uint32(start_height), uint32(end_height), True) fetched = False for peer in random.sample(peers_with_peak, len(peers_with_peak)): if peer.closed: peers_with_peak.remove(peer) continue response = await peer.request_blocks(request, timeout=10) if response is None: await peer.close() peers_with_peak.remove(peer) elif isinstance(response, RespondBlocks): await batch_queue.put((peer, response.blocks)) fetched = True break if fetched is False: self.log.error(f"failed fetching {start_height} to {end_height} from peers") await batch_queue.put(None) return if self.sync_store.peers_changed.is_set(): peers_with_peak = self.get_peers_with_peak(peak_hash) self.sync_store.peers_changed.clear() except Exception as e: self.log.error(f"Exception fetching {start_height} to {end_height} from peer {e}") finally: # finished signal with None await batch_queue.put(None) async def validate_block_batches(batch_queue): advanced_peak = False while True: res = await batch_queue.get() if res is None: self.log.debug("done fetching blocks") return peer, blocks = res start_height = blocks[0].height end_height = blocks[-1].height success, advanced_peak, fork_height, coin_states = await self.receive_block_batch( blocks, peer, None if advanced_peak else uint32(fork_point_height), summaries ) if success is False: if peer in peers_with_peak: peers_with_peak.remove(peer) await peer.close(600) raise ValueError(f"Failed to validate block batch {start_height} to {end_height}") self.log.info(f"Added blocks {start_height} to {end_height}") await self.send_peak_to_wallets() peak = self.blockchain.get_peak() if len(coin_states) > 0 and fork_height is not None: await self.update_wallets(peak.height, fork_height, peak.header_hash, coin_states) self.blockchain.clean_block_record(end_height - self.constants.BLOCKS_CACHE_SIZE) loop = asyncio.get_event_loop() batch_queue: asyncio.Queue[Tuple[ws.WSStaiDeltaConnection, List[FullBlock]]] = asyncio.Queue( loop=loop, maxsize=buffer_size ) fetch_task = asyncio.Task(fetch_block_batches(batch_queue, peers_with_peak)) validate_task = asyncio.Task(validate_block_batches(batch_queue)) try: await asyncio.gather(fetch_task, validate_task) except Exception as e: assert validate_task.done() fetch_task.cancel() # no need to cancel validate_task, if we end up here validate_task is already done self.log.error(f"sync from fork point failed err: {e}") async def send_peak_to_wallets(self): peak = self.blockchain.get_peak() assert peak is not None msg = make_msg( ProtocolMessageTypes.new_peak_wallet, wallet_protocol.NewPeakWallet( peak.header_hash, peak.height, peak.weight, uint32(max(peak.height - 1, uint32(0))) ), ) await self.server.send_to_all([msg], NodeType.WALLET) def get_peers_with_peak(self, peak_hash: bytes32) -> List: peer_ids: Set[bytes32] = self.sync_store.get_peers_that_have_peak([peak_hash]) if len(peer_ids) == 0: self.log.warning(f"Not syncing, no peers with header_hash {peak_hash} ") return [] peers_with_peak: List = [c for c in self.server.all_connections.values() if c.peer_node_id in peer_ids] return peers_with_peak async def update_wallets( self, height: uint32, fork_height: uint32, peak_hash: bytes32, state_update: Tuple[List[CoinRecord], Dict[bytes, Dict[bytes32, CoinRecord]]], ): changes_for_peer: Dict[bytes32, Set[CoinState]] = {} states, hint_state = state_update for coin_record in states: if coin_record.name in self.coin_subscriptions: subscribed_peers = self.coin_subscriptions[coin_record.name] for peer in subscribed_peers: if peer not in changes_for_peer: changes_for_peer[peer] = set() changes_for_peer[peer].add(coin_record.coin_state) if coin_record.coin.puzzle_hash in self.ph_subscriptions: subscribed_peers = self.ph_subscriptions[coin_record.coin.puzzle_hash] for peer in subscribed_peers: if peer not in changes_for_peer: changes_for_peer[peer] = set() changes_for_peer[peer].add(coin_record.coin_state) for hint, records in hint_state.items(): if hint in self.ph_subscriptions: subscribed_peers = self.ph_subscriptions[hint] for peer in subscribed_peers: if peer not in changes_for_peer: changes_for_peer[peer] = set() for record in records.values(): changes_for_peer[peer].add(record.coin_state) for peer, changes in changes_for_peer.items(): if peer not in self.server.all_connections: continue ws_peer: ws.WSStaiDeltaConnection = self.server.all_connections[peer] state = CoinStateUpdate(height, fork_height, peak_hash, list(changes)) msg = make_msg(ProtocolMessageTypes.coin_state_update, state) await ws_peer.send_message(msg) async def receive_block_batch( self, all_blocks: List[FullBlock], peer: ws.WSStaiDeltaConnection, fork_point: Optional[uint32], wp_summaries: Optional[List[SubEpochSummary]] = None, ) -> Tuple[bool, bool, Optional[uint32], Tuple[List[CoinRecord], Dict[bytes, Dict[bytes, CoinRecord]]]]: advanced_peak = False fork_height: Optional[uint32] = uint32(0) blocks_to_validate: List[FullBlock] = [] for i, block in enumerate(all_blocks): if not self.blockchain.contains_block_in_peak_chain(block.header_hash): blocks_to_validate = all_blocks[i:] break if len(blocks_to_validate) == 0: return True, False, fork_height, ([], {}) pre_validate_start = time.time() pre_validation_results: Optional[ List[PreValidationResult] ] = await self.blockchain.pre_validate_blocks_multiprocessing(blocks_to_validate, {}, wp_summaries=wp_summaries) pre_validate_end = time.time() if pre_validate_end - pre_validate_start > 10: self.log.warning(f"Block pre-validation time: {pre_validate_end - pre_validate_start:0.2f} seconds") else: self.log.debug(f"Block pre-validation time: {pre_validate_end - pre_validate_start:0.2f} seconds") if pre_validation_results is None: return False, False, None, ([], {}) for i, block in enumerate(blocks_to_validate): if pre_validation_results[i].error is not None: self.log.error( f"Invalid block from peer: {peer.get_peer_logging()} {Err(pre_validation_results[i].error)}" ) return False, advanced_peak, fork_height, ([], {}) # Dicts because deduping all_coin_changes: Dict[bytes32, CoinRecord] = {} all_hint_changes: Dict[bytes, Dict[bytes32, CoinRecord]] = {} for i, block in enumerate(blocks_to_validate): assert pre_validation_results[i].required_iters is not None result, error, fork_height, coin_changes = await self.blockchain.receive_block( block, pre_validation_results[i], None if advanced_peak else fork_point ) coin_record_list, hint_records = coin_changes # Update all changes for record in coin_record_list: all_coin_changes[record.name] = record for hint, list_of_records in hint_records.items(): if hint not in all_hint_changes: all_hint_changes[hint] = {} for record in list_of_records.values(): all_hint_changes[hint][record.name] = record if result == ReceiveBlockResult.NEW_PEAK: advanced_peak = True elif result == ReceiveBlockResult.INVALID_BLOCK or result == ReceiveBlockResult.DISCONNECTED_BLOCK: if error is not None: self.log.error(f"Error: {error}, Invalid block from peer: {peer.get_peer_logging()} ") return False, advanced_peak, fork_height, ([], {}) block_record = self.blockchain.block_record(block.header_hash) if block_record.sub_epoch_summary_included is not None: if self.weight_proof_handler is not None: await self.weight_proof_handler.create_prev_sub_epoch_segments() if advanced_peak: self._state_changed("new_peak") self.log.debug( f"Total time for {len(blocks_to_validate)} blocks: {time.time() - pre_validate_start}, " f"advanced: {advanced_peak}" ) return True, advanced_peak, fork_height, (list(all_coin_changes.values()), all_hint_changes) async def _finish_sync(self): """ Finalize sync by setting sync mode to False, clearing all sync information, and adding any final blocks that we have finalized recently. """ self.log.info("long sync done") self.sync_store.set_long_sync(False) self.sync_store.set_sync_mode(False) self._state_changed("sync_mode") if self.server is None: return None peak: Optional[BlockRecord] = self.blockchain.get_peak() async with self._blockchain_lock_high_priority: await self.sync_store.clear_sync_info() peak_fb: FullBlock = await self.blockchain.get_full_peak() if peak is not None: mempool_new_peak_result, fns_peak_result = await self.peak_post_processing( peak_fb, peak, max(peak.height - 1, 0), None, [] ) await self.peak_post_processing_2( peak_fb, peak, max(peak.height - 1, 0), None, ([], {}), mempool_new_peak_result, fns_peak_result ) if peak is not None and self.weight_proof_handler is not None: await self.weight_proof_handler.get_proof_of_weight(peak.header_hash) self._state_changed("block") def has_valid_pool_sig(self, block: Union[UnfinishedBlock, FullBlock]): if ( block.foliage.foliage_block_data.pool_target == PoolTarget(self.constants.GENESIS_PRE_FARM_POOL_PUZZLE_HASH, uint32(0)) and block.foliage.prev_block_hash != self.constants.GENESIS_CHALLENGE and block.reward_chain_block.proof_of_space.pool_public_key is not None ): if not AugSchemeMPL.verify( block.reward_chain_block.proof_of_space.pool_public_key, bytes(block.foliage.foliage_block_data.pool_target), block.foliage.foliage_block_data.pool_signature, ): return False return True async def signage_point_post_processing( self, request: full_node_protocol.RespondSignagePoint, peer: ws.WSStaiDeltaConnection, ip_sub_slot: Optional[EndOfSubSlotBundle], ): self.log.info( f"⏲️ Finished signage point {request.index_from_challenge}/" f"{self.constants.NUM_SPS_SUB_SLOT}: " f"CC: {request.challenge_chain_vdf.output.get_hash()} " f"RC: {request.reward_chain_vdf.output.get_hash()} " f"Timelord reward: {bytes(request.timelord_reward_puzzle_hash).hex()} " ) self.signage_point_times[request.index_from_challenge] = time.time() sub_slot_tuple = self.full_node_store.get_sub_slot(request.challenge_chain_vdf.challenge) if sub_slot_tuple is not None: prev_challenge = sub_slot_tuple[0].challenge_chain.challenge_chain_end_of_slot_vdf.challenge else: prev_challenge = None # Notify nodes of the new signage point broadcast = full_node_protocol.NewSignagePointOrEndOfSubSlot( prev_challenge, request.challenge_chain_vdf.challenge, request.index_from_challenge, request.reward_chain_vdf.challenge, request.timelord_reward_puzzle_hash ) msg = make_msg(ProtocolMessageTypes.new_signage_point_or_end_of_sub_slot, broadcast) await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id) peak = self.blockchain.get_peak() if peak is not None and peak.height > self.constants.MAX_SUB_SLOT_BLOCKS: sub_slot_iters = peak.sub_slot_iters difficulty = uint64(peak.weight - self.blockchain.block_record(peak.prev_hash).weight) # Makes sure to potentially update the difficulty if we are past the peak (into a new sub-slot) assert ip_sub_slot is not None if request.challenge_chain_vdf.challenge != ip_sub_slot.challenge_chain.get_hash(): next_difficulty = self.blockchain.get_next_difficulty(peak.header_hash, True) next_sub_slot_iters = self.blockchain.get_next_slot_iters(peak.header_hash, True) difficulty = next_difficulty sub_slot_iters = next_sub_slot_iters else: difficulty = self.constants.DIFFICULTY_STARTING sub_slot_iters = self.constants.SUB_SLOT_ITERS_STARTING # Notify farmers of the new signage point broadcast_farmer = farmer_protocol.NewSignagePoint( request.challenge_chain_vdf.challenge, request.challenge_chain_vdf.output.get_hash(), request.reward_chain_vdf.output.get_hash(), difficulty, sub_slot_iters, request.index_from_challenge, request.timelord_reward_puzzle_hash ) msg = make_msg(ProtocolMessageTypes.new_signage_point, broadcast_farmer) await self.server.send_to_all([msg], NodeType.FARMER) async def peak_post_processing( self, block: FullBlock, record: BlockRecord, fork_height: uint32, peer: Optional[ws.WSStaiDeltaConnection], coin_changes: List[CoinRecord], ): """ Must be called under self.blockchain.lock. This updates the internal state of the full node with the latest peak information. It also notifies peers about the new peak. """ difficulty = self.blockchain.get_next_difficulty(record.header_hash, False) sub_slot_iters = self.blockchain.get_next_slot_iters(record.header_hash, False) self.log.info( f"🌱 Updated peak to height {record.height}, weight {record.weight}, " f"hh {record.header_hash}, " f"forked at {fork_height}, rh: {record.reward_infusion_new_challenge}, " f"total iters: {record.total_iters}, " f"overflow: {record.overflow}, " f"deficit: {record.deficit}, " f"difficulty: {difficulty}, " f"sub slot iters: {sub_slot_iters}, " f"Generator size: " f"{len(bytes(block.transactions_generator)) if block.transactions_generator else "No tx"}, " f"Generator ref list size: " f"{len(block.transactions_generator_ref_list) if block.transactions_generator else "No tx"}" ) sub_slots = await self.blockchain.get_sp_and_ip_sub_slots(record.header_hash) assert sub_slots is not None if not self.sync_store.get_sync_mode(): self.blockchain.clean_block_records() fork_block: Optional[BlockRecord] = None if fork_height != block.height - 1 and block.height != 0: # This is a reorg fork_block = self.blockchain.block_record(self.blockchain.height_to_hash(fork_height)) fns_peak_result: FullNodeStorePeakResult = self.full_node_store.new_peak( record, block, sub_slots[0], sub_slots[1], fork_block, self.blockchain, ) if fns_peak_result.new_signage_points is not None and peer is not None: for index, sp in fns_peak_result.new_signage_points: assert ( sp.cc_vdf is not None and sp.cc_proof is not None and sp.rc_vdf is not None and sp.rc_proof is not None and sp.timelord_reward_puzzle_hash is not None ) await self.signage_point_post_processing( RespondSignagePoint(index, sp.cc_vdf, sp.cc_proof, sp.rc_vdf, sp.rc_proof, sp.timelord_reward_puzzle_hash), peer, sub_slots[1] ) if sub_slots[1] is None: assert record.ip_sub_slot_total_iters(self.constants) == 0 # Ensure the signage point is also in the store, for consistency self.full_node_store.new_signage_point( record.signage_point_index, self.blockchain, record, record.sub_slot_iters, SignagePoint( block.reward_chain_block.challenge_chain_sp_vdf, block.challenge_chain_sp_proof, block.reward_chain_block.reward_chain_sp_vdf, block.reward_chain_sp_proof, block.foliage.foliage_block_data.timelord_reward_puzzle_hash ), skip_vdf_validation=True, ) # Update the mempool (returns successful pending transactions added to the mempool) mempool_new_peak_result: List[Tuple[SpendBundle, NPCResult, bytes32]] = await self.mempool_manager.new_peak( self.blockchain.get_peak(), coin_changes ) # Check if we detected a spent transaction, to load up our generator cache if block.transactions_generator is not None and self.full_node_store.previous_generator is None: generator_arg = detect_potential_template_generator(block.height, block.transactions_generator) if generator_arg: self.log.info(f"Saving previous generator for height {block.height}") self.full_node_store.previous_generator = generator_arg return mempool_new_peak_result, fns_peak_result async def peak_post_processing_2( self, block: FullBlock, record: BlockRecord, fork_height: uint32, peer: Optional[ws.WSStaiDeltaConnection], coin_changes: Tuple[List[CoinRecord], Dict[bytes, Dict[bytes32, CoinRecord]]], mempool_peak_result: List[Tuple[SpendBundle, NPCResult, bytes32]], fns_peak_result: FullNodeStorePeakResult, ): """ Does NOT need to be called under the blockchain lock. Handle other parts of post processing like communicating with peers """ for bundle, result, spend_name in mempool_peak_result: self.log.debug(f"Added transaction to mempool: {spend_name}") mempool_item = self.mempool_manager.get_mempool_item(spend_name) assert mempool_item is not None fees = mempool_item.fee assert fees >= 0 assert mempool_item.cost is not None new_tx = full_node_protocol.NewTransaction( spend_name, mempool_item.cost, uint64(bundle.fees()), ) msg = make_msg(ProtocolMessageTypes.new_transaction, new_tx) await self.server.send_to_all([msg], NodeType.FULL_NODE) timelord_reward_puzzle_hash: bytes32 = self.constants.TIMELORD_PUZZLE_HASH # If there were pending end of slots that happen after this peak, broadcast them if they are added if fns_peak_result.added_eos is not None: broadcast = full_node_protocol.NewSignagePointOrEndOfSubSlot( fns_peak_result.added_eos.challenge_chain.challenge_chain_end_of_slot_vdf.challenge, fns_peak_result.added_eos.challenge_chain.get_hash(), uint8(0), fns_peak_result.added_eos.reward_chain.end_of_slot_vdf.challenge, timelord_reward_puzzle_hash ) msg = make_msg(ProtocolMessageTypes.new_signage_point_or_end_of_sub_slot, broadcast) await self.server.send_to_all([msg], NodeType.FULL_NODE) # TODO: maybe add and broadcast new IPs as well if record.height % 1000 == 0: # Occasionally clear data in full node store to keep memory usage small self.full_node_store.clear_seen_unfinished_blocks() self.full_node_store.clear_old_cache_entries() if self.sync_store.get_sync_mode() is False: await self.send_peak_to_timelords(block) # Tell full nodes about the new peak msg = make_msg( ProtocolMessageTypes.new_peak, full_node_protocol.NewPeak( record.header_hash, record.height, record.weight, fork_height, block.reward_chain_block.get_unfinished().get_hash(), ), ) if peer is not None: await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id) else: await self.server.send_to_all([msg], NodeType.FULL_NODE) # Tell wallets about the new peak msg = make_msg( ProtocolMessageTypes.new_peak_wallet, wallet_protocol.NewPeakWallet( record.header_hash, record.height, record.weight, fork_height, ), ) await self.update_wallets(record.height, fork_height, record.header_hash, coin_changes) await self.server.send_to_all([msg], NodeType.WALLET) self._state_changed("new_peak") async def respond_block( self, respond_block: full_node_protocol.RespondBlock, peer: Optional[ws.WSStaiDeltaConnection] = None, ) -> Optional[Message]: """ Receive a full block from a peer full node (or ourselves). """ block: FullBlock = respond_block.block if self.sync_store.get_sync_mode(): return None # Adds the block to seen, and check if it's seen before (which means header is in memory) header_hash = block.header_hash if self.blockchain.contains_block(header_hash): return None pre_validation_result: Optional[PreValidationResult] = None if ( block.is_transaction_block() and block.transactions_info is not None and block.transactions_info.generator_root != bytes([0] * 32) and block.transactions_generator is None ): # This is the case where we already had the unfinished block, and asked for this block without # the transactions (since we already had them). Therefore, here we add the transactions. unfinished_rh: bytes32 = block.reward_chain_block.get_unfinished().get_hash() unf_block: Optional[UnfinishedBlock] = self.full_node_store.get_unfinished_block(unfinished_rh) if ( unf_block is not None and unf_block.transactions_generator is not None and unf_block.foliage_transaction_block == block.foliage_transaction_block ): pre_validation_result = self.full_node_store.get_unfinished_block_result(unfinished_rh) assert pre_validation_result is not None block = dataclasses.replace( block, transactions_generator=unf_block.transactions_generator, transactions_generator_ref_list=unf_block.transactions_generator_ref_list, ) else: # We still do not have the correct information for this block, perhaps there is a duplicate block # with the same unfinished block hash in the cache, so we need to fetch the correct one if peer is None: return None block_response: Optional[Any] = await peer.request_block( full_node_protocol.RequestBlock(block.height, True) ) if block_response is None or not isinstance(block_response, full_node_protocol.RespondBlock): self.log.warning( f"Was not able to fetch the correct block for height {block.height} {block_response}" ) return None new_block: FullBlock = block_response.block if new_block.foliage_transaction_block != block.foliage_transaction_block: self.log.warning(f"Received the wrong block for height {block.height} {new_block.header_hash}") return None assert new_block.transactions_generator is not None self.log.debug( f"Wrong info in the cache for bh {new_block.header_hash}, there might be multiple blocks from the " f"same farmer with the same pospace." ) # This recursion ends here, we cannot recurse again because transactions_generator is not None return await self.respond_block(block_response, peer) coin_changes: Tuple[List[CoinRecord], Dict[bytes, Dict[bytes32, CoinRecord]]] = ([], {}) mempool_new_peak_result, fns_peak_result = None, None async with self._blockchain_lock_high_priority: # After acquiring the lock, check again, because another asyncio thread might have added it if self.blockchain.contains_block(header_hash): return None validation_start = time.time() # Tries to add the block to the blockchain, if we already validated transactions, don't do it again npc_results = {} if pre_validation_result is not None and pre_validation_result.npc_result is not None: npc_results[block.height] = pre_validation_result.npc_result pre_validation_results = await self.blockchain.pre_validate_blocks_multiprocessing([block], npc_results) added: Optional[ReceiveBlockResult] = None pre_validation_time = time.time() - validation_start try: if pre_validation_results is None: raise ValueError(f"Failed to validate block {header_hash} height {block.height}") if pre_validation_results[0].error is not None: if Err(pre_validation_results[0].error) == Err.INVALID_PREV_BLOCK_HASH: added = ReceiveBlockResult.DISCONNECTED_BLOCK error_code: Optional[Err] = Err.INVALID_PREV_BLOCK_HASH fork_height: Optional[uint32] = None else: raise ValueError( f"Failed to validate block {header_hash} height " f"{block.height}: {Err(pre_validation_results[0].error).name}" ) else: result_to_validate = ( pre_validation_results[0] if pre_validation_result is None else pre_validation_result ) assert result_to_validate.required_iters == pre_validation_results[0].required_iters added, error_code, fork_height, coin_changes = await self.blockchain.receive_block( block, result_to_validate, None ) if ( self.full_node_store.previous_generator is not None and fork_height is not None and fork_height < self.full_node_store.previous_generator.block_height ): self.full_node_store.previous_generator = None if added == ReceiveBlockResult.ALREADY_HAVE_BLOCK: return None elif added == ReceiveBlockResult.INVALID_BLOCK: assert error_code is not None self.log.error(f"Block {header_hash} at height {block.height} is invalid with code {error_code}.") raise ConsensusError(error_code, header_hash) elif added == ReceiveBlockResult.DISCONNECTED_BLOCK: self.log.info(f"Disconnected block {header_hash} at height {block.height}") return None elif added == ReceiveBlockResult.NEW_PEAK: # Only propagate blocks which extend the blockchain (becomes one of the heads) new_peak: Optional[BlockRecord] = self.blockchain.get_peak() assert new_peak is not None and fork_height is not None mempool_new_peak_result, fns_peak_result = await self.peak_post_processing( block, new_peak, fork_height, peer, coin_changes[0] ) elif added == ReceiveBlockResult.ADDED_AS_ORPHAN: self.log.info( f"Received orphan block of height {block.height} rh " f"{block.reward_chain_block.get_hash()}" ) else: # Should never reach here, all the cases are covered raise RuntimeError(f"Invalid result from receive_block {added}") except asyncio.CancelledError: # We need to make sure to always call this method even when we get a cancel exception, to make sure # the node stays in sync new_peak = self.blockchain.get_peak() if added == ReceiveBlockResult.NEW_PEAK: assert new_peak is not None assert fork_height is not None await self.peak_post_processing(block, new_peak, fork_height, peer, coin_changes[0]) raise validation_time = time.time() - validation_start if mempool_new_peak_result is not None: assert new_peak is not None assert fork_height is not None assert fns_peak_result is not None await self.peak_post_processing_2( block, new_peak, fork_height, peer, coin_changes, mempool_new_peak_result, fns_peak_result ) percent_full_str = ( ( ", percent full: " + str(round(100.0 * float(block.transactions_info.cost) / self.constants.MAX_BLOCK_COST_CLVM, 3)) + "%" ) if block.transactions_info is not None else "" ) self.log.log( logging.WARNING if validation_time > 2 else logging.DEBUG, f"Block validation time: {validation_time:0.2f} seconds, " f"pre_validation time: {pre_validation_time:0.2f} seconds, " f"cost: {block.transactions_info.cost if block.transactions_info is not None else "None"}" f"{percent_full_str}", ) # This code path is reached if added == ADDED_AS_ORPHAN or NEW_TIP peak = self.blockchain.get_peak() assert peak is not None # Removes all temporary data for old blocks clear_height = uint32(max(0, peak.height - 50)) self.full_node_store.clear_candidate_blocks_below(clear_height) self.full_node_store.clear_unfinished_blocks_below(clear_height) if peak.height % 1000 == 0 and not self.sync_store.get_sync_mode(): await self.sync_store.clear_sync_info() # Occasionally clear sync peer info self._state_changed("block") record = self.blockchain.block_record(block.header_hash) if self.weight_proof_handler is not None and record.sub_epoch_summary_included is not None: if self._segment_task is None or self._segment_task.done(): self._segment_task = asyncio.create_task(self.weight_proof_handler.create_prev_sub_epoch_segments()) return None async def respond_unfinished_block( self, respond_unfinished_block: full_node_protocol.RespondUnfinishedBlock, peer: Optional[ws.WSStaiDeltaConnection], farmed_block: bool = False, block_bytes: Optional[bytes] = None, ): """ We have received an unfinished block, either created by us, or from another peer. We can validate it and if it's a good block, propagate it to other peers and timelords. """ block = respond_unfinished_block.unfinished_block receive_time = time.time() if block.prev_header_hash != self.constants.GENESIS_CHALLENGE and not self.blockchain.contains_block( block.prev_header_hash ): # No need to request the parent, since the peer will send it to us anyway, via NewPeak self.log.debug("Received a disconnected unfinished block") return None # Adds the unfinished block to seen, and check if it's seen before, to prevent # processing it twice. This searches for the exact version of the unfinished block (there can be many different # foliages for the same trunk). This is intentional, to prevent DOS attacks. # Note that it does not require that this block was successfully processed if self.full_node_store.seen_unfinished_block(block.get_hash()): return None block_hash = block.reward_chain_block.get_hash() # This searched for the trunk hash (unfinished reward hash). If we have already added a block with the same # hash, return if self.full_node_store.get_unfinished_block(block_hash) is not None: return None peak: Optional[BlockRecord] = self.blockchain.get_peak() if peak is not None: if block.total_iters < peak.sp_total_iters(self.constants): # This means this unfinished block is pretty far behind, it will not add weight to our chain return None if block.prev_header_hash == self.constants.GENESIS_CHALLENGE: prev_b = None else: prev_b = self.blockchain.block_record(block.prev_header_hash) # Count the blocks in sub slot, and check if it's a new epoch if len(block.finished_sub_slots) > 0: num_blocks_in_ss = 1 # Curr else: curr = self.blockchain.try_block_record(block.prev_header_hash) num_blocks_in_ss = 2 # Curr and prev while (curr is not None) and not curr.first_in_sub_slot: curr = self.blockchain.try_block_record(curr.prev_hash) num_blocks_in_ss += 1 if num_blocks_in_ss > self.constants.MAX_SUB_SLOT_BLOCKS: # TODO: potentially allow overflow blocks here, which count for the next slot self.log.warning("Too many blocks added, not adding block") return None # The clvm generator and aggregate signature are validated outside of the lock, to allow other blocks and # transactions to get validated npc_result: Optional[NPCResult] = None pre_validation_time = None if block.transactions_generator is not None: pre_validation_start = time.time() assert block.transactions_info is not None try: block_generator: Optional[BlockGenerator] = await self.blockchain.get_block_generator(block) except ValueError: raise ConsensusError(Err.GENERATOR_REF_HAS_NO_GENERATOR) if block_generator is None: raise ConsensusError(Err.GENERATOR_REF_HAS_NO_GENERATOR) if block_bytes is None: block_bytes = bytes(block) npc_result = await self.blockchain.run_generator(block_bytes, block_generator) pre_validation_time = time.time() - pre_validation_start pairs_pks, pairs_msgs = pkm_pairs(npc_result.npc_list, self.constants.AGG_SIG_ME_ADDITIONAL_DATA) if not cached_bls.aggregate_verify( pairs_pks, pairs_msgs, block.transactions_info.aggregated_signature, True ): raise ConsensusError(Err.BAD_AGGREGATE_SIGNATURE) async with self._blockchain_lock_high_priority: # TODO: pre-validate VDFs outside of lock validation_start = time.time() validate_result = await self.blockchain.validate_unfinished_block(block, npc_result) if validate_result.error is not None: if validate_result.error == Err.COIN_AMOUNT_NEGATIVE.value: # TODO: remove in the future, hotfix for 1.1.5 peers to not disconnect older peers self.log.info(f"Consensus error {validate_result.error}, not disconnecting") return raise ConsensusError(Err(validate_result.error)) validation_time = time.time() - validation_start assert validate_result.required_iters is not None # Perform another check, in case we have already concurrently added the same unfinished block if self.full_node_store.get_unfinished_block(block_hash) is not None: return None if block.prev_header_hash == self.constants.GENESIS_CHALLENGE: height = uint32(0) else: height = uint32(self.blockchain.block_record(block.prev_header_hash).height + 1) ses: Optional[SubEpochSummary] = next_sub_epoch_summary( self.constants, self.blockchain, validate_result.required_iters, block, True, ) self.full_node_store.add_unfinished_block(height, block, validate_result) pre_validation_log = ( f"pre_validation time {pre_validation_time:0.4f}, " if pre_validation_time is not None else "" ) if farmed_block is True: self.log.info( f"🍀 ️Farmed unfinished_block {block_hash}, SP: {block.reward_chain_block.signage_point_index}, " f"validation time: {validation_time:0.4f} seconds, {pre_validation_log}" f"cost: {block.transactions_info.cost if block.transactions_info else "None"} " ) else: percent_full_str = ( ( ", percent full: " + str(round(100.0 * float(block.transactions_info.cost) / self.constants.MAX_BLOCK_COST_CLVM, 3)) + "%" ) if block.transactions_info is not None else "" ) self.log.info( f"Added unfinished_block {block_hash}, not farmed by us," f" SP: {block.reward_chain_block.signage_point_index} farmer response time: " f"{receive_time - self.signage_point_times[block.reward_chain_block.signage_point_index]:0.4f}, " f"Pool pk {encode_puzzle_hash(block.foliage.foliage_block_data.pool_target.puzzle_hash, "staidelta")}, " f"validation time: {validation_time:0.4f} seconds, {pre_validation_log}" f"cost: {block.transactions_info.cost if block.transactions_info else "None"}" f"{percent_full_str}" ) sub_slot_iters, difficulty = get_next_sub_slot_iters_and_difficulty( self.constants, len(block.finished_sub_slots) > 0, prev_b, self.blockchain, ) if block.reward_chain_block.signage_point_index == 0: res = self.full_node_store.get_sub_slot(block.reward_chain_block.pos_ss_cc_challenge_hash) if res is None: if block.reward_chain_block.pos_ss_cc_challenge_hash == self.constants.GENESIS_CHALLENGE: rc_prev = self.constants.GENESIS_CHALLENGE else: self.log.warning(f"Do not have sub slot {block.reward_chain_block.pos_ss_cc_challenge_hash}") return None else: rc_prev = res[0].reward_chain.get_hash() else: assert block.reward_chain_block.reward_chain_sp_vdf is not None rc_prev = block.reward_chain_block.reward_chain_sp_vdf.challenge timelord_request = timelord_protocol.NewUnfinishedBlockTimelord( block.reward_chain_block, difficulty, sub_slot_iters, block.foliage, ses, rc_prev, validate_result.difficulty_coeff, ) timelord_msg = make_msg(ProtocolMessageTypes.new_unfinished_block_timelord, timelord_request) await self.server.send_to_all([timelord_msg], NodeType.TIMELORD) full_node_request = full_node_protocol.NewUnfinishedBlock(block.reward_chain_block.get_hash()) msg = make_msg(ProtocolMessageTypes.new_unfinished_block, full_node_request) if peer is not None: await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id) else: await self.server.send_to_all([msg], NodeType.FULL_NODE) self._state_changed("unfinished_block") async def new_infusion_point_vdf( self, request: timelord_protocol.NewInfusionPointVDF, timelord_peer: Optional[ws.WSStaiDeltaConnection] = None ) -> Optional[Message]: # Lookup unfinished blocks unfinished_block: Optional[UnfinishedBlock] = self.full_node_store.get_unfinished_block( request.unfinished_reward_hash ) if unfinished_block is None: self.log.warning( f"Do not have unfinished reward chain block {request.unfinished_reward_hash}, cannot finish." ) return None prev_b: Optional[BlockRecord] = None target_rc_hash = request.reward_chain_ip_vdf.challenge last_slot_cc_hash = request.challenge_chain_ip_vdf.challenge # Backtracks through end of slot objects, should work for multiple empty sub slots for eos, _, _ in reversed(self.full_node_store.finished_sub_slots): if eos is not None and eos.reward_chain.get_hash() == target_rc_hash: target_rc_hash = eos.reward_chain.end_of_slot_vdf.challenge if target_rc_hash == self.constants.GENESIS_CHALLENGE: prev_b = None else: # Find the prev block, starts looking backwards from the peak. target_rc_hash must be the hash of a block # and not an end of slot (since we just looked through the slots and backtracked) curr: Optional[BlockRecord] = self.blockchain.get_peak() for _ in range(10): if curr is None: break if curr.reward_infusion_new_challenge == target_rc_hash: # Found our prev block prev_b = curr break curr = self.blockchain.try_block_record(curr.prev_hash) # If not found, cache keyed on prev block if prev_b is None: self.full_node_store.add_to_future_ip(request) self.log.warning(f"Previous block is None, infusion point {request.reward_chain_ip_vdf.challenge}") return None finished_sub_slots: Optional[List[EndOfSubSlotBundle]] = self.full_node_store.get_finished_sub_slots( self.blockchain, prev_b, last_slot_cc_hash, ) if finished_sub_slots is None: return None sub_slot_iters, difficulty = get_next_sub_slot_iters_and_difficulty( self.constants, len(finished_sub_slots) > 0, prev_b, self.blockchain, ) if unfinished_block.reward_chain_block.pos_ss_cc_challenge_hash == self.constants.GENESIS_CHALLENGE: sub_slot_start_iters = uint128(0) else: ss_res = self.full_node_store.get_sub_slot(unfinished_block.reward_chain_block.pos_ss_cc_challenge_hash) if ss_res is None: self.log.warning(f"Do not have sub slot {unfinished_block.reward_chain_block.pos_ss_cc_challenge_hash}") return None _, _, sub_slot_start_iters = ss_res sp_total_iters = uint128( sub_slot_start_iters + calculate_sp_iters( self.constants, sub_slot_iters, unfinished_block.reward_chain_block.signage_point_index, ) ) block: FullBlock = unfinished_block_to_full_block( unfinished_block, request.challenge_chain_ip_vdf, request.challenge_chain_ip_proof, request.reward_chain_ip_vdf, request.reward_chain_ip_proof, request.infused_challenge_chain_ip_vdf, request.infused_challenge_chain_ip_proof, finished_sub_slots, prev_b, self.blockchain, sp_total_iters, difficulty, ) if not self.has_valid_pool_sig(block): self.log.warning("Trying to make a pre-farm block but height is not 0") return None try: await self.respond_block(full_node_protocol.RespondBlock(block)) except Exception as e: self.log.warning(f"Consensus error validating block: {e}") if timelord_peer is not None: # Only sends to the timelord who sent us this VDF, to reset them to the correct peak await self.send_peak_to_timelords(peer=timelord_peer) return None async def respond_end_of_sub_slot( self, request: full_node_protocol.RespondEndOfSubSlot, peer: ws.WSStaiDeltaConnection ) -> Tuple[Optional[Message], bool]: fetched_ss = self.full_node_store.get_sub_slot(request.end_of_slot_bundle.challenge_chain.get_hash()) # We are not interested in sub-slots which have the same challenge chain but different reward chain. If there # is a reorg, we will find out through the broadcast of blocks instead. if fetched_ss is not None: # Already have the sub-slot return None, True async with self.timelord_lock: fetched_ss = self.full_node_store.get_sub_slot( request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge ) if ( (fetched_ss is None) and request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge != self.constants.GENESIS_CHALLENGE ): # If we don't have the prev, request the prev instead full_node_request = full_node_protocol.RequestSignagePointOrEndOfSubSlot( request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge, uint8(0), bytes([0] * 32), ) return ( make_msg(ProtocolMessageTypes.request_signage_point_or_end_of_sub_slot, full_node_request), False, ) timelord_reward_puzzle_hash: bytes32 = self.constants.TIMELORD_PUZZLE_HASH peak = self.blockchain.get_peak() if peak is not None and peak.height > 2: next_sub_slot_iters = self.blockchain.get_next_slot_iters(peak.header_hash, True) next_difficulty = self.blockchain.get_next_difficulty(peak.header_hash, True) timelord_reward_puzzle_hash = peak.timelord_puzzle_hash else: next_sub_slot_iters = self.constants.SUB_SLOT_ITERS_STARTING next_difficulty = self.constants.DIFFICULTY_STARTING # Adds the sub slot and potentially get new infusions new_infusions = self.full_node_store.new_finished_sub_slot( request.end_of_slot_bundle, self.blockchain, peak, await self.blockchain.get_full_peak(), ) # It may be an empty list, even if it's not None. Not None means added successfully if new_infusions is not None: self.log.info( f"⏲️ Finished sub slot, SP {self.constants.NUM_SPS_SUB_SLOT}/{self.constants.NUM_SPS_SUB_SLOT}, " f"{request.end_of_slot_bundle.challenge_chain.get_hash()}, " f"number of sub-slots: {len(self.full_node_store.finished_sub_slots)}, " f"RC hash: {request.end_of_slot_bundle.reward_chain.get_hash()}, " f"Deficit {request.end_of_slot_bundle.reward_chain.deficit}" f"Timelord reward {timelord_reward_puzzle_hash}" ) # Notify full nodes of the new sub-slot broadcast = full_node_protocol.NewSignagePointOrEndOfSubSlot( request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge, request.end_of_slot_bundle.challenge_chain.get_hash(), uint8(0), request.end_of_slot_bundle.reward_chain.end_of_slot_vdf.challenge, timelord_reward_puzzle_hash ) msg = make_msg(ProtocolMessageTypes.new_signage_point_or_end_of_sub_slot, broadcast) await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id) for infusion in new_infusions: await self.new_infusion_point_vdf(infusion) # Notify farmers of the new sub-slot broadcast_farmer = farmer_protocol.NewSignagePoint( request.end_of_slot_bundle.challenge_chain.get_hash(), request.end_of_slot_bundle.challenge_chain.get_hash(), request.end_of_slot_bundle.reward_chain.get_hash(), next_difficulty, next_sub_slot_iters, uint8(0), timelord_reward_puzzle_hash ) msg = make_msg(ProtocolMessageTypes.new_signage_point, broadcast_farmer) await self.server.send_to_all([msg], NodeType.FARMER) return None, True else: self.log.info( f"End of slot not added CC challenge " f"{request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge}" ) return None, False async def respond_transaction( self, transaction: SpendBundle, spend_name: bytes32, peer: Optional[ws.WSStaiDeltaConnection] = None, test: bool = False, tx_bytes: Optional[bytes] = None, ) -> Tuple[MempoolInclusionStatus, Optional[Err]]: if self.sync_store.get_sync_mode(): return MempoolInclusionStatus.FAILED, Err.NO_TRANSACTIONS_WHILE_SYNCING if not test and not (await self.synced()): return MempoolInclusionStatus.FAILED, Err.NO_TRANSACTIONS_WHILE_SYNCING if self.mempool_manager.seen(spend_name): return MempoolInclusionStatus.FAILED, Err.ALREADY_INCLUDING_TRANSACTION self.mempool_manager.add_and_maybe_pop_seen(spend_name) self.log.debug(f"Processing transaction: {spend_name}") # Ignore if syncing if self.sync_store.get_sync_mode(): status = MempoolInclusionStatus.FAILED error: Optional[Err] = Err.NO_TRANSACTIONS_WHILE_SYNCING self.mempool_manager.remove_seen(spend_name) else: try: cost_result = await self.mempool_manager.pre_validate_spendbundle(transaction, tx_bytes, spend_name) except ValidationError as e: self.mempool_manager.remove_seen(spend_name) return MempoolInclusionStatus.FAILED, e.code except Exception as e: self.mempool_manager.remove_seen(spend_name) raise e async with self._blockchain_lock_low_priority: if self.mempool_manager.get_spendbundle(spend_name) is not None: self.mempool_manager.remove_seen(spend_name) return MempoolInclusionStatus.FAILED, Err.ALREADY_INCLUDING_TRANSACTION cost, status, error = await self.mempool_manager.add_spendbundle(transaction, cost_result, spend_name) if status == MempoolInclusionStatus.SUCCESS: self.log.debug( f"Added transaction to mempool: {spend_name} mempool size: " f"{self.mempool_manager.mempool.total_mempool_cost} normalized " f"{self.mempool_manager.mempool.total_mempool_cost / 5000000}" ) # Only broadcast successful transactions, not pending ones. Otherwise it's a DOS # vector. mempool_item = self.mempool_manager.get_mempool_item(spend_name) assert mempool_item is not None fees = mempool_item.fee assert fees >= 0 assert cost is not None new_tx = full_node_protocol.NewTransaction( spend_name, cost, fees, ) msg = make_msg(ProtocolMessageTypes.new_transaction, new_tx) if peer is None: await self.server.send_to_all([msg], NodeType.FULL_NODE) else: await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id) self.not_dropped_tx += 1 else: self.mempool_manager.remove_seen(spend_name) self.log.debug( f"Wasn't able to add transaction with id {spend_name}, " f"status {status} error: {error}" ) return status, error async def _needs_compact_proof( self, vdf_info: VDFInfo, header_block: HeaderBlock, field_vdf: CompressibleVDFField ) -> bool: if field_vdf == CompressibleVDFField.CC_EOS_VDF: for sub_slot in header_block.finished_sub_slots: if sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf == vdf_info: if ( sub_slot.proofs.challenge_chain_slot_proof.witness_type == 0 and sub_slot.proofs.challenge_chain_slot_proof.normalized_to_identity ): return False return True if field_vdf == CompressibleVDFField.ICC_EOS_VDF: for sub_slot in header_block.finished_sub_slots: if ( sub_slot.infused_challenge_chain is not None and sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf == vdf_info ): assert sub_slot.proofs.infused_challenge_chain_slot_proof is not None if ( sub_slot.proofs.infused_challenge_chain_slot_proof.witness_type == 0 and sub_slot.proofs.infused_challenge_chain_slot_proof.normalized_to_identity ): return False return True if field_vdf == CompressibleVDFField.CC_SP_VDF: if header_block.reward_chain_block.challenge_chain_sp_vdf is None: return False if vdf_info == header_block.reward_chain_block.challenge_chain_sp_vdf: assert header_block.challenge_chain_sp_proof is not None if ( header_block.challenge_chain_sp_proof.witness_type == 0 and header_block.challenge_chain_sp_proof.normalized_to_identity ): return False return True if field_vdf == CompressibleVDFField.CC_IP_VDF: if vdf_info == header_block.reward_chain_block.challenge_chain_ip_vdf: if ( header_block.challenge_chain_ip_proof.witness_type == 0 and header_block.challenge_chain_ip_proof.normalized_to_identity ): return False return True return False async def _can_accept_compact_proof( self, vdf_info: VDFInfo, vdf_proof: VDFProof, height: uint32, header_hash: bytes32, field_vdf: CompressibleVDFField, ) -> bool: """ - Checks if the provided proof is indeed compact. - Checks if proof verifies given the vdf_info from the start of sub-slot. - Checks if the provided vdf_info is correct, assuming it refers to the start of sub-slot. - Checks if the existing proof was non-compact. Ignore this proof if we already have a compact proof. """ is_fully_compactified = await self.block_store.is_fully_compactified(header_hash) if is_fully_compactified is None or is_fully_compactified: self.log.info(f"Already compactified block: {header_hash}. Ignoring.") return False if vdf_proof.witness_type > 0 or not vdf_proof.normalized_to_identity: self.log.error(f"Received vdf proof is not compact: {vdf_proof}.") return False if not vdf_proof.is_valid(self.constants, ClassgroupElement.get_default_element(), vdf_info): self.log.error(f"Received compact vdf proof is not valid: {vdf_proof}.") return False header_block = await self.blockchain.get_header_block_by_height(height, header_hash, tx_filter=False) if header_block is None: self.log.error(f"Can't find block for given compact vdf. Height: {height} Header hash: {header_hash}") return False is_new_proof = await self._needs_compact_proof(vdf_info, header_block, field_vdf) if not is_new_proof: self.log.info(f"Duplicate compact proof. Height: {height}. Header hash: {header_hash}.") return is_new_proof async def _replace_proof( self, vdf_info: VDFInfo, vdf_proof: VDFProof, height: uint32, field_vdf: CompressibleVDFField, ) -> bool: full_blocks = await self.block_store.get_full_blocks_at([height]) assert len(full_blocks) > 0 replaced = False expected_header_hash = self.blockchain.height_to_hash(height) for block in full_blocks: new_block = None if block.header_hash != expected_header_hash: continue block_record = await self.blockchain.get_block_record_from_db(expected_header_hash) assert block_record is not None if field_vdf == CompressibleVDFField.CC_EOS_VDF: for index, sub_slot in enumerate(block.finished_sub_slots): if sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf == vdf_info: new_proofs = dataclasses.replace(sub_slot.proofs, challenge_chain_slot_proof=vdf_proof) new_subslot = dataclasses.replace(sub_slot, proofs=new_proofs) new_finished_subslots = block.finished_sub_slots new_finished_subslots[index] = new_subslot new_block = dataclasses.replace(block, finished_sub_slots=new_finished_subslots) break if field_vdf == CompressibleVDFField.ICC_EOS_VDF: for index, sub_slot in enumerate(block.finished_sub_slots): if ( sub_slot.infused_challenge_chain is not None and sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf == vdf_info ): new_proofs = dataclasses.replace(sub_slot.proofs, infused_challenge_chain_slot_proof=vdf_proof) new_subslot = dataclasses.replace(sub_slot, proofs=new_proofs) new_finished_subslots = block.finished_sub_slots new_finished_subslots[index] = new_subslot new_block = dataclasses.replace(block, finished_sub_slots=new_finished_subslots) break if field_vdf == CompressibleVDFField.CC_SP_VDF: if block.reward_chain_block.challenge_chain_sp_vdf == vdf_info: assert block.challenge_chain_sp_proof is not None new_block = dataclasses.replace(block, challenge_chain_sp_proof=vdf_proof) if field_vdf == CompressibleVDFField.CC_IP_VDF: if block.reward_chain_block.challenge_chain_ip_vdf == vdf_info: new_block = dataclasses.replace(block, challenge_chain_ip_proof=vdf_proof) if new_block is None: continue async with self.db_wrapper.lock: await self.block_store.add_full_block(new_block.header_hash, new_block, block_record) await self.block_store.db_wrapper.commit_transaction() replaced = True return replaced async def respond_compact_proof_of_time(self, request: timelord_protocol.RespondCompactProofOfTime): field_vdf = CompressibleVDFField(int(request.field_vdf)) if not await self._can_accept_compact_proof( request.vdf_info, request.vdf_proof, request.height, request.header_hash, field_vdf ): return None async with self.blockchain.compact_proof_lock: replaced = await self._replace_proof(request.vdf_info, request.vdf_proof, request.height, field_vdf) if not replaced: self.log.error(f"Could not replace compact proof: {request.height}") return None self.log.info(f"Replaced compact proof at height {request.height}") msg = make_msg( ProtocolMessageTypes.new_compact_vdf, full_node_protocol.NewCompactVDF(request.height, request.header_hash, request.field_vdf, request.vdf_info), ) if self.server is not None: await self.server.send_to_all([msg], NodeType.FULL_NODE) async def new_compact_vdf(self, request: full_node_protocol.NewCompactVDF, peer: ws.WSStaiDeltaConnection): is_fully_compactified = await self.block_store.is_fully_compactified(request.header_hash) if is_fully_compactified is None or is_fully_compactified: return False header_block = await self.blockchain.get_header_block_by_height( request.height, request.header_hash, tx_filter=False ) if header_block is None: return None field_vdf = CompressibleVDFField(int(request.field_vdf)) if await self._needs_compact_proof(request.vdf_info, header_block, field_vdf): peer_request = full_node_protocol.RequestCompactVDF( request.height, request.header_hash, request.field_vdf, request.vdf_info ) response = await peer.request_compact_vdf(peer_request, timeout=10) if response is not None and isinstance(response, full_node_protocol.RespondCompactVDF): await self.respond_compact_vdf(response, peer) async def request_compact_vdf(self, request: full_node_protocol.RequestCompactVDF, peer: ws.WSStaiDeltaConnection): header_block = await self.blockchain.get_header_block_by_height( request.height, request.header_hash, tx_filter=False ) if header_block is None: return None vdf_proof: Optional[VDFProof] = None field_vdf = CompressibleVDFField(int(request.field_vdf)) if field_vdf == CompressibleVDFField.CC_EOS_VDF: for sub_slot in header_block.finished_sub_slots: if sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf == request.vdf_info: vdf_proof = sub_slot.proofs.challenge_chain_slot_proof break if field_vdf == CompressibleVDFField.ICC_EOS_VDF: for sub_slot in header_block.finished_sub_slots: if ( sub_slot.infused_challenge_chain is not None and sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf == request.vdf_info ): vdf_proof = sub_slot.proofs.infused_challenge_chain_slot_proof break if ( field_vdf == CompressibleVDFField.CC_SP_VDF and header_block.reward_chain_block.challenge_chain_sp_vdf == request.vdf_info ): vdf_proof = header_block.challenge_chain_sp_proof if ( field_vdf == CompressibleVDFField.CC_IP_VDF and header_block.reward_chain_block.challenge_chain_ip_vdf == request.vdf_info ): vdf_proof = header_block.challenge_chain_ip_proof if vdf_proof is None or vdf_proof.witness_type > 0 or not vdf_proof.normalized_to_identity: self.log.error(f"{peer} requested compact vdf we don't have, height: {request.height}.") return None compact_vdf = full_node_protocol.RespondCompactVDF( request.height, request.header_hash, request.field_vdf, request.vdf_info, vdf_proof, ) msg = make_msg(ProtocolMessageTypes.respond_compact_vdf, compact_vdf) await peer.send_message(msg) async def respond_compact_vdf(self, request: full_node_protocol.RespondCompactVDF, peer: ws.WSStaiDeltaConnection): field_vdf = CompressibleVDFField(int(request.field_vdf)) if not await self._can_accept_compact_proof( request.vdf_info, request.vdf_proof, request.height, request.header_hash, field_vdf ): return None async with self.blockchain.compact_proof_lock: if self.blockchain.seen_compact_proofs(request.vdf_info, request.height): return None replaced = await self._replace_proof(request.vdf_info, request.vdf_proof, request.height, field_vdf) if not replaced: self.log.error(f"Could not replace compact proof: {request.height}") return None msg = make_msg( ProtocolMessageTypes.new_compact_vdf, full_node_protocol.NewCompactVDF(request.height, request.header_hash, request.field_vdf, request.vdf_info), ) if self.server is not None: await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id) async def broadcast_uncompact_blocks( self, uncompact_interval_scan: int, target_uncompact_proofs: int, sanitize_weight_proof_only: bool ): try: while not self._shut_down: while self.sync_store.get_sync_mode(): if self._shut_down: return None await asyncio.sleep(30) broadcast_list: List[timelord_protocol.RequestCompactProofOfTime] = [] self.log.info("Getting random heights for bluebox to compact") heights = await self.block_store.get_random_not_compactified(target_uncompact_proofs) self.log.info("Heights found for bluebox to compact: [%s]" % ", ".join(map(str, heights))) for h in heights: headers = await self.blockchain.get_header_blocks_in_range(h, h, tx_filter=False) records: Dict[bytes32, BlockRecord] = {} if sanitize_weight_proof_only: records = await self.blockchain.get_block_records_in_range(h, h) for header in headers.values(): expected_header_hash = self.blockchain.height_to_hash(header.height) if header.header_hash != expected_header_hash: continue if sanitize_weight_proof_only: assert header.header_hash in records record = records[header.header_hash] for sub_slot in header.finished_sub_slots: if ( sub_slot.proofs.challenge_chain_slot_proof.witness_type > 0 or not sub_slot.proofs.challenge_chain_slot_proof.normalized_to_identity ): broadcast_list.append( timelord_protocol.RequestCompactProofOfTime( sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf, header.header_hash, header.height, uint8(CompressibleVDFField.CC_EOS_VDF), ) ) if sub_slot.proofs.infused_challenge_chain_slot_proof is not None and ( sub_slot.proofs.infused_challenge_chain_slot_proof.witness_type > 0 or not sub_slot.proofs.infused_challenge_chain_slot_proof.normalized_to_identity ): assert sub_slot.infused_challenge_chain is not None broadcast_list.append( timelord_protocol.RequestCompactProofOfTime( sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf, header.header_hash, header.height, uint8(CompressibleVDFField.ICC_EOS_VDF), ) ) # Running in 'sanitize_weight_proof_only' ignores CC_SP_VDF and CC_IP_VDF # unless this is a challenge block. if sanitize_weight_proof_only: if not record.is_challenge_block(self.constants): continue if header.challenge_chain_sp_proof is not None and ( header.challenge_chain_sp_proof.witness_type > 0 or not header.challenge_chain_sp_proof.normalized_to_identity ): assert header.reward_chain_block.challenge_chain_sp_vdf is not None broadcast_list.append( timelord_protocol.RequestCompactProofOfTime( header.reward_chain_block.challenge_chain_sp_vdf, header.header_hash, header.height, uint8(CompressibleVDFField.CC_SP_VDF), ) ) if ( header.challenge_chain_ip_proof.witness_type > 0 or not header.challenge_chain_ip_proof.normalized_to_identity ): broadcast_list.append( timelord_protocol.RequestCompactProofOfTime( header.reward_chain_block.challenge_chain_ip_vdf, header.header_hash, header.height, uint8(CompressibleVDFField.CC_IP_VDF), ) ) if len(broadcast_list) > target_uncompact_proofs: broadcast_list = broadcast_list[:target_uncompact_proofs] if self.sync_store.get_sync_mode(): continue if self.server is not None: self.log.info(f"Broadcasting {len(broadcast_list)} items to the bluebox") msgs = [] for new_pot in broadcast_list: msg = make_msg(ProtocolMessageTypes.request_compact_proof_of_time, new_pot) msgs.append(msg) await self.server.send_to_all(msgs, NodeType.TIMELORD) await asyncio.sleep(uncompact_interval_scan) except Exception as e: error_stack = traceback.format_exc() self.log.error(f"Exception in broadcast_uncompact_blocks: {e}") self.log.error(f"Exception Stack: {error_stack}") async def node_next_block_check( peer: ws.WSStaiDeltaConnection, potential_peek: uint32, blockchain: BlockchainInterface ) -> bool: block_response: Optional[Any] = await peer.request_block(full_node_protocol.RequestBlock(potential_peek, True)) if block_response is not None and isinstance(block_response, full_node_protocol.RespondBlock): peak = blockchain.get_peak() if peak is not None and block_response.block.prev_header_hash == peak.header_hash: return True return False
import asyncio import dataclasses import logging import random import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union import aiosqlite from blspy import AugSchemeMPL import staidelta.server.ws_connection as ws # lgtm [py/import-and-import-from] from staidelta.consensus.block_creation import unfinished_block_to_full_block from staidelta.consensus.block_record import BlockRecord from staidelta.consensus.blockchain import Blockchain, ReceiveBlockResult from staidelta.consensus.blockchain_interface import BlockchainInterface from staidelta.consensus.constants import ConsensusConstants from staidelta.consensus.cost_calculator import NPCResult from staidelta.consensus.difficulty_adjustment import get_next_sub_slot_iters_and_difficulty from staidelta.consensus.make_sub_epoch_summary import next_sub_epoch_summary from staidelta.consensus.multiprocess_validation import PreValidationResult from staidelta.consensus.pot_iterations import calculate_sp_iters from staidelta.full_node.block_store import BlockStore from staidelta.full_node.lock_queue import LockQueue, LockClient from staidelta.full_node.bundle_tools import detect_potential_template_generator from staidelta.full_node.coin_store import CoinStore from staidelta.full_node.full_node_store import FullNodeStore, FullNodeStorePeakResult from staidelta.full_node.hint_store import HintStore from staidelta.full_node.mempool_manager import MempoolManager from staidelta.full_node.signage_point import SignagePoint from staidelta.full_node.sync_store import SyncStore from staidelta.full_node.weight_proof import WeightProofHandler from staidelta.protocols import farmer_protocol, full_node_protocol, timelord_protocol, wallet_protocol from staidelta.protocols.full_node_protocol import ( RequestBlocks, RespondBlock, RespondBlocks, RespondSignagePoint, ) from staidelta.protocols.protocol_message_types import ProtocolMessageTypes from staidelta.protocols.wallet_protocol import CoinState, CoinStateUpdate from staidelta.server.node_discovery import FullNodePeers from staidelta.server.outbound_message import Message, NodeType, make_msg from staidelta.server.server import StaiDeltaServer from staidelta.types.blockchain_format.classgroup import ClassgroupElement from staidelta.types.blockchain_format.pool_target import PoolTarget from staidelta.types.blockchain_format.sized_bytes import bytes32 from staidelta.types.blockchain_format.sub_epoch_summary import SubEpochSummary from staidelta.types.blockchain_format.vdf import CompressibleVDFField, VDFInfo, VDFProof from staidelta.types.coin_record import CoinRecord from staidelta.types.end_of_slot_bundle import EndOfSubSlotBundle from staidelta.types.full_block import FullBlock from staidelta.types.generator_types import BlockGenerator from staidelta.types.header_block import HeaderBlock from staidelta.types.mempool_inclusion_status import MempoolInclusionStatus from staidelta.types.spend_bundle import SpendBundle from staidelta.types.transaction_queue_entry import TransactionQueueEntry from staidelta.types.unfinished_block import UnfinishedBlock from staidelta.util import cached_bls from staidelta.util.bech32m import encode_puzzle_hash from staidelta.util.check_fork_next_block import check_fork_next_block from staidelta.util.condition_tools import pkm_pairs from staidelta.util.db_wrapper import DBWrapper from staidelta.util.errors import ConsensusError, Err, ValidationError from staidelta.util.ints import uint8, uint32, uint64, uint128 from staidelta.util.path import mkdir, path_from_root from staidelta.util.safe_cancel_task import cancel_task_safe from staidelta.util.profiler import profile_task from datetime import datetime from staidelta.util.db_synchronous import db_synchronous_on class FullNode: block_store: BlockStore full_node_store: FullNodeStore full_node_peers: Optional[FullNodePeers] sync_store: Any coin_store: CoinStore mempool_manager: MempoolManager connection: aiosqlite.Connection _sync_task: Optional[asyncio.Task] _init_weight_proof: Optional[asyncio.Task] = None blockchain: Blockchain config: Dict server: Any log: logging.Logger constants: ConsensusConstants _shut_down: bool root_path: Path state_changed_callback: Optional[Callable] timelord_lock: asyncio.Lock initialized: bool weight_proof_handler: Optional[WeightProofHandler] _ui_tasks: Set[asyncio.Task] _blockchain_lock_queue: LockQueue _blockchain_lock_ultra_priority: LockClient _blockchain_lock_high_priority: LockClient _blockchain_lock_low_priority: LockClient def __init__( self, config: Dict, root_path: Path, consensus_constants: ConsensusConstants, name: str = None, ): self.initialized = False self.root_path = root_path self.config = config self.server = None self._shut_down = False # Set to true to close all infinite loops self.constants = consensus_constants self.pow_creation: Dict[uint32, asyncio.Event] = {} self.state_changed_callback: Optional[Callable] = None self.full_node_peers = None self.sync_store = None self.signage_point_times = [time.time() for _ in range(self.constants.NUM_SPS_SUB_SLOT)] self.full_node_store = FullNodeStore(self.constants) self.uncompact_task = None self.compact_vdf_requests: Set[bytes32] = set() self.log = logging.getLogger(name if name else __name__) # Used for metrics self.dropped_tx: Set[bytes32] = set() self.not_dropped_tx = 0 self._ui_tasks = set() db_path_replaced: str = config["database_path"].replace("CHALLENGE", config["selected_network"]) self.db_path = path_from_root(root_path, db_path_replaced) self.coin_subscriptions: Dict[bytes32, Set[bytes32]] = {} # Puzzle Hash : Set[Peer ID] self.ph_subscriptions: Dict[bytes32, Set[bytes32]] = {} # Puzzle Hash : Set[Peer ID] self.peer_coin_ids: Dict[bytes32, Set[bytes32]] = {} # Peer ID: Set[Coin ids] self.peer_puzzle_hash: Dict[bytes32, Set[bytes32]] = {} # Peer ID: Set[puzzle_hash] self.peer_sub_counter: Dict[bytes32, int] = {} # Peer ID: int (subscription count) mkdir(self.db_path.parent) def _set_state_changed_callback(self, callback: Callable): self.state_changed_callback = callback async def _start(self): self.timelord_lock = asyncio.Lock() self.compact_vdf_sem = asyncio.Semaphore(4) # We don't want to run too many concurrent new_peak instances, because it would fetch the same block from # multiple peers and re-validate. self.new_peak_sem = asyncio.Semaphore(2) # These many respond_transaction tasks can be active at any point in time self.respond_transaction_semaphore = asyncio.Semaphore(200) # create the store (db) and full node instance self.connection = await aiosqlite.connect(self.db_path) await self.connection.execute("pragma journal_mode=wal") # Never use pragma synchronous=OFF in StaiDelta. # await self.connection.execute( # "pragma synchronous={}".format(db_synchronous_on(self.config.get("db_sync", "auto"), self.db_path)) # ) if self.config.get("log_sqlite_cmds", False): sql_log_path = path_from_root(self.root_path, "log/sql.log") self.log.info(f"logging SQL commands to {sql_log_path}") def sql_trace_callback(req: str): timestamp = datetime.now().strftime("%H:%M:%S.%f") log = open(sql_log_path, "a") log.write(timestamp + " " + req + "\n") log.close() await self.connection.set_trace_callback(sql_trace_callback) self.db_wrapper = DBWrapper(self.connection) self.block_store = await BlockStore.create(self.db_wrapper) self.sync_store = await SyncStore.create() self.hint_store = await HintStore.create(self.db_wrapper) self.coin_store = await CoinStore.create(self.db_wrapper) self.log.info("Initializing blockchain from disk") start_time = time.time() self.blockchain = await Blockchain.create(self.coin_store, self.block_store, self.constants, self.hint_store) self.mempool_manager = MempoolManager(self.coin_store, self.constants) # Blocks are validated under high priority, and transactions under low priority. This guarantees blocks will # be validated first. self._blockchain_lock_queue = LockQueue(self.blockchain.lock) self._blockchain_lock_ultra_priority = LockClient(0, self._blockchain_lock_queue) self._blockchain_lock_high_priority = LockClient(1, self._blockchain_lock_queue) self._blockchain_lock_low_priority = LockClient(2, self._blockchain_lock_queue) # Transactions go into this queue from the server, and get sent to respond_transaction self.transaction_queue = asyncio.PriorityQueue(10000) self._transaction_queue_task = asyncio.create_task(self._handle_transactions()) self.transaction_responses: List[Tuple[bytes32, MempoolInclusionStatus, Optional[Err]]] = [] self.weight_proof_handler = None self._init_weight_proof = asyncio.create_task(self.initialize_weight_proof()) if self.config.get("enable_profiler", False): asyncio.create_task(profile_task(self.root_path, "node", self.log)) self._sync_task = None self._segment_task = None time_taken = time.time() - start_time if self.blockchain.get_peak() is None: self.log.info(f"Initialized with empty blockchain time taken: {int(time_taken)}s") else: self.log.info( f"Blockchain initialized to peak {self.blockchain.get_peak().header_hash} height" f" {self.blockchain.get_peak().height}, " f"time taken: {int(time_taken)}s" ) async with self._blockchain_lock_high_priority: pending_tx = await self.mempool_manager.new_peak(self.blockchain.get_peak(), []) assert len(pending_tx) == 0 # no pending transactions when starting up peak: Optional[BlockRecord] = self.blockchain.get_peak() if peak is not None: full_peak = await self.blockchain.get_full_peak() mempool_new_peak_result, fns_peak_result = await self.peak_post_processing( full_peak, peak, max(peak.height - 1, 0), None, [] ) await self.peak_post_processing_2( full_peak, peak, max(peak.height - 1, 0), None, ([], {}), mempool_new_peak_result, fns_peak_result ) if self.config["send_uncompact_interval"] != 0: sanitize_weight_proof_only = False if "sanitize_weight_proof_only" in self.config: sanitize_weight_proof_only = self.config["sanitize_weight_proof_only"] assert self.config["target_uncompact_proofs"] != 0 self.uncompact_task = asyncio.create_task( self.broadcast_uncompact_blocks( self.config["send_uncompact_interval"], self.config["target_uncompact_proofs"], sanitize_weight_proof_only, ) ) self.initialized = True if self.full_node_peers is not None: asyncio.create_task(self.full_node_peers.start()) async def _handle_one_transaction(self, entry: TransactionQueueEntry): peer = entry.peer try: inc_status, err = await self.respond_transaction(entry.transaction, entry.spend_name, peer, entry.test) self.transaction_responses.append((entry.spend_name, inc_status, err)) if len(self.transaction_responses) > 50: self.transaction_responses = self.transaction_responses[1:] except asyncio.CancelledError: error_stack = traceback.format_exc() self.log.debug(f"Cancelling _handle_one_transaction, closing: {error_stack}") except Exception: error_stack = traceback.format_exc() self.log.error(f"Error in _handle_one_transaction, closing: {error_stack}") if peer is not None: await peer.close() finally: self.respond_transaction_semaphore.release() async def _handle_transactions(self): try: while not self._shut_down: # We use a semaphore to make sure we don't send more than 200 concurrent calls of respond_transaction. # However doing them one at a time would be slow, because they get sent to other processes. await self.respond_transaction_semaphore.acquire() item: TransactionQueueEntry = (await self.transaction_queue.get())[1] asyncio.create_task(self._handle_one_transaction(item)) except asyncio.CancelledError: raise async def initialize_weight_proof(self): self.weight_proof_handler = WeightProofHandler(self.constants, self.blockchain) peak = self.blockchain.get_peak() if peak is not None: await self.weight_proof_handler.create_sub_epoch_segments() def set_server(self, server: StaiDeltaServer): self.server = server dns_servers = [] try: network_name = self.config["selected_network"] default_port = self.config["network_overrides"]["config"][network_name]["default_full_node_port"] except Exception: self.log.info("Default port field not found in config.") default_port = None if "dns_servers" in self.config: dns_servers = self.config["dns_servers"] elif self.config["port"] == 3100: # If `dns_servers` misses from the `config`, hardcode it if we're running mainnet. dns_servers.append("dns-introducer.staidelta-network.net") try: self.full_node_peers = FullNodePeers( self.server, self.root_path, self.config["target_peer_count"] - self.config["target_outbound_peer_count"], self.config["target_outbound_peer_count"], self.config["peer_db_path"], self.config["introducer_peer"], dns_servers, self.config["peer_connect_interval"], self.config["selected_network"], default_port, self.log, ) except Exception as e: error_stack = traceback.format_exc() self.log.error(f"Exception: {e}") self.log.error(f"Exception in peer discovery: {e}") self.log.error(f"Exception Stack: {error_stack}") def _state_changed(self, change: str): if self.state_changed_callback is not None: self.state_changed_callback(change) async def short_sync_batch(self, peer: ws.WSStaiDeltaConnection, start_height: uint32, target_height: uint32) -> bool: """ Tries to sync to a chain which is not too far in the future, by downloading batches of blocks. If the first block that we download is not connected to our chain, we return False and do an expensive long sync instead. Long sync is not preferred because it requires downloading and validating a weight proof. Args: peer: peer to sync from start_height: height that we should start downloading at. (Our peak is higher) target_height: target to sync to Returns: False if the fork point was not found, and we need to do a long sync. True otherwise. """ # Don't trigger multiple batch syncs to the same peer if ( peer.peer_node_id in self.sync_store.backtrack_syncing and self.sync_store.backtrack_syncing[peer.peer_node_id] > 0 ): return True # Don't batch sync, we are already in progress of a backtrack sync if peer.peer_node_id in self.sync_store.batch_syncing: return True # Don't trigger a long sync self.sync_store.batch_syncing.add(peer.peer_node_id) self.log.info(f"Starting batch short sync from {start_height} to height {target_height}") if start_height > 0: first = await peer.request_block(full_node_protocol.RequestBlock(uint32(start_height), False)) if first is None or not isinstance(first, full_node_protocol.RespondBlock): self.sync_store.batch_syncing.remove(peer.peer_node_id) raise ValueError(f"Error short batch syncing, could not fetch block at height {start_height}") if not self.blockchain.contains_block(first.block.prev_header_hash): self.log.info("Batch syncing stopped, this is a deep chain") self.sync_store.batch_syncing.remove(peer.peer_node_id) # First sb not connected to our blockchain, do a long sync instead return False batch_size = self.constants.MAX_BLOCK_COUNT_PER_REQUESTS if self._segment_task is not None and (not self._segment_task.done()): try: self._segment_task.cancel() except Exception as e: self.log.warning(f"failed to cancel segment task {e}") self._segment_task = None try: for height in range(start_height, target_height, batch_size): end_height = min(target_height, height + batch_size) request = RequestBlocks(uint32(height), uint32(end_height), True) response = await peer.request_blocks(request) if not response: raise ValueError(f"Error short batch syncing, invalid/no response for {height}-{end_height}") async with self._blockchain_lock_high_priority: for block in response.blocks: success, advanced_peak, fork_height, coin_changes = await self.receive_block_batch( [block], peer, None ) if not success: raise ValueError( f"Error short batch syncing, failed to validate blocks {height}-{end_height}" ) if advanced_peak: peak = self.blockchain.get_peak() try: peak_fb: Optional[FullBlock] = await self.blockchain.get_full_peak() assert peak is not None and peak_fb is not None and fork_height is not None mempool_new_peak_result, fns_peak_result = await self.peak_post_processing( peak_fb, peak, fork_height, peer, coin_changes[0] ) await self.peak_post_processing_2( peak_fb, peak, fork_height, peer, coin_changes, mempool_new_peak_result, fns_peak_result, ) except asyncio.CancelledError: # Still do post processing after cancel peak_fb = await self.blockchain.get_full_peak() assert peak is not None and peak_fb is not None and fork_height is not None await self.peak_post_processing(peak_fb, peak, fork_height, peer, coin_changes[0]) raise finally: self.log.info(f"Added blocks {height}-{end_height}") except (asyncio.CancelledError, Exception) as e: self.sync_store.batch_syncing.remove(peer.peer_node_id) raise e self.sync_store.batch_syncing.remove(peer.peer_node_id) return True async def short_sync_backtrack( self, peer: ws.WSStaiDeltaConnection, peak_height: uint32, target_height: uint32, target_unf_hash: bytes32 ): """ Performs a backtrack sync, where blocks are downloaded one at a time from newest to oldest. If we do not find the fork point 5 deeper than our peak, we return False and do a long sync instead. Args: peer: peer to sync from peak_height: height of our peak target_height: target height target_unf_hash: partial hash of the unfinished block of the target Returns: True iff we found the fork point, and we do not need to long sync. """ try: if peer.peer_node_id not in self.sync_store.backtrack_syncing: self.sync_store.backtrack_syncing[peer.peer_node_id] = 0 self.sync_store.backtrack_syncing[peer.peer_node_id] += 1 unfinished_block: Optional[UnfinishedBlock] = self.full_node_store.get_unfinished_block(target_unf_hash) curr_height: int = target_height found_fork_point = False responses = [] while curr_height > peak_height - 5: # If we already have the unfinished block, don't fetch the transactions. In the normal case, we will # already have the unfinished block, from when it was broadcast, so we just need to download the header, # but not the transactions fetch_tx: bool = unfinished_block is None or curr_height != target_height curr = await peer.request_block(full_node_protocol.RequestBlock(uint32(curr_height), fetch_tx)) if curr is None: raise ValueError(f"Failed to fetch block {curr_height} from {peer.get_peer_logging()}, timed out") if curr is None or not isinstance(curr, full_node_protocol.RespondBlock): raise ValueError( f"Failed to fetch block {curr_height} from {peer.get_peer_logging()}, wrong type {type(curr)}" ) responses.append(curr) if self.blockchain.contains_block(curr.block.prev_header_hash) or curr_height == 0: found_fork_point = True break curr_height -= 1 if found_fork_point: for response in reversed(responses): await self.respond_block(response, peer) except (asyncio.CancelledError, Exception) as e: self.sync_store.backtrack_syncing[peer.peer_node_id] -= 1 raise e self.sync_store.backtrack_syncing[peer.peer_node_id] -= 1 return found_fork_point async def _refresh_ui_connections(self, sleep_before: float = 0): if sleep_before > 0: await asyncio.sleep(sleep_before) self._state_changed("peer_changed_peak") async def new_peak(self, request: full_node_protocol.NewPeak, peer: ws.WSStaiDeltaConnection): """ We have received a notification of a new peak from a peer. This happens either when we have just connected, or when the peer has updated their peak. Args: request: information about the new peak peer: peer that sent the message """ try: seen_header_hash = self.sync_store.seen_header_hash(request.header_hash) # Updates heights in the UI. Sleeps 1.5s before, so other peers have time to update their peaks as well. # Limit to 3 refreshes. if not seen_header_hash and len(self._ui_tasks) < 3: self._ui_tasks.add(asyncio.create_task(self._refresh_ui_connections(1.5))) # Prune completed connect tasks self._ui_tasks = set(filter(lambda t: not t.done(), self._ui_tasks)) except Exception as e: self.log.warning(f"Exception UI refresh task: {e}") # Store this peak/peer combination in case we want to sync to it, and to keep track of peers self.sync_store.peer_has_block(request.header_hash, peer.peer_node_id, request.weight, request.height, True) if self.blockchain.contains_block(request.header_hash): return None # Not interested in less heavy peaks peak: Optional[BlockRecord] = self.blockchain.get_peak() curr_peak_height = uint32(0) if peak is None else peak.height if peak is not None and peak.weight > request.weight: return None if self.sync_store.get_sync_mode(): # If peer connects while we are syncing, check if they have the block we are syncing towards peak_sync_hash = self.sync_store.get_sync_target_hash() peak_sync_height = self.sync_store.get_sync_target_height() if peak_sync_hash is not None and request.header_hash != peak_sync_hash and peak_sync_height is not None: peak_peers: Set[bytes32] = self.sync_store.get_peers_that_have_peak([peak_sync_hash]) # Don't ask if we already know this peer has the peak if peer.peer_node_id not in peak_peers: target_peak_response: Optional[RespondBlock] = await peer.request_block( full_node_protocol.RequestBlock(uint32(peak_sync_height), False), timeout=10 ) if target_peak_response is not None and isinstance(target_peak_response, RespondBlock): self.sync_store.peer_has_block( peak_sync_hash, peer.peer_node_id, target_peak_response.block.weight, peak_sync_height, False, ) else: if request.height <= curr_peak_height + self.config["short_sync_blocks_behind_threshold"]: # This is the normal case of receiving the next block if await self.short_sync_backtrack( peer, curr_peak_height, request.height, request.unfinished_reward_block_hash ): return None if request.height < self.constants.WEIGHT_PROOF_RECENT_BLOCKS: # This is the case of syncing up more than a few blocks, at the start of the chain self.log.debug("Doing batch sync, no backup") await self.short_sync_batch(peer, uint32(0), request.height) return None if request.height < curr_peak_height + self.config["sync_blocks_behind_threshold"]: # This case of being behind but not by so much if await self.short_sync_batch(peer, uint32(max(curr_peak_height - 6, 0)), request.height): return None # This is the either the case where we were not able to sync successfully (for example, due to the fork # point being in the past), or we are very far behind. Performs a long sync. self._sync_task = asyncio.create_task(self._sync()) async def send_peak_to_timelords( self, peak_block: Optional[FullBlock] = None, peer: Optional[ws.WSStaiDeltaConnection] = None ): """ Sends current peak to timelords """ if peak_block is None: peak_block = await self.blockchain.get_full_peak() if peak_block is not None: peak = self.blockchain.block_record(peak_block.header_hash) self.log.info(f"send_peak_to_timelords {peak.height} {peak.required_iters}") difficulty = self.blockchain.get_next_difficulty(peak.header_hash, False) difficulty_coeff = await self.blockchain.get_farmer_difficulty_coeff( peak.farmer_public_key, peak.height - 1 if peak.height > 0 else 0 ) ses: Optional[SubEpochSummary] = next_sub_epoch_summary( self.constants, self.blockchain, peak.required_iters, peak_block, True, ) recent_rc = self.blockchain.get_recent_reward_challenges() curr = peak while not curr.is_challenge_block(self.constants) and not curr.first_in_sub_slot: curr = self.blockchain.block_record(curr.prev_hash) if curr.is_challenge_block(self.constants): last_csb_or_eos = curr.total_iters else: last_csb_or_eos = curr.ip_sub_slot_total_iters(self.constants) curr = peak passed_ses_height_but_not_yet_included = True while (curr.height % self.constants.SUB_EPOCH_BLOCKS) != 0: if curr.sub_epoch_summary_included: passed_ses_height_but_not_yet_included = False curr = self.blockchain.block_record(curr.prev_hash) if curr.sub_epoch_summary_included or curr.height == 0: passed_ses_height_but_not_yet_included = False timelord_new_peak: timelord_protocol.NewPeakTimelord = timelord_protocol.NewPeakTimelord( peak_block.reward_chain_block, difficulty, str(difficulty_coeff), peak.deficit, peak.sub_slot_iters, ses, recent_rc, last_csb_or_eos, passed_ses_height_but_not_yet_included, ) msg = make_msg(ProtocolMessageTypes.new_peak_timelord, timelord_new_peak) if peer is None: await self.server.send_to_all([msg], NodeType.TIMELORD) else: await self.server.send_to_specific([msg], peer.peer_node_id) async def synced(self) -> bool: curr: Optional[BlockRecord] = self.blockchain.get_peak() if curr is None: return False while curr is not None and not curr.is_transaction_block: curr = self.blockchain.try_block_record(curr.prev_hash) now = time.time() if ( curr is None or curr.timestamp is None or curr.timestamp < uint64(int(now - 60 * 7)) or self.sync_store.get_sync_mode() ): return False else: return True async def on_connect(self, connection: ws.WSStaiDeltaConnection): """ Whenever we connect to another node / wallet, send them our current heads. Also send heads to farmers and challenges to timelords. """ self._state_changed("add_connection") self._state_changed("sync_mode") if self.full_node_peers is not None: asyncio.create_task(self.full_node_peers.on_connect(connection)) if self.initialized is False: return None if connection.connection_type is NodeType.FULL_NODE: # Send filter to node and request mempool items that are not in it (Only if we are currently synced) synced = await self.synced() peak_height = self.blockchain.get_peak_height() if synced and peak_height is not None: my_filter = self.mempool_manager.get_filter() mempool_request = full_node_protocol.RequestMempoolTransactions(my_filter) msg = make_msg(ProtocolMessageTypes.request_mempool_transactions, mempool_request) await connection.send_message(msg) peak_full: Optional[FullBlock] = await self.blockchain.get_full_peak() if peak_full is not None: peak: BlockRecord = self.blockchain.block_record(peak_full.header_hash) if connection.connection_type is NodeType.FULL_NODE: request_node = full_node_protocol.NewPeak( peak.header_hash, peak.height, peak.weight, peak.height, peak_full.reward_chain_block.get_unfinished().get_hash(), ) await connection.send_message(make_msg(ProtocolMessageTypes.new_peak, request_node)) elif connection.connection_type is NodeType.WALLET: # If connected to a wallet, send the Peak request_wallet = wallet_protocol.NewPeakWallet( peak.header_hash, peak.height, peak.weight, peak.height, ) await connection.send_message(make_msg(ProtocolMessageTypes.new_peak_wallet, request_wallet)) elif connection.connection_type is NodeType.TIMELORD: await self.send_peak_to_timelords() def on_disconnect(self, connection: ws.WSStaiDeltaConnection): self.log.info(f"peer disconnected {connection.get_peer_logging()}") self._state_changed("close_connection") self._state_changed("sync_mode") if self.sync_store is not None: self.sync_store.peer_disconnected(connection.peer_node_id) self.remove_subscriptions(connection) def remove_subscriptions(self, peer: ws.WSStaiDeltaConnection): # Remove all ph | coin id subscription for this peer node_id = peer.peer_node_id if node_id in self.peer_puzzle_hash: puzzle_hashes = self.peer_puzzle_hash[node_id] for ph in puzzle_hashes: if ph in self.ph_subscriptions: if node_id in self.ph_subscriptions[ph]: self.ph_subscriptions[ph].remove(node_id) if node_id in self.peer_coin_ids: coin_ids = self.peer_coin_ids[node_id] for coin_id in coin_ids: if coin_id in self.coin_subscriptions: if node_id in self.coin_subscriptions[coin_id]: self.coin_subscriptions[coin_id].remove(node_id) if peer.peer_node_id in self.peer_sub_counter: self.peer_sub_counter.pop(peer.peer_node_id) def _num_needed_peers(self) -> int: assert self.server is not None assert self.server.all_connections is not None diff = self.config["target_peer_count"] - len(self.server.all_connections) return diff if diff >= 0 else 0 def _close(self): self._shut_down = True if self._init_weight_proof is not None: self._init_weight_proof.cancel() # blockchain is created in _start and in certain cases it may not exist here during _close if hasattr(self, "blockchain"): self.blockchain.shut_down() # same for mempool_manager if hasattr(self, "mempool_manager"): self.mempool_manager.shut_down() if self.full_node_peers is not None: asyncio.create_task(self.full_node_peers.close()) if self.uncompact_task is not None: self.uncompact_task.cancel() self._transaction_queue_task.cancel() self._blockchain_lock_queue.close() async def _await_closed(self): cancel_task_safe(self._sync_task, self.log) for task_id, task in list(self.full_node_store.tx_fetch_tasks.items()): cancel_task_safe(task, self.log) await self.connection.close() if self._init_weight_proof is not None: await asyncio.wait([self._init_weight_proof]) await self._blockchain_lock_queue.await_closed() async def _sync(self): """ Performs a full sync of the blockchain up to the peak. - Wait a few seconds for peers to send us their peaks - Select the heaviest peak, and request a weight proof from a peer with that peak - Validate the weight proof, and disconnect from the peer if invalid - Find the fork point to see where to start downloading blocks - Download blocks in batch (and in parallel) and verify them one at a time - Disconnect peers that provide invalid blocks or don't have the blocks """ if self.weight_proof_handler is None: return None # Ensure we are only syncing once and not double calling this method if self.sync_store.get_sync_mode(): return None if self.sync_store.get_long_sync(): self.log.debug("already in long sync") return None self.sync_store.set_long_sync(True) self.log.debug("long sync started") try: self.log.info("Starting to perform sync.") self.log.info("Waiting to receive peaks from peers.") # Wait until we have 3 peaks or up to a max of 30 seconds peaks = [] for i in range(300): peaks = [tup[0] for tup in self.sync_store.get_peak_of_each_peer().values()] if len(self.sync_store.get_peers_that_have_peak(peaks)) < 3: if self._shut_down: return None await asyncio.sleep(0.1) self.log.info(f"Collected a total of {len(peaks)} peaks.") self.sync_peers_handler = None # Based on responses from peers about the current peaks, see which peak is the heaviest # (similar to longest chain rule). target_peak = self.sync_store.get_heaviest_peak() if target_peak is None: raise RuntimeError("Not performing sync, no peaks collected") heaviest_peak_hash, heaviest_peak_height, heaviest_peak_weight = target_peak self.sync_store.set_peak_target(heaviest_peak_hash, heaviest_peak_height) self.log.info(f"Selected peak {heaviest_peak_height}, {heaviest_peak_hash}") # Check which peers are updated to this height peers = [] coroutines = [] for peer in self.server.all_connections.values(): if peer.connection_type == NodeType.FULL_NODE: peers.append(peer.peer_node_id) coroutines.append( peer.request_block( full_node_protocol.RequestBlock(uint32(heaviest_peak_height), True), timeout=10 ) ) for i, target_peak_response in enumerate(await asyncio.gather(*coroutines)): if target_peak_response is not None and isinstance(target_peak_response, RespondBlock): self.sync_store.peer_has_block( heaviest_peak_hash, peers[i], heaviest_peak_weight, heaviest_peak_height, False ) # TODO: disconnect from peer which gave us the heaviest_peak, if nobody has the peak peer_ids: Set[bytes32] = self.sync_store.get_peers_that_have_peak([heaviest_peak_hash]) peers_with_peak: List = [c for c in self.server.all_connections.values() if c.peer_node_id in peer_ids] # Request weight proof from a random peer self.log.info(f"Total of {len(peers_with_peak)} peers with peak {heaviest_peak_height}") weight_proof_peer = random.choice(peers_with_peak) self.log.info( f"Requesting weight proof from peer {weight_proof_peer.peer_host} up to height" f" {heaviest_peak_height}" ) if self.blockchain.get_peak() is not None and heaviest_peak_weight <= self.blockchain.get_peak().weight: raise ValueError("Not performing sync, already caught up.") wp_timeout = 360 if "weight_proof_timeout" in self.config: wp_timeout = self.config["weight_proof_timeout"] self.log.debug(f"weight proof timeout is {wp_timeout} sec") request = full_node_protocol.RequestProofOfWeight(heaviest_peak_height, heaviest_peak_hash) response = await weight_proof_peer.request_proof_of_weight(request, timeout=wp_timeout) # Disconnect from this peer, because they have not behaved properly if response is None or not isinstance(response, full_node_protocol.RespondProofOfWeight): await weight_proof_peer.close(600) raise RuntimeError(f"Weight proof did not arrive in time from peer: {weight_proof_peer.peer_host}") if response.wp.recent_chain_data[-1].reward_chain_block.height != heaviest_peak_height: await weight_proof_peer.close(600) raise RuntimeError(f"Weight proof had the wrong height: {weight_proof_peer.peer_host}") if response.wp.recent_chain_data[-1].reward_chain_block.weight != heaviest_peak_weight: await weight_proof_peer.close(600) raise RuntimeError(f"Weight proof had the wrong weight: {weight_proof_peer.peer_host}") # dont sync to wp if local peak is heavier, # dont ban peer, we asked for this peak current_peak = self.blockchain.get_peak() if current_peak is not None: if response.wp.recent_chain_data[-1].reward_chain_block.weight <= current_peak.weight: raise RuntimeError(f"current peak is heavier than Weight proof peek: {weight_proof_peer.peer_host}") try: validated, fork_point, summaries = await self.weight_proof_handler.validate_weight_proof(response.wp) except Exception as e: await weight_proof_peer.close(600) raise ValueError(f"Weight proof validation threw an error {e}") if not validated: await weight_proof_peer.close(600) raise ValueError("Weight proof validation failed") self.log.info(f"Re-checked peers: total of {len(peers_with_peak)} peers with peak {heaviest_peak_height}") self.sync_store.set_sync_mode(True) self._state_changed("sync_mode") # Ensures that the fork point does not change async with self._blockchain_lock_high_priority: await self.blockchain.warmup(fork_point) await self.sync_from_fork_point(fork_point, heaviest_peak_height, heaviest_peak_hash, summaries) except asyncio.CancelledError: self.log.warning("Syncing failed, CancelledError") except Exception as e: tb = traceback.format_exc() self.log.error(f"Error with syncing: {type(e)}{tb}") finally: if self._shut_down: return None await self._finish_sync() async def sync_from_fork_point( self, fork_point_height: uint32, target_peak_sb_height: uint32, peak_hash: bytes32, summaries: List[SubEpochSummary], ): buffer_size = 4 self.log.info(f"Start syncing from fork point at {fork_point_height} up to {target_peak_sb_height}") peers_with_peak = self.get_peers_with_peak(peak_hash) fork_point_height = await check_fork_next_block( self.blockchain, fork_point_height, peers_with_peak, node_next_block_check ) batch_size = self.constants.MAX_BLOCK_COUNT_PER_REQUESTS async def fetch_block_batches(batch_queue, peers_with_peak: List[ws.WSStaiDeltaConnection]): try: for start_height in range(fork_point_height, target_peak_sb_height, batch_size): end_height = min(target_peak_sb_height, start_height + batch_size) request = RequestBlocks(uint32(start_height), uint32(end_height), True) fetched = False for peer in random.sample(peers_with_peak, len(peers_with_peak)): if peer.closed: peers_with_peak.remove(peer) continue response = await peer.request_blocks(request, timeout=10) if response is None: await peer.close() peers_with_peak.remove(peer) elif isinstance(response, RespondBlocks): await batch_queue.put((peer, response.blocks)) fetched = True break if fetched is False: self.log.error(f"failed fetching {start_height} to {end_height} from peers") await batch_queue.put(None) return if self.sync_store.peers_changed.is_set(): peers_with_peak = self.get_peers_with_peak(peak_hash) self.sync_store.peers_changed.clear() except Exception as e: self.log.error(f"Exception fetching {start_height} to {end_height} from peer {e}") finally: # finished signal with None await batch_queue.put(None) async def validate_block_batches(batch_queue): advanced_peak = False while True: res = await batch_queue.get() if res is None: self.log.debug("done fetching blocks") return peer, blocks = res start_height = blocks[0].height end_height = blocks[-1].height success, advanced_peak, fork_height, coin_states = await self.receive_block_batch( blocks, peer, None if advanced_peak else uint32(fork_point_height), summaries ) if success is False: if peer in peers_with_peak: peers_with_peak.remove(peer) await peer.close(600) raise ValueError(f"Failed to validate block batch {start_height} to {end_height}") self.log.info(f"Added blocks {start_height} to {end_height}") await self.send_peak_to_wallets() peak = self.blockchain.get_peak() if len(coin_states) > 0 and fork_height is not None: await self.update_wallets(peak.height, fork_height, peak.header_hash, coin_states) self.blockchain.clean_block_record(end_height - self.constants.BLOCKS_CACHE_SIZE) loop = asyncio.get_event_loop() batch_queue: asyncio.Queue[Tuple[ws.WSStaiDeltaConnection, List[FullBlock]]] = asyncio.Queue( loop=loop, maxsize=buffer_size ) fetch_task = asyncio.Task(fetch_block_batches(batch_queue, peers_with_peak)) validate_task = asyncio.Task(validate_block_batches(batch_queue)) try: await asyncio.gather(fetch_task, validate_task) except Exception as e: assert validate_task.done() fetch_task.cancel() # no need to cancel validate_task, if we end up here validate_task is already done self.log.error(f"sync from fork point failed err: {e}") async def send_peak_to_wallets(self): peak = self.blockchain.get_peak() assert peak is not None msg = make_msg( ProtocolMessageTypes.new_peak_wallet, wallet_protocol.NewPeakWallet( peak.header_hash, peak.height, peak.weight, uint32(max(peak.height - 1, uint32(0))) ), ) await self.server.send_to_all([msg], NodeType.WALLET) def get_peers_with_peak(self, peak_hash: bytes32) -> List: peer_ids: Set[bytes32] = self.sync_store.get_peers_that_have_peak([peak_hash]) if len(peer_ids) == 0: self.log.warning(f"Not syncing, no peers with header_hash {peak_hash} ") return [] peers_with_peak: List = [c for c in self.server.all_connections.values() if c.peer_node_id in peer_ids] return peers_with_peak async def update_wallets( self, height: uint32, fork_height: uint32, peak_hash: bytes32, state_update: Tuple[List[CoinRecord], Dict[bytes, Dict[bytes32, CoinRecord]]], ): changes_for_peer: Dict[bytes32, Set[CoinState]] = {} states, hint_state = state_update for coin_record in states: if coin_record.name in self.coin_subscriptions: subscribed_peers = self.coin_subscriptions[coin_record.name] for peer in subscribed_peers: if peer not in changes_for_peer: changes_for_peer[peer] = set() changes_for_peer[peer].add(coin_record.coin_state) if coin_record.coin.puzzle_hash in self.ph_subscriptions: subscribed_peers = self.ph_subscriptions[coin_record.coin.puzzle_hash] for peer in subscribed_peers: if peer not in changes_for_peer: changes_for_peer[peer] = set() changes_for_peer[peer].add(coin_record.coin_state) for hint, records in hint_state.items(): if hint in self.ph_subscriptions: subscribed_peers = self.ph_subscriptions[hint] for peer in subscribed_peers: if peer not in changes_for_peer: changes_for_peer[peer] = set() for record in records.values(): changes_for_peer[peer].add(record.coin_state) for peer, changes in changes_for_peer.items(): if peer not in self.server.all_connections: continue ws_peer: ws.WSStaiDeltaConnection = self.server.all_connections[peer] state = CoinStateUpdate(height, fork_height, peak_hash, list(changes)) msg = make_msg(ProtocolMessageTypes.coin_state_update, state) await ws_peer.send_message(msg) async def receive_block_batch( self, all_blocks: List[FullBlock], peer: ws.WSStaiDeltaConnection, fork_point: Optional[uint32], wp_summaries: Optional[List[SubEpochSummary]] = None, ) -> Tuple[bool, bool, Optional[uint32], Tuple[List[CoinRecord], Dict[bytes, Dict[bytes, CoinRecord]]]]: advanced_peak = False fork_height: Optional[uint32] = uint32(0) blocks_to_validate: List[FullBlock] = [] for i, block in enumerate(all_blocks): if not self.blockchain.contains_block_in_peak_chain(block.header_hash): blocks_to_validate = all_blocks[i:] break if len(blocks_to_validate) == 0: return True, False, fork_height, ([], {}) pre_validate_start = time.time() pre_validation_results: Optional[ List[PreValidationResult] ] = await self.blockchain.pre_validate_blocks_multiprocessing(blocks_to_validate, {}, wp_summaries=wp_summaries) pre_validate_end = time.time() if pre_validate_end - pre_validate_start > 10: self.log.warning(f"Block pre-validation time: {pre_validate_end - pre_validate_start:0.2f} seconds") else: self.log.debug(f"Block pre-validation time: {pre_validate_end - pre_validate_start:0.2f} seconds") if pre_validation_results is None: return False, False, None, ([], {}) for i, block in enumerate(blocks_to_validate): if pre_validation_results[i].error is not None: self.log.error( f"Invalid block from peer: {peer.get_peer_logging()} {Err(pre_validation_results[i].error)}" ) return False, advanced_peak, fork_height, ([], {}) # Dicts because deduping all_coin_changes: Dict[bytes32, CoinRecord] = {} all_hint_changes: Dict[bytes, Dict[bytes32, CoinRecord]] = {} for i, block in enumerate(blocks_to_validate): assert pre_validation_results[i].required_iters is not None result, error, fork_height, coin_changes = await self.blockchain.receive_block( block, pre_validation_results[i], None if advanced_peak else fork_point ) coin_record_list, hint_records = coin_changes # Update all changes for record in coin_record_list: all_coin_changes[record.name] = record for hint, list_of_records in hint_records.items(): if hint not in all_hint_changes: all_hint_changes[hint] = {} for record in list_of_records.values(): all_hint_changes[hint][record.name] = record if result == ReceiveBlockResult.NEW_PEAK: advanced_peak = True elif result == ReceiveBlockResult.INVALID_BLOCK or result == ReceiveBlockResult.DISCONNECTED_BLOCK: if error is not None: self.log.error(f"Error: {error}, Invalid block from peer: {peer.get_peer_logging()} ") return False, advanced_peak, fork_height, ([], {}) block_record = self.blockchain.block_record(block.header_hash) if block_record.sub_epoch_summary_included is not None: if self.weight_proof_handler is not None: await self.weight_proof_handler.create_prev_sub_epoch_segments() if advanced_peak: self._state_changed("new_peak") self.log.debug( f"Total time for {len(blocks_to_validate)} blocks: {time.time() - pre_validate_start}, " f"advanced: {advanced_peak}" ) return True, advanced_peak, fork_height, (list(all_coin_changes.values()), all_hint_changes) async def _finish_sync(self): """ Finalize sync by setting sync mode to False, clearing all sync information, and adding any final blocks that we have finalized recently. """ self.log.info("long sync done") self.sync_store.set_long_sync(False) self.sync_store.set_sync_mode(False) self._state_changed("sync_mode") if self.server is None: return None peak: Optional[BlockRecord] = self.blockchain.get_peak() async with self._blockchain_lock_high_priority: await self.sync_store.clear_sync_info() peak_fb: FullBlock = await self.blockchain.get_full_peak() if peak is not None: mempool_new_peak_result, fns_peak_result = await self.peak_post_processing( peak_fb, peak, max(peak.height - 1, 0), None, [] ) await self.peak_post_processing_2( peak_fb, peak, max(peak.height - 1, 0), None, ([], {}), mempool_new_peak_result, fns_peak_result ) if peak is not None and self.weight_proof_handler is not None: await self.weight_proof_handler.get_proof_of_weight(peak.header_hash) self._state_changed("block") def has_valid_pool_sig(self, block: Union[UnfinishedBlock, FullBlock]): if ( block.foliage.foliage_block_data.pool_target == PoolTarget(self.constants.GENESIS_PRE_FARM_POOL_PUZZLE_HASH, uint32(0)) and block.foliage.prev_block_hash != self.constants.GENESIS_CHALLENGE and block.reward_chain_block.proof_of_space.pool_public_key is not None ): if not AugSchemeMPL.verify( block.reward_chain_block.proof_of_space.pool_public_key, bytes(block.foliage.foliage_block_data.pool_target), block.foliage.foliage_block_data.pool_signature, ): return False return True async def signage_point_post_processing( self, request: full_node_protocol.RespondSignagePoint, peer: ws.WSStaiDeltaConnection, ip_sub_slot: Optional[EndOfSubSlotBundle], ): self.log.info( f"⏲️ Finished signage point {request.index_from_challenge}/" f"{self.constants.NUM_SPS_SUB_SLOT}: " f"CC: {request.challenge_chain_vdf.output.get_hash()} " f"RC: {request.reward_chain_vdf.output.get_hash()} " f"Timelord reward: {bytes(request.timelord_reward_puzzle_hash).hex()} " ) self.signage_point_times[request.index_from_challenge] = time.time() sub_slot_tuple = self.full_node_store.get_sub_slot(request.challenge_chain_vdf.challenge) if sub_slot_tuple is not None: prev_challenge = sub_slot_tuple[0].challenge_chain.challenge_chain_end_of_slot_vdf.challenge else: prev_challenge = None # Notify nodes of the new signage point broadcast = full_node_protocol.NewSignagePointOrEndOfSubSlot( prev_challenge, request.challenge_chain_vdf.challenge, request.index_from_challenge, request.reward_chain_vdf.challenge, request.timelord_reward_puzzle_hash ) msg = make_msg(ProtocolMessageTypes.new_signage_point_or_end_of_sub_slot, broadcast) await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id) peak = self.blockchain.get_peak() if peak is not None and peak.height > self.constants.MAX_SUB_SLOT_BLOCKS: sub_slot_iters = peak.sub_slot_iters difficulty = uint64(peak.weight - self.blockchain.block_record(peak.prev_hash).weight) # Makes sure to potentially update the difficulty if we are past the peak (into a new sub-slot) assert ip_sub_slot is not None if request.challenge_chain_vdf.challenge != ip_sub_slot.challenge_chain.get_hash(): next_difficulty = self.blockchain.get_next_difficulty(peak.header_hash, True) next_sub_slot_iters = self.blockchain.get_next_slot_iters(peak.header_hash, True) difficulty = next_difficulty sub_slot_iters = next_sub_slot_iters else: difficulty = self.constants.DIFFICULTY_STARTING sub_slot_iters = self.constants.SUB_SLOT_ITERS_STARTING # Notify farmers of the new signage point broadcast_farmer = farmer_protocol.NewSignagePoint( request.challenge_chain_vdf.challenge, request.challenge_chain_vdf.output.get_hash(), request.reward_chain_vdf.output.get_hash(), difficulty, sub_slot_iters, request.index_from_challenge, request.timelord_reward_puzzle_hash ) msg = make_msg(ProtocolMessageTypes.new_signage_point, broadcast_farmer) await self.server.send_to_all([msg], NodeType.FARMER) async def peak_post_processing( self, block: FullBlock, record: BlockRecord, fork_height: uint32, peer: Optional[ws.WSStaiDeltaConnection], coin_changes: List[CoinRecord], ): """ Must be called under self.blockchain.lock. This updates the internal state of the full node with the latest peak information. It also notifies peers about the new peak. """ difficulty = self.blockchain.get_next_difficulty(record.header_hash, False) sub_slot_iters = self.blockchain.get_next_slot_iters(record.header_hash, False) self.log.info( f"🌱 Updated peak to height {record.height}, weight {record.weight}, " f"hh {record.header_hash}, " f"forked at {fork_height}, rh: {record.reward_infusion_new_challenge}, " f"total iters: {record.total_iters}, " f"overflow: {record.overflow}, " f"deficit: {record.deficit}, " f"difficulty: {difficulty}, " f"sub slot iters: {sub_slot_iters}, " f"Generator size: " f"{len(bytes(block.transactions_generator)) if block.transactions_generator else 'No tx'}, " f"Generator ref list size: " f"{len(block.transactions_generator_ref_list) if block.transactions_generator else 'No tx'}" ) sub_slots = await self.blockchain.get_sp_and_ip_sub_slots(record.header_hash) assert sub_slots is not None if not self.sync_store.get_sync_mode(): self.blockchain.clean_block_records() fork_block: Optional[BlockRecord] = None if fork_height != block.height - 1 and block.height != 0: # This is a reorg fork_block = self.blockchain.block_record(self.blockchain.height_to_hash(fork_height)) fns_peak_result: FullNodeStorePeakResult = self.full_node_store.new_peak( record, block, sub_slots[0], sub_slots[1], fork_block, self.blockchain, ) if fns_peak_result.new_signage_points is not None and peer is not None: for index, sp in fns_peak_result.new_signage_points: assert ( sp.cc_vdf is not None and sp.cc_proof is not None and sp.rc_vdf is not None and sp.rc_proof is not None and sp.timelord_reward_puzzle_hash is not None ) await self.signage_point_post_processing( RespondSignagePoint(index, sp.cc_vdf, sp.cc_proof, sp.rc_vdf, sp.rc_proof, sp.timelord_reward_puzzle_hash), peer, sub_slots[1] ) if sub_slots[1] is None: assert record.ip_sub_slot_total_iters(self.constants) == 0 # Ensure the signage point is also in the store, for consistency self.full_node_store.new_signage_point( record.signage_point_index, self.blockchain, record, record.sub_slot_iters, SignagePoint( block.reward_chain_block.challenge_chain_sp_vdf, block.challenge_chain_sp_proof, block.reward_chain_block.reward_chain_sp_vdf, block.reward_chain_sp_proof, block.foliage.foliage_block_data.timelord_reward_puzzle_hash ), skip_vdf_validation=True, ) # Update the mempool (returns successful pending transactions added to the mempool) mempool_new_peak_result: List[Tuple[SpendBundle, NPCResult, bytes32]] = await self.mempool_manager.new_peak( self.blockchain.get_peak(), coin_changes ) # Check if we detected a spent transaction, to load up our generator cache if block.transactions_generator is not None and self.full_node_store.previous_generator is None: generator_arg = detect_potential_template_generator(block.height, block.transactions_generator) if generator_arg: self.log.info(f"Saving previous generator for height {block.height}") self.full_node_store.previous_generator = generator_arg return mempool_new_peak_result, fns_peak_result async def peak_post_processing_2( self, block: FullBlock, record: BlockRecord, fork_height: uint32, peer: Optional[ws.WSStaiDeltaConnection], coin_changes: Tuple[List[CoinRecord], Dict[bytes, Dict[bytes32, CoinRecord]]], mempool_peak_result: List[Tuple[SpendBundle, NPCResult, bytes32]], fns_peak_result: FullNodeStorePeakResult, ): """ Does NOT need to be called under the blockchain lock. Handle other parts of post processing like communicating with peers """ for bundle, result, spend_name in mempool_peak_result: self.log.debug(f"Added transaction to mempool: {spend_name}") mempool_item = self.mempool_manager.get_mempool_item(spend_name) assert mempool_item is not None fees = mempool_item.fee assert fees >= 0 assert mempool_item.cost is not None new_tx = full_node_protocol.NewTransaction( spend_name, mempool_item.cost, uint64(bundle.fees()), ) msg = make_msg(ProtocolMessageTypes.new_transaction, new_tx) await self.server.send_to_all([msg], NodeType.FULL_NODE) timelord_reward_puzzle_hash: bytes32 = self.constants.TIMELORD_PUZZLE_HASH # If there were pending end of slots that happen after this peak, broadcast them if they are added if fns_peak_result.added_eos is not None: broadcast = full_node_protocol.NewSignagePointOrEndOfSubSlot( fns_peak_result.added_eos.challenge_chain.challenge_chain_end_of_slot_vdf.challenge, fns_peak_result.added_eos.challenge_chain.get_hash(), uint8(0), fns_peak_result.added_eos.reward_chain.end_of_slot_vdf.challenge, timelord_reward_puzzle_hash ) msg = make_msg(ProtocolMessageTypes.new_signage_point_or_end_of_sub_slot, broadcast) await self.server.send_to_all([msg], NodeType.FULL_NODE) # TODO: maybe add and broadcast new IPs as well if record.height % 1000 == 0: # Occasionally clear data in full node store to keep memory usage small self.full_node_store.clear_seen_unfinished_blocks() self.full_node_store.clear_old_cache_entries() if self.sync_store.get_sync_mode() is False: await self.send_peak_to_timelords(block) # Tell full nodes about the new peak msg = make_msg( ProtocolMessageTypes.new_peak, full_node_protocol.NewPeak( record.header_hash, record.height, record.weight, fork_height, block.reward_chain_block.get_unfinished().get_hash(), ), ) if peer is not None: await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id) else: await self.server.send_to_all([msg], NodeType.FULL_NODE) # Tell wallets about the new peak msg = make_msg( ProtocolMessageTypes.new_peak_wallet, wallet_protocol.NewPeakWallet( record.header_hash, record.height, record.weight, fork_height, ), ) await self.update_wallets(record.height, fork_height, record.header_hash, coin_changes) await self.server.send_to_all([msg], NodeType.WALLET) self._state_changed("new_peak") async def respond_block( self, respond_block: full_node_protocol.RespondBlock, peer: Optional[ws.WSStaiDeltaConnection] = None, ) -> Optional[Message]: """ Receive a full block from a peer full node (or ourselves). """ block: FullBlock = respond_block.block if self.sync_store.get_sync_mode(): return None # Adds the block to seen, and check if it's seen before (which means header is in memory) header_hash = block.header_hash if self.blockchain.contains_block(header_hash): return None pre_validation_result: Optional[PreValidationResult] = None if ( block.is_transaction_block() and block.transactions_info is not None and block.transactions_info.generator_root != bytes([0] * 32) and block.transactions_generator is None ): # This is the case where we already had the unfinished block, and asked for this block without # the transactions (since we already had them). Therefore, here we add the transactions. unfinished_rh: bytes32 = block.reward_chain_block.get_unfinished().get_hash() unf_block: Optional[UnfinishedBlock] = self.full_node_store.get_unfinished_block(unfinished_rh) if ( unf_block is not None and unf_block.transactions_generator is not None and unf_block.foliage_transaction_block == block.foliage_transaction_block ): pre_validation_result = self.full_node_store.get_unfinished_block_result(unfinished_rh) assert pre_validation_result is not None block = dataclasses.replace( block, transactions_generator=unf_block.transactions_generator, transactions_generator_ref_list=unf_block.transactions_generator_ref_list, ) else: # We still do not have the correct information for this block, perhaps there is a duplicate block # with the same unfinished block hash in the cache, so we need to fetch the correct one if peer is None: return None block_response: Optional[Any] = await peer.request_block( full_node_protocol.RequestBlock(block.height, True) ) if block_response is None or not isinstance(block_response, full_node_protocol.RespondBlock): self.log.warning( f"Was not able to fetch the correct block for height {block.height} {block_response}" ) return None new_block: FullBlock = block_response.block if new_block.foliage_transaction_block != block.foliage_transaction_block: self.log.warning(f"Received the wrong block for height {block.height} {new_block.header_hash}") return None assert new_block.transactions_generator is not None self.log.debug( f"Wrong info in the cache for bh {new_block.header_hash}, there might be multiple blocks from the " f"same farmer with the same pospace." ) # This recursion ends here, we cannot recurse again because transactions_generator is not None return await self.respond_block(block_response, peer) coin_changes: Tuple[List[CoinRecord], Dict[bytes, Dict[bytes32, CoinRecord]]] = ([], {}) mempool_new_peak_result, fns_peak_result = None, None async with self._blockchain_lock_high_priority: # After acquiring the lock, check again, because another asyncio thread might have added it if self.blockchain.contains_block(header_hash): return None validation_start = time.time() # Tries to add the block to the blockchain, if we already validated transactions, don't do it again npc_results = {} if pre_validation_result is not None and pre_validation_result.npc_result is not None: npc_results[block.height] = pre_validation_result.npc_result pre_validation_results = await self.blockchain.pre_validate_blocks_multiprocessing([block], npc_results) added: Optional[ReceiveBlockResult] = None pre_validation_time = time.time() - validation_start try: if pre_validation_results is None: raise ValueError(f"Failed to validate block {header_hash} height {block.height}") if pre_validation_results[0].error is not None: if Err(pre_validation_results[0].error) == Err.INVALID_PREV_BLOCK_HASH: added = ReceiveBlockResult.DISCONNECTED_BLOCK error_code: Optional[Err] = Err.INVALID_PREV_BLOCK_HASH fork_height: Optional[uint32] = None else: raise ValueError( f"Failed to validate block {header_hash} height " f"{block.height}: {Err(pre_validation_results[0].error).name}" ) else: result_to_validate = ( pre_validation_results[0] if pre_validation_result is None else pre_validation_result ) assert result_to_validate.required_iters == pre_validation_results[0].required_iters added, error_code, fork_height, coin_changes = await self.blockchain.receive_block( block, result_to_validate, None ) if ( self.full_node_store.previous_generator is not None and fork_height is not None and fork_height < self.full_node_store.previous_generator.block_height ): self.full_node_store.previous_generator = None if added == ReceiveBlockResult.ALREADY_HAVE_BLOCK: return None elif added == ReceiveBlockResult.INVALID_BLOCK: assert error_code is not None self.log.error(f"Block {header_hash} at height {block.height} is invalid with code {error_code}.") raise ConsensusError(error_code, header_hash) elif added == ReceiveBlockResult.DISCONNECTED_BLOCK: self.log.info(f"Disconnected block {header_hash} at height {block.height}") return None elif added == ReceiveBlockResult.NEW_PEAK: # Only propagate blocks which extend the blockchain (becomes one of the heads) new_peak: Optional[BlockRecord] = self.blockchain.get_peak() assert new_peak is not None and fork_height is not None mempool_new_peak_result, fns_peak_result = await self.peak_post_processing( block, new_peak, fork_height, peer, coin_changes[0] ) elif added == ReceiveBlockResult.ADDED_AS_ORPHAN: self.log.info( f"Received orphan block of height {block.height} rh " f"{block.reward_chain_block.get_hash()}" ) else: # Should never reach here, all the cases are covered raise RuntimeError(f"Invalid result from receive_block {added}") except asyncio.CancelledError: # We need to make sure to always call this method even when we get a cancel exception, to make sure # the node stays in sync new_peak = self.blockchain.get_peak() if added == ReceiveBlockResult.NEW_PEAK: assert new_peak is not None assert fork_height is not None await self.peak_post_processing(block, new_peak, fork_height, peer, coin_changes[0]) raise validation_time = time.time() - validation_start if mempool_new_peak_result is not None: assert new_peak is not None assert fork_height is not None assert fns_peak_result is not None await self.peak_post_processing_2( block, new_peak, fork_height, peer, coin_changes, mempool_new_peak_result, fns_peak_result ) percent_full_str = ( ( ", percent full: " + str(round(100.0 * float(block.transactions_info.cost) / self.constants.MAX_BLOCK_COST_CLVM, 3)) + "%" ) if block.transactions_info is not None else "" ) self.log.log( logging.WARNING if validation_time > 2 else logging.DEBUG, f"Block validation time: {validation_time:0.2f} seconds, " f"pre_validation time: {pre_validation_time:0.2f} seconds, " f"cost: {block.transactions_info.cost if block.transactions_info is not None else 'None'}" f"{percent_full_str}", ) # This code path is reached if added == ADDED_AS_ORPHAN or NEW_TIP peak = self.blockchain.get_peak() assert peak is not None # Removes all temporary data for old blocks clear_height = uint32(max(0, peak.height - 50)) self.full_node_store.clear_candidate_blocks_below(clear_height) self.full_node_store.clear_unfinished_blocks_below(clear_height) if peak.height % 1000 == 0 and not self.sync_store.get_sync_mode(): await self.sync_store.clear_sync_info() # Occasionally clear sync peer info self._state_changed("block") record = self.blockchain.block_record(block.header_hash) if self.weight_proof_handler is not None and record.sub_epoch_summary_included is not None: if self._segment_task is None or self._segment_task.done(): self._segment_task = asyncio.create_task(self.weight_proof_handler.create_prev_sub_epoch_segments()) return None async def respond_unfinished_block( self, respond_unfinished_block: full_node_protocol.RespondUnfinishedBlock, peer: Optional[ws.WSStaiDeltaConnection], farmed_block: bool = False, block_bytes: Optional[bytes] = None, ): """ We have received an unfinished block, either created by us, or from another peer. We can validate it and if it's a good block, propagate it to other peers and timelords. """ block = respond_unfinished_block.unfinished_block receive_time = time.time() if block.prev_header_hash != self.constants.GENESIS_CHALLENGE and not self.blockchain.contains_block( block.prev_header_hash ): # No need to request the parent, since the peer will send it to us anyway, via NewPeak self.log.debug("Received a disconnected unfinished block") return None # Adds the unfinished block to seen, and check if it's seen before, to prevent # processing it twice. This searches for the exact version of the unfinished block (there can be many different # foliages for the same trunk). This is intentional, to prevent DOS attacks. # Note that it does not require that this block was successfully processed if self.full_node_store.seen_unfinished_block(block.get_hash()): return None block_hash = block.reward_chain_block.get_hash() # This searched for the trunk hash (unfinished reward hash). If we have already added a block with the same # hash, return if self.full_node_store.get_unfinished_block(block_hash) is not None: return None peak: Optional[BlockRecord] = self.blockchain.get_peak() if peak is not None: if block.total_iters < peak.sp_total_iters(self.constants): # This means this unfinished block is pretty far behind, it will not add weight to our chain return None if block.prev_header_hash == self.constants.GENESIS_CHALLENGE: prev_b = None else: prev_b = self.blockchain.block_record(block.prev_header_hash) # Count the blocks in sub slot, and check if it's a new epoch if len(block.finished_sub_slots) > 0: num_blocks_in_ss = 1 # Curr else: curr = self.blockchain.try_block_record(block.prev_header_hash) num_blocks_in_ss = 2 # Curr and prev while (curr is not None) and not curr.first_in_sub_slot: curr = self.blockchain.try_block_record(curr.prev_hash) num_blocks_in_ss += 1 if num_blocks_in_ss > self.constants.MAX_SUB_SLOT_BLOCKS: # TODO: potentially allow overflow blocks here, which count for the next slot self.log.warning("Too many blocks added, not adding block") return None # The clvm generator and aggregate signature are validated outside of the lock, to allow other blocks and # transactions to get validated npc_result: Optional[NPCResult] = None pre_validation_time = None if block.transactions_generator is not None: pre_validation_start = time.time() assert block.transactions_info is not None try: block_generator: Optional[BlockGenerator] = await self.blockchain.get_block_generator(block) except ValueError: raise ConsensusError(Err.GENERATOR_REF_HAS_NO_GENERATOR) if block_generator is None: raise ConsensusError(Err.GENERATOR_REF_HAS_NO_GENERATOR) if block_bytes is None: block_bytes = bytes(block) npc_result = await self.blockchain.run_generator(block_bytes, block_generator) pre_validation_time = time.time() - pre_validation_start pairs_pks, pairs_msgs = pkm_pairs(npc_result.npc_list, self.constants.AGG_SIG_ME_ADDITIONAL_DATA) if not cached_bls.aggregate_verify( pairs_pks, pairs_msgs, block.transactions_info.aggregated_signature, True ): raise ConsensusError(Err.BAD_AGGREGATE_SIGNATURE) async with self._blockchain_lock_high_priority: # TODO: pre-validate VDFs outside of lock validation_start = time.time() validate_result = await self.blockchain.validate_unfinished_block(block, npc_result) if validate_result.error is not None: if validate_result.error == Err.COIN_AMOUNT_NEGATIVE.value: # TODO: remove in the future, hotfix for 1.1.5 peers to not disconnect older peers self.log.info(f"Consensus error {validate_result.error}, not disconnecting") return raise ConsensusError(Err(validate_result.error)) validation_time = time.time() - validation_start assert validate_result.required_iters is not None # Perform another check, in case we have already concurrently added the same unfinished block if self.full_node_store.get_unfinished_block(block_hash) is not None: return None if block.prev_header_hash == self.constants.GENESIS_CHALLENGE: height = uint32(0) else: height = uint32(self.blockchain.block_record(block.prev_header_hash).height + 1) ses: Optional[SubEpochSummary] = next_sub_epoch_summary( self.constants, self.blockchain, validate_result.required_iters, block, True, ) self.full_node_store.add_unfinished_block(height, block, validate_result) pre_validation_log = ( f"pre_validation time {pre_validation_time:0.4f}, " if pre_validation_time is not None else "" ) if farmed_block is True: self.log.info( f"🍀 ️Farmed unfinished_block {block_hash}, SP: {block.reward_chain_block.signage_point_index}, " f"validation time: {validation_time:0.4f} seconds, {pre_validation_log}" f"cost: {block.transactions_info.cost if block.transactions_info else 'None'} " ) else: percent_full_str = ( ( ", percent full: " + str(round(100.0 * float(block.transactions_info.cost) / self.constants.MAX_BLOCK_COST_CLVM, 3)) + "%" ) if block.transactions_info is not None else "" ) self.log.info( f"Added unfinished_block {block_hash}, not farmed by us," f" SP: {block.reward_chain_block.signage_point_index} farmer response time: " f"{receive_time - self.signage_point_times[block.reward_chain_block.signage_point_index]:0.4f}, " f"Pool pk {encode_puzzle_hash(block.foliage.foliage_block_data.pool_target.puzzle_hash, 'staidelta')}, " f"validation time: {validation_time:0.4f} seconds, {pre_validation_log}" f"cost: {block.transactions_info.cost if block.transactions_info else 'None'}" f"{percent_full_str}" ) sub_slot_iters, difficulty = get_next_sub_slot_iters_and_difficulty( self.constants, len(block.finished_sub_slots) > 0, prev_b, self.blockchain, ) if block.reward_chain_block.signage_point_index == 0: res = self.full_node_store.get_sub_slot(block.reward_chain_block.pos_ss_cc_challenge_hash) if res is None: if block.reward_chain_block.pos_ss_cc_challenge_hash == self.constants.GENESIS_CHALLENGE: rc_prev = self.constants.GENESIS_CHALLENGE else: self.log.warning(f"Do not have sub slot {block.reward_chain_block.pos_ss_cc_challenge_hash}") return None else: rc_prev = res[0].reward_chain.get_hash() else: assert block.reward_chain_block.reward_chain_sp_vdf is not None rc_prev = block.reward_chain_block.reward_chain_sp_vdf.challenge timelord_request = timelord_protocol.NewUnfinishedBlockTimelord( block.reward_chain_block, difficulty, sub_slot_iters, block.foliage, ses, rc_prev, validate_result.difficulty_coeff, ) timelord_msg = make_msg(ProtocolMessageTypes.new_unfinished_block_timelord, timelord_request) await self.server.send_to_all([timelord_msg], NodeType.TIMELORD) full_node_request = full_node_protocol.NewUnfinishedBlock(block.reward_chain_block.get_hash()) msg = make_msg(ProtocolMessageTypes.new_unfinished_block, full_node_request) if peer is not None: await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id) else: await self.server.send_to_all([msg], NodeType.FULL_NODE) self._state_changed("unfinished_block") async def new_infusion_point_vdf( self, request: timelord_protocol.NewInfusionPointVDF, timelord_peer: Optional[ws.WSStaiDeltaConnection] = None ) -> Optional[Message]: # Lookup unfinished blocks unfinished_block: Optional[UnfinishedBlock] = self.full_node_store.get_unfinished_block( request.unfinished_reward_hash ) if unfinished_block is None: self.log.warning( f"Do not have unfinished reward chain block {request.unfinished_reward_hash}, cannot finish." ) return None prev_b: Optional[BlockRecord] = None target_rc_hash = request.reward_chain_ip_vdf.challenge last_slot_cc_hash = request.challenge_chain_ip_vdf.challenge # Backtracks through end of slot objects, should work for multiple empty sub slots for eos, _, _ in reversed(self.full_node_store.finished_sub_slots): if eos is not None and eos.reward_chain.get_hash() == target_rc_hash: target_rc_hash = eos.reward_chain.end_of_slot_vdf.challenge if target_rc_hash == self.constants.GENESIS_CHALLENGE: prev_b = None else: # Find the prev block, starts looking backwards from the peak. target_rc_hash must be the hash of a block # and not an end of slot (since we just looked through the slots and backtracked) curr: Optional[BlockRecord] = self.blockchain.get_peak() for _ in range(10): if curr is None: break if curr.reward_infusion_new_challenge == target_rc_hash: # Found our prev block prev_b = curr break curr = self.blockchain.try_block_record(curr.prev_hash) # If not found, cache keyed on prev block if prev_b is None: self.full_node_store.add_to_future_ip(request) self.log.warning(f"Previous block is None, infusion point {request.reward_chain_ip_vdf.challenge}") return None finished_sub_slots: Optional[List[EndOfSubSlotBundle]] = self.full_node_store.get_finished_sub_slots( self.blockchain, prev_b, last_slot_cc_hash, ) if finished_sub_slots is None: return None sub_slot_iters, difficulty = get_next_sub_slot_iters_and_difficulty( self.constants, len(finished_sub_slots) > 0, prev_b, self.blockchain, ) if unfinished_block.reward_chain_block.pos_ss_cc_challenge_hash == self.constants.GENESIS_CHALLENGE: sub_slot_start_iters = uint128(0) else: ss_res = self.full_node_store.get_sub_slot(unfinished_block.reward_chain_block.pos_ss_cc_challenge_hash) if ss_res is None: self.log.warning(f"Do not have sub slot {unfinished_block.reward_chain_block.pos_ss_cc_challenge_hash}") return None _, _, sub_slot_start_iters = ss_res sp_total_iters = uint128( sub_slot_start_iters + calculate_sp_iters( self.constants, sub_slot_iters, unfinished_block.reward_chain_block.signage_point_index, ) ) block: FullBlock = unfinished_block_to_full_block( unfinished_block, request.challenge_chain_ip_vdf, request.challenge_chain_ip_proof, request.reward_chain_ip_vdf, request.reward_chain_ip_proof, request.infused_challenge_chain_ip_vdf, request.infused_challenge_chain_ip_proof, finished_sub_slots, prev_b, self.blockchain, sp_total_iters, difficulty, ) if not self.has_valid_pool_sig(block): self.log.warning("Trying to make a pre-farm block but height is not 0") return None try: await self.respond_block(full_node_protocol.RespondBlock(block)) except Exception as e: self.log.warning(f"Consensus error validating block: {e}") if timelord_peer is not None: # Only sends to the timelord who sent us this VDF, to reset them to the correct peak await self.send_peak_to_timelords(peer=timelord_peer) return None async def respond_end_of_sub_slot( self, request: full_node_protocol.RespondEndOfSubSlot, peer: ws.WSStaiDeltaConnection ) -> Tuple[Optional[Message], bool]: fetched_ss = self.full_node_store.get_sub_slot(request.end_of_slot_bundle.challenge_chain.get_hash()) # We are not interested in sub-slots which have the same challenge chain but different reward chain. If there # is a reorg, we will find out through the broadcast of blocks instead. if fetched_ss is not None: # Already have the sub-slot return None, True async with self.timelord_lock: fetched_ss = self.full_node_store.get_sub_slot( request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge ) if ( (fetched_ss is None) and request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge != self.constants.GENESIS_CHALLENGE ): # If we don't have the prev, request the prev instead full_node_request = full_node_protocol.RequestSignagePointOrEndOfSubSlot( request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge, uint8(0), bytes([0] * 32), ) return ( make_msg(ProtocolMessageTypes.request_signage_point_or_end_of_sub_slot, full_node_request), False, ) timelord_reward_puzzle_hash: bytes32 = self.constants.TIMELORD_PUZZLE_HASH peak = self.blockchain.get_peak() if peak is not None and peak.height > 2: next_sub_slot_iters = self.blockchain.get_next_slot_iters(peak.header_hash, True) next_difficulty = self.blockchain.get_next_difficulty(peak.header_hash, True) timelord_reward_puzzle_hash = peak.timelord_puzzle_hash else: next_sub_slot_iters = self.constants.SUB_SLOT_ITERS_STARTING next_difficulty = self.constants.DIFFICULTY_STARTING # Adds the sub slot and potentially get new infusions new_infusions = self.full_node_store.new_finished_sub_slot( request.end_of_slot_bundle, self.blockchain, peak, await self.blockchain.get_full_peak(), ) # It may be an empty list, even if it's not None. Not None means added successfully if new_infusions is not None: self.log.info( f"⏲️ Finished sub slot, SP {self.constants.NUM_SPS_SUB_SLOT}/{self.constants.NUM_SPS_SUB_SLOT}, " f"{request.end_of_slot_bundle.challenge_chain.get_hash()}, " f"number of sub-slots: {len(self.full_node_store.finished_sub_slots)}, " f"RC hash: {request.end_of_slot_bundle.reward_chain.get_hash()}, " f"Deficit {request.end_of_slot_bundle.reward_chain.deficit}" f"Timelord reward {timelord_reward_puzzle_hash}" ) # Notify full nodes of the new sub-slot broadcast = full_node_protocol.NewSignagePointOrEndOfSubSlot( request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge, request.end_of_slot_bundle.challenge_chain.get_hash(), uint8(0), request.end_of_slot_bundle.reward_chain.end_of_slot_vdf.challenge, timelord_reward_puzzle_hash ) msg = make_msg(ProtocolMessageTypes.new_signage_point_or_end_of_sub_slot, broadcast) await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id) for infusion in new_infusions: await self.new_infusion_point_vdf(infusion) # Notify farmers of the new sub-slot broadcast_farmer = farmer_protocol.NewSignagePoint( request.end_of_slot_bundle.challenge_chain.get_hash(), request.end_of_slot_bundle.challenge_chain.get_hash(), request.end_of_slot_bundle.reward_chain.get_hash(), next_difficulty, next_sub_slot_iters, uint8(0), timelord_reward_puzzle_hash ) msg = make_msg(ProtocolMessageTypes.new_signage_point, broadcast_farmer) await self.server.send_to_all([msg], NodeType.FARMER) return None, True else: self.log.info( f"End of slot not added CC challenge " f"{request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge}" ) return None, False async def respond_transaction( self, transaction: SpendBundle, spend_name: bytes32, peer: Optional[ws.WSStaiDeltaConnection] = None, test: bool = False, tx_bytes: Optional[bytes] = None, ) -> Tuple[MempoolInclusionStatus, Optional[Err]]: if self.sync_store.get_sync_mode(): return MempoolInclusionStatus.FAILED, Err.NO_TRANSACTIONS_WHILE_SYNCING if not test and not (await self.synced()): return MempoolInclusionStatus.FAILED, Err.NO_TRANSACTIONS_WHILE_SYNCING if self.mempool_manager.seen(spend_name): return MempoolInclusionStatus.FAILED, Err.ALREADY_INCLUDING_TRANSACTION self.mempool_manager.add_and_maybe_pop_seen(spend_name) self.log.debug(f"Processing transaction: {spend_name}") # Ignore if syncing if self.sync_store.get_sync_mode(): status = MempoolInclusionStatus.FAILED error: Optional[Err] = Err.NO_TRANSACTIONS_WHILE_SYNCING self.mempool_manager.remove_seen(spend_name) else: try: cost_result = await self.mempool_manager.pre_validate_spendbundle(transaction, tx_bytes, spend_name) except ValidationError as e: self.mempool_manager.remove_seen(spend_name) return MempoolInclusionStatus.FAILED, e.code except Exception as e: self.mempool_manager.remove_seen(spend_name) raise e async with self._blockchain_lock_low_priority: if self.mempool_manager.get_spendbundle(spend_name) is not None: self.mempool_manager.remove_seen(spend_name) return MempoolInclusionStatus.FAILED, Err.ALREADY_INCLUDING_TRANSACTION cost, status, error = await self.mempool_manager.add_spendbundle(transaction, cost_result, spend_name) if status == MempoolInclusionStatus.SUCCESS: self.log.debug( f"Added transaction to mempool: {spend_name} mempool size: " f"{self.mempool_manager.mempool.total_mempool_cost} normalized " f"{self.mempool_manager.mempool.total_mempool_cost / 5000000}" ) # Only broadcast successful transactions, not pending ones. Otherwise it's a DOS # vector. mempool_item = self.mempool_manager.get_mempool_item(spend_name) assert mempool_item is not None fees = mempool_item.fee assert fees >= 0 assert cost is not None new_tx = full_node_protocol.NewTransaction( spend_name, cost, fees, ) msg = make_msg(ProtocolMessageTypes.new_transaction, new_tx) if peer is None: await self.server.send_to_all([msg], NodeType.FULL_NODE) else: await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id) self.not_dropped_tx += 1 else: self.mempool_manager.remove_seen(spend_name) self.log.debug( f"Wasn't able to add transaction with id {spend_name}, " f"status {status} error: {error}" ) return status, error async def _needs_compact_proof( self, vdf_info: VDFInfo, header_block: HeaderBlock, field_vdf: CompressibleVDFField ) -> bool: if field_vdf == CompressibleVDFField.CC_EOS_VDF: for sub_slot in header_block.finished_sub_slots: if sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf == vdf_info: if ( sub_slot.proofs.challenge_chain_slot_proof.witness_type == 0 and sub_slot.proofs.challenge_chain_slot_proof.normalized_to_identity ): return False return True if field_vdf == CompressibleVDFField.ICC_EOS_VDF: for sub_slot in header_block.finished_sub_slots: if ( sub_slot.infused_challenge_chain is not None and sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf == vdf_info ): assert sub_slot.proofs.infused_challenge_chain_slot_proof is not None if ( sub_slot.proofs.infused_challenge_chain_slot_proof.witness_type == 0 and sub_slot.proofs.infused_challenge_chain_slot_proof.normalized_to_identity ): return False return True if field_vdf == CompressibleVDFField.CC_SP_VDF: if header_block.reward_chain_block.challenge_chain_sp_vdf is None: return False if vdf_info == header_block.reward_chain_block.challenge_chain_sp_vdf: assert header_block.challenge_chain_sp_proof is not None if ( header_block.challenge_chain_sp_proof.witness_type == 0 and header_block.challenge_chain_sp_proof.normalized_to_identity ): return False return True if field_vdf == CompressibleVDFField.CC_IP_VDF: if vdf_info == header_block.reward_chain_block.challenge_chain_ip_vdf: if ( header_block.challenge_chain_ip_proof.witness_type == 0 and header_block.challenge_chain_ip_proof.normalized_to_identity ): return False return True return False async def _can_accept_compact_proof( self, vdf_info: VDFInfo, vdf_proof: VDFProof, height: uint32, header_hash: bytes32, field_vdf: CompressibleVDFField, ) -> bool: """ - Checks if the provided proof is indeed compact. - Checks if proof verifies given the vdf_info from the start of sub-slot. - Checks if the provided vdf_info is correct, assuming it refers to the start of sub-slot. - Checks if the existing proof was non-compact. Ignore this proof if we already have a compact proof. """ is_fully_compactified = await self.block_store.is_fully_compactified(header_hash) if is_fully_compactified is None or is_fully_compactified: self.log.info(f"Already compactified block: {header_hash}. Ignoring.") return False if vdf_proof.witness_type > 0 or not vdf_proof.normalized_to_identity: self.log.error(f"Received vdf proof is not compact: {vdf_proof}.") return False if not vdf_proof.is_valid(self.constants, ClassgroupElement.get_default_element(), vdf_info): self.log.error(f"Received compact vdf proof is not valid: {vdf_proof}.") return False header_block = await self.blockchain.get_header_block_by_height(height, header_hash, tx_filter=False) if header_block is None: self.log.error(f"Can't find block for given compact vdf. Height: {height} Header hash: {header_hash}") return False is_new_proof = await self._needs_compact_proof(vdf_info, header_block, field_vdf) if not is_new_proof: self.log.info(f"Duplicate compact proof. Height: {height}. Header hash: {header_hash}.") return is_new_proof async def _replace_proof( self, vdf_info: VDFInfo, vdf_proof: VDFProof, height: uint32, field_vdf: CompressibleVDFField, ) -> bool: full_blocks = await self.block_store.get_full_blocks_at([height]) assert len(full_blocks) > 0 replaced = False expected_header_hash = self.blockchain.height_to_hash(height) for block in full_blocks: new_block = None if block.header_hash != expected_header_hash: continue block_record = await self.blockchain.get_block_record_from_db(expected_header_hash) assert block_record is not None if field_vdf == CompressibleVDFField.CC_EOS_VDF: for index, sub_slot in enumerate(block.finished_sub_slots): if sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf == vdf_info: new_proofs = dataclasses.replace(sub_slot.proofs, challenge_chain_slot_proof=vdf_proof) new_subslot = dataclasses.replace(sub_slot, proofs=new_proofs) new_finished_subslots = block.finished_sub_slots new_finished_subslots[index] = new_subslot new_block = dataclasses.replace(block, finished_sub_slots=new_finished_subslots) break if field_vdf == CompressibleVDFField.ICC_EOS_VDF: for index, sub_slot in enumerate(block.finished_sub_slots): if ( sub_slot.infused_challenge_chain is not None and sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf == vdf_info ): new_proofs = dataclasses.replace(sub_slot.proofs, infused_challenge_chain_slot_proof=vdf_proof) new_subslot = dataclasses.replace(sub_slot, proofs=new_proofs) new_finished_subslots = block.finished_sub_slots new_finished_subslots[index] = new_subslot new_block = dataclasses.replace(block, finished_sub_slots=new_finished_subslots) break if field_vdf == CompressibleVDFField.CC_SP_VDF: if block.reward_chain_block.challenge_chain_sp_vdf == vdf_info: assert block.challenge_chain_sp_proof is not None new_block = dataclasses.replace(block, challenge_chain_sp_proof=vdf_proof) if field_vdf == CompressibleVDFField.CC_IP_VDF: if block.reward_chain_block.challenge_chain_ip_vdf == vdf_info: new_block = dataclasses.replace(block, challenge_chain_ip_proof=vdf_proof) if new_block is None: continue async with self.db_wrapper.lock: await self.block_store.add_full_block(new_block.header_hash, new_block, block_record) await self.block_store.db_wrapper.commit_transaction() replaced = True return replaced async def respond_compact_proof_of_time(self, request: timelord_protocol.RespondCompactProofOfTime): field_vdf = CompressibleVDFField(int(request.field_vdf)) if not await self._can_accept_compact_proof( request.vdf_info, request.vdf_proof, request.height, request.header_hash, field_vdf ): return None async with self.blockchain.compact_proof_lock: replaced = await self._replace_proof(request.vdf_info, request.vdf_proof, request.height, field_vdf) if not replaced: self.log.error(f"Could not replace compact proof: {request.height}") return None self.log.info(f"Replaced compact proof at height {request.height}") msg = make_msg( ProtocolMessageTypes.new_compact_vdf, full_node_protocol.NewCompactVDF(request.height, request.header_hash, request.field_vdf, request.vdf_info), ) if self.server is not None: await self.server.send_to_all([msg], NodeType.FULL_NODE) async def new_compact_vdf(self, request: full_node_protocol.NewCompactVDF, peer: ws.WSStaiDeltaConnection): is_fully_compactified = await self.block_store.is_fully_compactified(request.header_hash) if is_fully_compactified is None or is_fully_compactified: return False header_block = await self.blockchain.get_header_block_by_height( request.height, request.header_hash, tx_filter=False ) if header_block is None: return None field_vdf = CompressibleVDFField(int(request.field_vdf)) if await self._needs_compact_proof(request.vdf_info, header_block, field_vdf): peer_request = full_node_protocol.RequestCompactVDF( request.height, request.header_hash, request.field_vdf, request.vdf_info ) response = await peer.request_compact_vdf(peer_request, timeout=10) if response is not None and isinstance(response, full_node_protocol.RespondCompactVDF): await self.respond_compact_vdf(response, peer) async def request_compact_vdf(self, request: full_node_protocol.RequestCompactVDF, peer: ws.WSStaiDeltaConnection): header_block = await self.blockchain.get_header_block_by_height( request.height, request.header_hash, tx_filter=False ) if header_block is None: return None vdf_proof: Optional[VDFProof] = None field_vdf = CompressibleVDFField(int(request.field_vdf)) if field_vdf == CompressibleVDFField.CC_EOS_VDF: for sub_slot in header_block.finished_sub_slots: if sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf == request.vdf_info: vdf_proof = sub_slot.proofs.challenge_chain_slot_proof break if field_vdf == CompressibleVDFField.ICC_EOS_VDF: for sub_slot in header_block.finished_sub_slots: if ( sub_slot.infused_challenge_chain is not None and sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf == request.vdf_info ): vdf_proof = sub_slot.proofs.infused_challenge_chain_slot_proof break if ( field_vdf == CompressibleVDFField.CC_SP_VDF and header_block.reward_chain_block.challenge_chain_sp_vdf == request.vdf_info ): vdf_proof = header_block.challenge_chain_sp_proof if ( field_vdf == CompressibleVDFField.CC_IP_VDF and header_block.reward_chain_block.challenge_chain_ip_vdf == request.vdf_info ): vdf_proof = header_block.challenge_chain_ip_proof if vdf_proof is None or vdf_proof.witness_type > 0 or not vdf_proof.normalized_to_identity: self.log.error(f"{peer} requested compact vdf we don't have, height: {request.height}.") return None compact_vdf = full_node_protocol.RespondCompactVDF( request.height, request.header_hash, request.field_vdf, request.vdf_info, vdf_proof, ) msg = make_msg(ProtocolMessageTypes.respond_compact_vdf, compact_vdf) await peer.send_message(msg) async def respond_compact_vdf(self, request: full_node_protocol.RespondCompactVDF, peer: ws.WSStaiDeltaConnection): field_vdf = CompressibleVDFField(int(request.field_vdf)) if not await self._can_accept_compact_proof( request.vdf_info, request.vdf_proof, request.height, request.header_hash, field_vdf ): return None async with self.blockchain.compact_proof_lock: if self.blockchain.seen_compact_proofs(request.vdf_info, request.height): return None replaced = await self._replace_proof(request.vdf_info, request.vdf_proof, request.height, field_vdf) if not replaced: self.log.error(f"Could not replace compact proof: {request.height}") return None msg = make_msg( ProtocolMessageTypes.new_compact_vdf, full_node_protocol.NewCompactVDF(request.height, request.header_hash, request.field_vdf, request.vdf_info), ) if self.server is not None: await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id) async def broadcast_uncompact_blocks( self, uncompact_interval_scan: int, target_uncompact_proofs: int, sanitize_weight_proof_only: bool ): try: while not self._shut_down: while self.sync_store.get_sync_mode(): if self._shut_down: return None await asyncio.sleep(30) broadcast_list: List[timelord_protocol.RequestCompactProofOfTime] = [] self.log.info("Getting random heights for bluebox to compact") heights = await self.block_store.get_random_not_compactified(target_uncompact_proofs) self.log.info("Heights found for bluebox to compact: [%s]" % ", ".join(map(str, heights))) for h in heights: headers = await self.blockchain.get_header_blocks_in_range(h, h, tx_filter=False) records: Dict[bytes32, BlockRecord] = {} if sanitize_weight_proof_only: records = await self.blockchain.get_block_records_in_range(h, h) for header in headers.values(): expected_header_hash = self.blockchain.height_to_hash(header.height) if header.header_hash != expected_header_hash: continue if sanitize_weight_proof_only: assert header.header_hash in records record = records[header.header_hash] for sub_slot in header.finished_sub_slots: if ( sub_slot.proofs.challenge_chain_slot_proof.witness_type > 0 or not sub_slot.proofs.challenge_chain_slot_proof.normalized_to_identity ): broadcast_list.append( timelord_protocol.RequestCompactProofOfTime( sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf, header.header_hash, header.height, uint8(CompressibleVDFField.CC_EOS_VDF), ) ) if sub_slot.proofs.infused_challenge_chain_slot_proof is not None and ( sub_slot.proofs.infused_challenge_chain_slot_proof.witness_type > 0 or not sub_slot.proofs.infused_challenge_chain_slot_proof.normalized_to_identity ): assert sub_slot.infused_challenge_chain is not None broadcast_list.append( timelord_protocol.RequestCompactProofOfTime( sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf, header.header_hash, header.height, uint8(CompressibleVDFField.ICC_EOS_VDF), ) ) # Running in 'sanitize_weight_proof_only' ignores CC_SP_VDF and CC_IP_VDF # unless this is a challenge block. if sanitize_weight_proof_only: if not record.is_challenge_block(self.constants): continue if header.challenge_chain_sp_proof is not None and ( header.challenge_chain_sp_proof.witness_type > 0 or not header.challenge_chain_sp_proof.normalized_to_identity ): assert header.reward_chain_block.challenge_chain_sp_vdf is not None broadcast_list.append( timelord_protocol.RequestCompactProofOfTime( header.reward_chain_block.challenge_chain_sp_vdf, header.header_hash, header.height, uint8(CompressibleVDFField.CC_SP_VDF), ) ) if ( header.challenge_chain_ip_proof.witness_type > 0 or not header.challenge_chain_ip_proof.normalized_to_identity ): broadcast_list.append( timelord_protocol.RequestCompactProofOfTime( header.reward_chain_block.challenge_chain_ip_vdf, header.header_hash, header.height, uint8(CompressibleVDFField.CC_IP_VDF), ) ) if len(broadcast_list) > target_uncompact_proofs: broadcast_list = broadcast_list[:target_uncompact_proofs] if self.sync_store.get_sync_mode(): continue if self.server is not None: self.log.info(f"Broadcasting {len(broadcast_list)} items to the bluebox") msgs = [] for new_pot in broadcast_list: msg = make_msg(ProtocolMessageTypes.request_compact_proof_of_time, new_pot) msgs.append(msg) await self.server.send_to_all(msgs, NodeType.TIMELORD) await asyncio.sleep(uncompact_interval_scan) except Exception as e: error_stack = traceback.format_exc() self.log.error(f"Exception in broadcast_uncompact_blocks: {e}") self.log.error(f"Exception Stack: {error_stack}") async def node_next_block_check( peer: ws.WSStaiDeltaConnection, potential_peek: uint32, blockchain: BlockchainInterface ) -> bool: block_response: Optional[Any] = await peer.request_block(full_node_protocol.RequestBlock(potential_peek, True)) if block_response is not None and isinstance(block_response, full_node_protocol.RespondBlock): peak = blockchain.get_peak() if peak is not None and block_response.block.prev_header_hash == peak.header_hash: return True return False
#!/usr/bin/python3 """ Primary module """ # pylint: disable=wildcard-import import logging import signal from time import time, sleep from threading import Thread, Event from yaml import load, FullLoader import typing as tp import humanfriendly import argparse from pymeterreader.device_lib import BaseReader, Sample, strip, SmlReader, PlainReader, Bme280Reader from pymeterreader.gateway import * PARSER = argparse.ArgumentParser(description='MeterReader reads out supported devices ' 'and forwards the data to a middleware ' '(e.g. see https://volkszaehler.org/).') PARSER.add_argument('-d', '--debug', help='Make process chatty.', action='store_true') PARSER.add_argument('-c', '--configfile', help="User for Jama login", default='/etc/meter_reader.yaml') def humanfriendly_time_parser(humanfriendly_input: tp.Union[int, float, str]) -> int: """ Convert a time definition from a string to a int. :param humanfriendly_input: Strings like '5s', '10m', '24h' or '1d' :returns the input time in seconds as int """ if isinstance(humanfriendly_input, str): return humanfriendly.parse_timespan(humanfriendly_input) return int(humanfriendly_input) class MeterReaderNode: """ MeterReaderNode represents a mapping of a meter's channels to uuids. """ class ChannelInfo: def __init__(self, uuid, interval, factor, last_upload, last_value): """ Channel info structure :param uuid: uuid of db entry to feed :param interval: interval between readings in seconds :param factor: multiply to original values, e.g. to conver kWh to Wh :param last_upload: time of last upload to middleware :param last_value: last value in middleware """ # pylint: disable=too-many-arguments self.uuid = uuid self.interval = interval self.factor = factor self.last_upload = last_upload self.last_value = last_value def __init__(self, channels: tp.Dict[str, tp.Tuple[str, tp.Union[int, float], tp.Union[int, float]]], reader: BaseReader, gateway: BaseGateway): """ Reader node object connects one or more channels from a meter to uuids and upload interval times. :param channels: map channel ids to uuids, interval times and value multiplication factors :param reader: MeterReader object used to poll the meter :param gateway: Gateway object used for uploads to the middleware """ self.__channels = {} for channel, values in channels.items(): middleware_entry = gateway.get(values[0]) if middleware_entry is None: logging.warning(f"Cannot get last entry for {values[0]}") last_upload = -1 last_value = -1 else: last_upload = middleware_entry[0] last_value = middleware_entry[1] self.__channels[channel] = MeterReaderNode.ChannelInfo(uuid=values[0], interval=values[1], factor=values[2], last_upload=last_upload, last_value=last_value) self.__reader = reader self.__gateway = gateway @property def poll_interval(self): """ This property indicates the optimal interval to poll this node :return: greatest common divisor """ def hcf_naive(a, b): if b == 0: return a return hcf_naive(b, a % b) intervals = [channel.interval for channel in self.__channels.values()] while len(intervals) > 1: intervals = [hcf_naive(intervals[i], intervals[i + 1]) if i + 1 < len(intervals) else intervals[i] for i in range(0, len(intervals), 2)] return intervals[0] @staticmethod def __cast_value(value_orig: tp.Union[str, int, float], factor) -> tp.Union[int, float]: """ Cast to int if possible, else float :param value_orig: value as str, int or float :return: value as int or float """ if isinstance(value_orig, str): value = int(value_orig) if value_orig.isnumeric() else float(value_orig) else: value = value_orig return value * factor def poll_and_push(self, sample: Sample = None) -> bool: """ Poll a channel and push it by it's uuid :param sample: optional sample data (skip polling) :returns True if successful """ # pylint: disable=too-many-arguments, too-many-nested-blocks now = time() posted = 0 if sample is None: sample = self.__reader.poll() if sample: for entry in sample.channels: cur_unit = entry.get('unit', '') try: if cur_unit: cur_channel = strip(entry.get('objName', '')) if cur_channel in self.__channels: cur_value = self.__cast_value(entry.get('value', ''), self.__channels[cur_channel].factor) if self.__channels[cur_channel].last_upload + self.__channels[cur_channel].interval <= now: # Push hourly interpolated values to enable line plotting in volkszaehler middleware if self.__gateway.interpolate: self.__push_interpolated_data(cur_value, now, self.__channels[cur_channel]) if self.__gateway.post(self.__channels[cur_channel].uuid, cur_value, sample.time): self.__channels[cur_channel].last_upload = now self.__channels[cur_channel].last_value = cur_value logging.debug(f"POST {cur_value}{cur_unit} to {self.__channels[cur_channel].uuid}") posted += 1 else: logging.error(f"POST to {self.__channels[cur_channel].uuid} failed!") else: logging.info(f"Skipping upload for {self.__channels[cur_channel].uuid}.") posted += 1 except ValueError: logging.error(f'Unable to cast {entry.get('value', 'N/A')}.') continue else: logging.error("No data from meter. Skipping interval.") return posted == len(self.__channels) def __push_interpolated_data(self, cur_value: tp.Union[float, int], cur_time: float, channel: ChannelInfo): hours = round((cur_time - channel.last_upload) / 3600) diff = cur_value - channel.last_value if hours <= 24: for hour in range(1, hours): btw_time = channel.last_upload + hour * 3600 btw_value = channel.last_value + diff * (hour / hours) self.__gateway.post(channel.uuid, btw_value, btw_time) class MeterReaderTask(Thread): class Timer(Thread): """ Precise event timer """ def __init__(self, interval: float or int, event: Event): Thread.__init__(self) self.__interval = interval self.__event = event self.daemon = True self.__stop_event = Event() def run(self): while not self.__stop_event.is_set(): sleep(self.__interval) self.__event.set() def stop(self): self.__stop_event.set() def __init__(self, meter_reader_node: MeterReaderNode): """ Worker thread will call "poll and push" as often as required. :param meter_reader_node: """ Thread.__init__(self) self.__meter_reader_mode = meter_reader_node self.__timer = Event() self.stop_event = Event() self.__timer_thread = self.Timer(self.__meter_reader_mode.poll_interval, self.__timer) self.daemon = True self.__timer_thread.start() super().start() def __block(self): self.__timer.wait() self.__timer.clear() return True def stop(self): """ Call to stop the thread """ self.stop_event.set() self.__timer.set() def run(self): """ Start the worker thread. """ self.__block() # initial sample polled during initialization while not self.stop_event.is_set(): self.__meter_reader_mode.poll_and_push() self.__block() def map_configuration(config: dict) -> tp.List[MeterReaderNode]: # noqa MC0001 """ Parsed configuration :param config: dict from :return: """ # pylint: disable=too-many-locals, too-many-nested-blocks meter_reader_nodes = [] if 'devices' in config and 'middleware' in config: try: if config.get('middleware').get('type') == 'volkszaehler': gateway = VolkszaehlerGateway(config.get('middleware').get('middleware_url'), config.get('middleware').get('interpolate', True)) else: logging.error(f'Middleware "{config.get('middleware').get('type')}" not supported!') gateway = None if gateway: for device in config.get('devices').values(): meter_id = strip(str(device.pop('id'))) protocol = strip(device.pop('protocol')) channels = device.pop('channels') if protocol == 'SML': reader = SmlReader(meter_id, **device) elif protocol == 'PLAIN': reader = PlainReader(meter_id, **device) elif protocol == 'BME280': reader = Bme280Reader(meter_id, **device) else: logging.error(f'Unsupported protocol {protocol}') reader = None sample = reader.poll() if sample is not None: available_channels = {} for variable in sample.channels: obj_name = variable.get('objName', '') for channel_name, channel in channels.items(): interval = humanfriendly_time_parser(channel.get('interval', '1h')) uuid = channel.get('uuid') factor = channel.get('factor', 1) if strip(str(channel_name)) in strip(str(obj_name)): # Replacing config string with exact match available_channels[obj_name] = (uuid, interval, factor) if available_channels: meter_reader_node = MeterReaderNode(available_channels, reader, gateway) # Perform first push to middleware if meter_reader_node.poll_and_push(sample): meter_reader_nodes.append(meter_reader_node) else: logging.error(f"Not registering node for meter id {reader.meter_id}.") else: logging.warning(f"Cannot register channels for meter {meter_id}.") else: logging.warning(f"Could not read meter id {meter_id} using protocol {protocol}.") except KeyError as err: logging.error(f"Error while processing configuration: {err}") else: logging.error("Config file is incomplete.") return meter_reader_nodes class MeterReader: """ Meter Reader main class Loads configuration and starts worker threads. """ def __init__(self, config_file): signal.signal(signal.SIGINT, self.__keyboard_interrupt_handler) config = self.__read_config_file(config_file) meter_reader_nodes = map_configuration(config) logging.info(f"Starting {len(meter_reader_nodes)} worker threads...") self.worker_threads = [] for meter_reader_node in meter_reader_nodes: self.worker_threads.append(MeterReaderTask(meter_reader_node)) def block_main(self): for task in self.worker_threads: task.join() def __keyboard_interrupt_handler(self, stop_signal, frame): del stop_signal del frame logging.info("<< STOP REQUEST >>") for task in self.worker_threads: task.stop() @staticmethod def __read_config_file(file_name: str) -> dict: """ Read a yaml config file and return it as dict :param file_name: name of configuration yaml file :return: dict with all configuration entries """ try: with open(file_name, 'r') as conf_file: return load(conf_file, Loader=FullLoader) except OSError as err: if isinstance(err, FileNotFoundError): logging.error(f"File {file_name} can't be found.") elif isinstance(err, PermissionError): logging.error(f"Not allowed to read {file_name}.") else: logging.error(f'Error occurred when trying to open {file_name}.') return {} def main(): ARGS = PARSER.parse_args() logging.basicConfig(level=logging.DEBUG if ARGS.debug else logging.INFO) meter_reader = MeterReader(ARGS.configfile) meter_reader.block_main() if __name__ == '__main__': main()
#!/usr/bin/python3 """ Primary module """ # pylint: disable=wildcard-import import logging import signal from time import time, sleep from threading import Thread, Event from yaml import load, FullLoader import typing as tp import humanfriendly import argparse from pymeterreader.device_lib import BaseReader, Sample, strip, SmlReader, PlainReader, Bme280Reader from pymeterreader.gateway import * PARSER = argparse.ArgumentParser(description='MeterReader reads out supported devices ' 'and forwards the data to a middleware ' '(e.g. see https://volkszaehler.org/).') PARSER.add_argument('-d', '--debug', help='Make process chatty.', action='store_true') PARSER.add_argument('-c', '--configfile', help="User for Jama login", default='/etc/meter_reader.yaml') def humanfriendly_time_parser(humanfriendly_input: tp.Union[int, float, str]) -> int: """ Convert a time definition from a string to a int. :param humanfriendly_input: Strings like '5s', '10m', '24h' or '1d' :returns the input time in seconds as int """ if isinstance(humanfriendly_input, str): return humanfriendly.parse_timespan(humanfriendly_input) return int(humanfriendly_input) class MeterReaderNode: """ MeterReaderNode represents a mapping of a meter's channels to uuids. """ class ChannelInfo: def __init__(self, uuid, interval, factor, last_upload, last_value): """ Channel info structure :param uuid: uuid of db entry to feed :param interval: interval between readings in seconds :param factor: multiply to original values, e.g. to conver kWh to Wh :param last_upload: time of last upload to middleware :param last_value: last value in middleware """ # pylint: disable=too-many-arguments self.uuid = uuid self.interval = interval self.factor = factor self.last_upload = last_upload self.last_value = last_value def __init__(self, channels: tp.Dict[str, tp.Tuple[str, tp.Union[int, float], tp.Union[int, float]]], reader: BaseReader, gateway: BaseGateway): """ Reader node object connects one or more channels from a meter to uuids and upload interval times. :param channels: map channel ids to uuids, interval times and value multiplication factors :param reader: MeterReader object used to poll the meter :param gateway: Gateway object used for uploads to the middleware """ self.__channels = {} for channel, values in channels.items(): middleware_entry = gateway.get(values[0]) if middleware_entry is None: logging.warning(f"Cannot get last entry for {values[0]}") last_upload = -1 last_value = -1 else: last_upload = middleware_entry[0] last_value = middleware_entry[1] self.__channels[channel] = MeterReaderNode.ChannelInfo(uuid=values[0], interval=values[1], factor=values[2], last_upload=last_upload, last_value=last_value) self.__reader = reader self.__gateway = gateway @property def poll_interval(self): """ This property indicates the optimal interval to poll this node :return: greatest common divisor """ def hcf_naive(a, b): if b == 0: return a return hcf_naive(b, a % b) intervals = [channel.interval for channel in self.__channels.values()] while len(intervals) > 1: intervals = [hcf_naive(intervals[i], intervals[i + 1]) if i + 1 < len(intervals) else intervals[i] for i in range(0, len(intervals), 2)] return intervals[0] @staticmethod def __cast_value(value_orig: tp.Union[str, int, float], factor) -> tp.Union[int, float]: """ Cast to int if possible, else float :param value_orig: value as str, int or float :return: value as int or float """ if isinstance(value_orig, str): value = int(value_orig) if value_orig.isnumeric() else float(value_orig) else: value = value_orig return value * factor def poll_and_push(self, sample: Sample = None) -> bool: """ Poll a channel and push it by it's uuid :param sample: optional sample data (skip polling) :returns True if successful """ # pylint: disable=too-many-arguments, too-many-nested-blocks now = time() posted = 0 if sample is None: sample = self.__reader.poll() if sample: for entry in sample.channels: cur_unit = entry.get('unit', '') try: if cur_unit: cur_channel = strip(entry.get('objName', '')) if cur_channel in self.__channels: cur_value = self.__cast_value(entry.get('value', ''), self.__channels[cur_channel].factor) if self.__channels[cur_channel].last_upload + self.__channels[cur_channel].interval <= now: # Push hourly interpolated values to enable line plotting in volkszaehler middleware if self.__gateway.interpolate: self.__push_interpolated_data(cur_value, now, self.__channels[cur_channel]) if self.__gateway.post(self.__channels[cur_channel].uuid, cur_value, sample.time): self.__channels[cur_channel].last_upload = now self.__channels[cur_channel].last_value = cur_value logging.debug(f"POST {cur_value}{cur_unit} to {self.__channels[cur_channel].uuid}") posted += 1 else: logging.error(f"POST to {self.__channels[cur_channel].uuid} failed!") else: logging.info(f"Skipping upload for {self.__channels[cur_channel].uuid}.") posted += 1 except ValueError: logging.error(f'Unable to cast {entry.get("value", "N/A")}.') continue else: logging.error("No data from meter. Skipping interval.") return posted == len(self.__channels) def __push_interpolated_data(self, cur_value: tp.Union[float, int], cur_time: float, channel: ChannelInfo): hours = round((cur_time - channel.last_upload) / 3600) diff = cur_value - channel.last_value if hours <= 24: for hour in range(1, hours): btw_time = channel.last_upload + hour * 3600 btw_value = channel.last_value + diff * (hour / hours) self.__gateway.post(channel.uuid, btw_value, btw_time) class MeterReaderTask(Thread): class Timer(Thread): """ Precise event timer """ def __init__(self, interval: float or int, event: Event): Thread.__init__(self) self.__interval = interval self.__event = event self.daemon = True self.__stop_event = Event() def run(self): while not self.__stop_event.is_set(): sleep(self.__interval) self.__event.set() def stop(self): self.__stop_event.set() def __init__(self, meter_reader_node: MeterReaderNode): """ Worker thread will call "poll and push" as often as required. :param meter_reader_node: """ Thread.__init__(self) self.__meter_reader_mode = meter_reader_node self.__timer = Event() self.stop_event = Event() self.__timer_thread = self.Timer(self.__meter_reader_mode.poll_interval, self.__timer) self.daemon = True self.__timer_thread.start() super().start() def __block(self): self.__timer.wait() self.__timer.clear() return True def stop(self): """ Call to stop the thread """ self.stop_event.set() self.__timer.set() def run(self): """ Start the worker thread. """ self.__block() # initial sample polled during initialization while not self.stop_event.is_set(): self.__meter_reader_mode.poll_and_push() self.__block() def map_configuration(config: dict) -> tp.List[MeterReaderNode]: # noqa MC0001 """ Parsed configuration :param config: dict from :return: """ # pylint: disable=too-many-locals, too-many-nested-blocks meter_reader_nodes = [] if 'devices' in config and 'middleware' in config: try: if config.get('middleware').get('type') == 'volkszaehler': gateway = VolkszaehlerGateway(config.get('middleware').get('middleware_url'), config.get('middleware').get('interpolate', True)) else: logging.error(f'Middleware "{config.get("middleware").get("type")}" not supported!') gateway = None if gateway: for device in config.get('devices').values(): meter_id = strip(str(device.pop('id'))) protocol = strip(device.pop('protocol')) channels = device.pop('channels') if protocol == 'SML': reader = SmlReader(meter_id, **device) elif protocol == 'PLAIN': reader = PlainReader(meter_id, **device) elif protocol == 'BME280': reader = Bme280Reader(meter_id, **device) else: logging.error(f'Unsupported protocol {protocol}') reader = None sample = reader.poll() if sample is not None: available_channels = {} for variable in sample.channels: obj_name = variable.get('objName', '') for channel_name, channel in channels.items(): interval = humanfriendly_time_parser(channel.get('interval', '1h')) uuid = channel.get('uuid') factor = channel.get('factor', 1) if strip(str(channel_name)) in strip(str(obj_name)): # Replacing config string with exact match available_channels[obj_name] = (uuid, interval, factor) if available_channels: meter_reader_node = MeterReaderNode(available_channels, reader, gateway) # Perform first push to middleware if meter_reader_node.poll_and_push(sample): meter_reader_nodes.append(meter_reader_node) else: logging.error(f"Not registering node for meter id {reader.meter_id}.") else: logging.warning(f"Cannot register channels for meter {meter_id}.") else: logging.warning(f"Could not read meter id {meter_id} using protocol {protocol}.") except KeyError as err: logging.error(f"Error while processing configuration: {err}") else: logging.error("Config file is incomplete.") return meter_reader_nodes class MeterReader: """ Meter Reader main class Loads configuration and starts worker threads. """ def __init__(self, config_file): signal.signal(signal.SIGINT, self.__keyboard_interrupt_handler) config = self.__read_config_file(config_file) meter_reader_nodes = map_configuration(config) logging.info(f"Starting {len(meter_reader_nodes)} worker threads...") self.worker_threads = [] for meter_reader_node in meter_reader_nodes: self.worker_threads.append(MeterReaderTask(meter_reader_node)) def block_main(self): for task in self.worker_threads: task.join() def __keyboard_interrupt_handler(self, stop_signal, frame): del stop_signal del frame logging.info("<< STOP REQUEST >>") for task in self.worker_threads: task.stop() @staticmethod def __read_config_file(file_name: str) -> dict: """ Read a yaml config file and return it as dict :param file_name: name of configuration yaml file :return: dict with all configuration entries """ try: with open(file_name, 'r') as conf_file: return load(conf_file, Loader=FullLoader) except OSError as err: if isinstance(err, FileNotFoundError): logging.error(f"File {file_name} can't be found.") elif isinstance(err, PermissionError): logging.error(f"Not allowed to read {file_name}.") else: logging.error(f'Error occurred when trying to open {file_name}.') return {} def main(): ARGS = PARSER.parse_args() logging.basicConfig(level=logging.DEBUG if ARGS.debug else logging.INFO) meter_reader = MeterReader(ARGS.configfile) meter_reader.block_main() if __name__ == '__main__': main()
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 from collections import OrderedDict from functools import singledispatch from .array import is_numeric_array from .op import trace_ops from .program import OpProgram def _debug(x): return f"{type(x).__module__.split(".")[0]}.{type(x).__name__}({hex(id(x))[2:]})" def trace_function(fn, kwargs: dict, *, allow_constants=False): """ Traces function to an :class:`~funsor.ops.program.OpProgram` that runs on backend values. Example:: # Create a function involving ops. def fn(a, b, x): return ops.add(ops.matmul(a, x), b) # Evaluate via Funsor substitution. data = dict(a=randn(3, 3), b=randn(3), x=randn(3)) expected = fn(**data) # Alternatively evaluate via a program. program = trace_function(expr, data) actual = program(**data) assert (acutal == expected).all() :param Funsor expr: A funsor expression to evaluate. :returns: An op program. :rtype: ~funsor.ops.program.OpProgram """ # Extract kwargs. assert isinstance(kwargs, dict) assert all(is_variable(v) for v in kwargs.values()) kwarg_ids = {id(v) for v in kwargs.values()} assert len(kwarg_ids) == len(kwargs), "repeated inputs" # Trace the function. with trace_ops(is_variable) as trace: root = fn(**kwargs) assert is_variable(root) # Extract relevant portion of trace. dag = OrderedDict({id(root): (root, None, None)}) for result, op, args in reversed(trace.values()): # backward if id(result) not in dag or not is_variable(result): continue # not needed for arg in args: dag.setdefault(id(arg), (arg, None, None)) dag[id(result)] = result, op, args anf = list(reversed(dag.values())) # forward # Collect constants (leaves). ids = {} constants = [] for result, op, args in anf: if op is None and id(result) not in kwarg_ids: ids[id(result)] = len(ids) constants.append(result) if not allow_constants and is_variable(result): raise ValueError(f"Found constant: {repr(result)}") # Collect inputs (leaves). inputs = [] for name, value in kwargs.items(): ids[id(value)] = len(ids) inputs.append(name) # Collect operations to be computed (internal nodes). operations = [] for result, op, args in anf: if id(result) in ids: continue # constant or free variable assert op is not None ids[id(result)] = len(ids) arg_ids = tuple(ids[id(arg)] for arg in args) operations.append((op, arg_ids)) return OpProgram(constants, inputs, operations) @singledispatch def is_variable(x): """ An object is variable if it is either backend arrays or is a nested tuple containing at least one backend array. """ return is_numeric_array(x) @is_variable.register(int) def _is_variable_int(x): return type(x) is not int # allow numpy types @is_variable.register(float) def _is_variable_float(x): return type(x) is not float # allow numpy types @is_variable.register(tuple) def _is_variable_tuple(x): return any(map(is_variable, x)) __all__ = [ "trace_function", ]
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 from collections import OrderedDict from functools import singledispatch from .array import is_numeric_array from .op import trace_ops from .program import OpProgram def _debug(x): return f"{type(x).__module__.split('.')[0]}.{type(x).__name__}({hex(id(x))[2:]})" def trace_function(fn, kwargs: dict, *, allow_constants=False): """ Traces function to an :class:`~funsor.ops.program.OpProgram` that runs on backend values. Example:: # Create a function involving ops. def fn(a, b, x): return ops.add(ops.matmul(a, x), b) # Evaluate via Funsor substitution. data = dict(a=randn(3, 3), b=randn(3), x=randn(3)) expected = fn(**data) # Alternatively evaluate via a program. program = trace_function(expr, data) actual = program(**data) assert (acutal == expected).all() :param Funsor expr: A funsor expression to evaluate. :returns: An op program. :rtype: ~funsor.ops.program.OpProgram """ # Extract kwargs. assert isinstance(kwargs, dict) assert all(is_variable(v) for v in kwargs.values()) kwarg_ids = {id(v) for v in kwargs.values()} assert len(kwarg_ids) == len(kwargs), "repeated inputs" # Trace the function. with trace_ops(is_variable) as trace: root = fn(**kwargs) assert is_variable(root) # Extract relevant portion of trace. dag = OrderedDict({id(root): (root, None, None)}) for result, op, args in reversed(trace.values()): # backward if id(result) not in dag or not is_variable(result): continue # not needed for arg in args: dag.setdefault(id(arg), (arg, None, None)) dag[id(result)] = result, op, args anf = list(reversed(dag.values())) # forward # Collect constants (leaves). ids = {} constants = [] for result, op, args in anf: if op is None and id(result) not in kwarg_ids: ids[id(result)] = len(ids) constants.append(result) if not allow_constants and is_variable(result): raise ValueError(f"Found constant: {repr(result)}") # Collect inputs (leaves). inputs = [] for name, value in kwargs.items(): ids[id(value)] = len(ids) inputs.append(name) # Collect operations to be computed (internal nodes). operations = [] for result, op, args in anf: if id(result) in ids: continue # constant or free variable assert op is not None ids[id(result)] = len(ids) arg_ids = tuple(ids[id(arg)] for arg in args) operations.append((op, arg_ids)) return OpProgram(constants, inputs, operations) @singledispatch def is_variable(x): """ An object is variable if it is either backend arrays or is a nested tuple containing at least one backend array. """ return is_numeric_array(x) @is_variable.register(int) def _is_variable_int(x): return type(x) is not int # allow numpy types @is_variable.register(float) def _is_variable_float(x): return type(x) is not float # allow numpy types @is_variable.register(tuple) def _is_variable_tuple(x): return any(map(is_variable, x)) __all__ = [ "trace_function", ]
# -*- coding: utf8 -*- import json import random import socket from collections import OrderedDict from time import sleep import requests from fake_useragent import UserAgent import TickerConfig from agency.agency_tools import proxy from config import logger def _set_header_default(): header_dict = OrderedDict() # header_dict["Accept"] = "application/json, text/plain, */*" header_dict["Accept-Encoding"] = "gzip, deflate" header_dict[ "User-Agent"] = _set_user_agent() header_dict["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8" header_dict["Origin"] = "https://kyfw.12306.cn" header_dict["Connection"] = "keep-alive" return header_dict def _set_user_agent(): # try: # user_agent = UserAgent(verify_ssl=False).random # return user_agent # except: # print("请求头设置失败,使用默认请求头") # return 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.' + str( # random.randint(5000, 7000)) + '.0 Safari/537.36' return "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36" class HTTPClient(object): def __init__(self, is_proxy, cdnList=None): """ cdnList试试切换不包括查询的cdn,防止查询cdn污染登陆和下单cdn :param method: :param headers: Must be a dict. Such as headers={'Content_Type':'text/html'} """ self.initS() self._cdn = None self.cdnList = cdnList self._proxies = None if is_proxy == 1: self.proxy = proxy() self._proxies = self.proxy.setProxy() # print(u"设置当前代理ip为 {}, 请注意代理ip是否可用!!!!!请注意代理ip是否可用!!!!!请注意代理ip是否可用!!!!!".format(self._proxies)) def initS(self): self._s = requests.Session() self._s.headers.update(_set_header_default()) return self def set_cookies(self, kwargs): """ 设置cookies :param kwargs: :return: """ for kwarg in kwargs: for k, v in kwarg.items(): self._s.cookies.set(k, v) def get_cookies(self): """ 获取cookies :return: """ return self._s.cookies.values() def del_cookies(self): """ 删除所有的key :return: """ self._s.cookies.clear() def del_cookies_by_key(self, key): """ 删除指定key的session :return: """ self._s.cookies.set(key, None) def setHeaders(self, headers): self._s.headers.update(headers) return self def resetHeaders(self): self._s.headers.clear() self._s.headers.update(_set_header_default()) def getHeadersHost(self): return self._s.headers["Host"] def setHeadersHost(self, host): self._s.headers.update({"Host": host}) return self def setHeadersUserAgent(self): self._s.headers.update({"User-Agent": _set_user_agent()}) def getHeadersUserAgent(self): return self._s.headers["User-Agent"] def getHeadersReferer(self): return self._s.headers["Referer"] def setHeadersReferer(self, referer): self._s.headers.update({"Referer": referer}) return self @property def cdn(self): return self._cdn @cdn.setter def cdn(self, cdn): self._cdn = cdn def send(self, urls, data=None, **kwargs): """send request to url.If response 200,return response, else return None.""" allow_redirects = False is_logger = urls.get("is_logger", False) req_url = urls.get("req_url", "") re_try = urls.get("re_try", 0) s_time = urls.get("s_time", 0) is_cdn = urls.get("is_cdn", False) is_test_cdn = urls.get("is_test_cdn", False) error_data = {"code": 99999, "message": u"重试次数达到上限"} if data: method = "post" self.setHeaders({"Content-Length": "{0}".format(len(data))}) else: method = "get" self.resetHeaders() if TickerConfig.RANDOM_AGENT == 1: self.setHeadersUserAgent() self.setHeadersReferer(urls["Referer"]) if is_logger: logger.log( u"url: {0}\n入参: {1}\n请求方式: {2}\n".format(req_url, data, method)) self.setHeadersHost(urls["Host"]) if is_test_cdn: url_host = self._cdn elif is_cdn: if self._cdn: # print(u"当前请求cdn为{}".format(self._cdn)) url_host = self._cdn else: url_host = urls["Host"] else: url_host = urls["Host"] http = urls.get("httpType") or "https" for i in range(re_try): try: # sleep(urls["s_time"]) if "s_time" in urls else sleep(0.001) sleep(s_time) try: requests.packages.urllib3.disable_warnings() except: pass response = self._s.request(method=method, timeout=5, proxies=self._proxies, url=http + "://" + url_host + req_url, data=data, allow_redirects=allow_redirects, verify=False, **kwargs) if response.status_code == 200 or response.status_code == 302: if urls.get("not_decode", False): return response.content if response.content: if is_logger: logger.log( u"出参:{0}".format(response.content.decode())) if urls["is_json"]: return json.loads( response.content.decode() if isinstance(response.content, bytes) else response.content) else: return response.content.decode("utf8", "ignore") if isinstance(response.content, bytes) else response.content else: print(f"url: {urls["req_url"]}返回参数为空, 接口状态码: {response.status_code}") logger.log( u"url: {} 返回参数为空".format(urls["req_url"])) if self.cdnList: # 如果下单或者登陆出现cdn 302的情况,立马切换cdn url_host = self.cdnList.pop(random.randint(0, 4)) continue else: sleep(urls["re_time"]) except (requests.exceptions.Timeout, requests.exceptions.ReadTimeout, requests.exceptions.ConnectionError): pass except socket.error: pass return error_data
# -*- coding: utf8 -*- import json import random import socket from collections import OrderedDict from time import sleep import requests from fake_useragent import UserAgent import TickerConfig from agency.agency_tools import proxy from config import logger def _set_header_default(): header_dict = OrderedDict() # header_dict["Accept"] = "application/json, text/plain, */*" header_dict["Accept-Encoding"] = "gzip, deflate" header_dict[ "User-Agent"] = _set_user_agent() header_dict["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8" header_dict["Origin"] = "https://kyfw.12306.cn" header_dict["Connection"] = "keep-alive" return header_dict def _set_user_agent(): # try: # user_agent = UserAgent(verify_ssl=False).random # return user_agent # except: # print("请求头设置失败,使用默认请求头") # return 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.' + str( # random.randint(5000, 7000)) + '.0 Safari/537.36' return "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36" class HTTPClient(object): def __init__(self, is_proxy, cdnList=None): """ cdnList试试切换不包括查询的cdn,防止查询cdn污染登陆和下单cdn :param method: :param headers: Must be a dict. Such as headers={'Content_Type':'text/html'} """ self.initS() self._cdn = None self.cdnList = cdnList self._proxies = None if is_proxy == 1: self.proxy = proxy() self._proxies = self.proxy.setProxy() # print(u"设置当前代理ip为 {}, 请注意代理ip是否可用!!!!!请注意代理ip是否可用!!!!!请注意代理ip是否可用!!!!!".format(self._proxies)) def initS(self): self._s = requests.Session() self._s.headers.update(_set_header_default()) return self def set_cookies(self, kwargs): """ 设置cookies :param kwargs: :return: """ for kwarg in kwargs: for k, v in kwarg.items(): self._s.cookies.set(k, v) def get_cookies(self): """ 获取cookies :return: """ return self._s.cookies.values() def del_cookies(self): """ 删除所有的key :return: """ self._s.cookies.clear() def del_cookies_by_key(self, key): """ 删除指定key的session :return: """ self._s.cookies.set(key, None) def setHeaders(self, headers): self._s.headers.update(headers) return self def resetHeaders(self): self._s.headers.clear() self._s.headers.update(_set_header_default()) def getHeadersHost(self): return self._s.headers["Host"] def setHeadersHost(self, host): self._s.headers.update({"Host": host}) return self def setHeadersUserAgent(self): self._s.headers.update({"User-Agent": _set_user_agent()}) def getHeadersUserAgent(self): return self._s.headers["User-Agent"] def getHeadersReferer(self): return self._s.headers["Referer"] def setHeadersReferer(self, referer): self._s.headers.update({"Referer": referer}) return self @property def cdn(self): return self._cdn @cdn.setter def cdn(self, cdn): self._cdn = cdn def send(self, urls, data=None, **kwargs): """send request to url.If response 200,return response, else return None.""" allow_redirects = False is_logger = urls.get("is_logger", False) req_url = urls.get("req_url", "") re_try = urls.get("re_try", 0) s_time = urls.get("s_time", 0) is_cdn = urls.get("is_cdn", False) is_test_cdn = urls.get("is_test_cdn", False) error_data = {"code": 99999, "message": u"重试次数达到上限"} if data: method = "post" self.setHeaders({"Content-Length": "{0}".format(len(data))}) else: method = "get" self.resetHeaders() if TickerConfig.RANDOM_AGENT == 1: self.setHeadersUserAgent() self.setHeadersReferer(urls["Referer"]) if is_logger: logger.log( u"url: {0}\n入参: {1}\n请求方式: {2}\n".format(req_url, data, method)) self.setHeadersHost(urls["Host"]) if is_test_cdn: url_host = self._cdn elif is_cdn: if self._cdn: # print(u"当前请求cdn为{}".format(self._cdn)) url_host = self._cdn else: url_host = urls["Host"] else: url_host = urls["Host"] http = urls.get("httpType") or "https" for i in range(re_try): try: # sleep(urls["s_time"]) if "s_time" in urls else sleep(0.001) sleep(s_time) try: requests.packages.urllib3.disable_warnings() except: pass response = self._s.request(method=method, timeout=5, proxies=self._proxies, url=http + "://" + url_host + req_url, data=data, allow_redirects=allow_redirects, verify=False, **kwargs) if response.status_code == 200 or response.status_code == 302: if urls.get("not_decode", False): return response.content if response.content: if is_logger: logger.log( u"出参:{0}".format(response.content.decode())) if urls["is_json"]: return json.loads( response.content.decode() if isinstance(response.content, bytes) else response.content) else: return response.content.decode("utf8", "ignore") if isinstance(response.content, bytes) else response.content else: print(f"url: {urls['req_url']}返回参数为空, 接口状态码: {response.status_code}") logger.log( u"url: {} 返回参数为空".format(urls["req_url"])) if self.cdnList: # 如果下单或者登陆出现cdn 302的情况,立马切换cdn url_host = self.cdnList.pop(random.randint(0, 4)) continue else: sleep(urls["re_time"]) except (requests.exceptions.Timeout, requests.exceptions.ReadTimeout, requests.exceptions.ConnectionError): pass except socket.error: pass return error_data
import logging from PyQt5.QtWidgets import QPlainTextEdit, QGroupBox, QVBoxLayout from ..python_core.appdirs import get_app_log_dir import pathlib as pl import time import sys # solution copied from https://stackoverflow.com/questions/28655198/best-way-to-display-logs-in-pyqt class QPlainTextEditLogger(QPlainTextEdit, logging.Handler): def __init__(self, parent): super(QPlainTextEdit, self).__init__(parent) super(logging.Handler, self).__init__() self.setReadOnly(True) def emit(self, record): msg = self.format(record) text_cursor = self.textCursor() text_cursor.insertText(f"{msg}\n") self.setTextCursor(text_cursor) class LoggerGroupBox(QGroupBox): def __init__(self, parent, location_dir=None): super().__init__("Event Log", parent) if location_dir is None: location_dir = get_app_log_dir() log_dir = pl.Path(location_dir) log_dir.mkdir(exist_ok=True, parents=True) log_file = str(log_dir / f"started_at_{time.strftime("%Y-%m-%d-%H-%M-%S")}.log") vbox = QVBoxLayout(self) self.log_pte = QPlainTextEditLogger(parent) self.log_pte.setLevel(level=logging.INFO) vbox.addWidget(self.log_pte) view_logger = logging.getLogger("VIEW") view_logger.setLevel(level=logging.INFO) formatter = logging.Formatter("%(asctime)s [VIEW] [%(levelname)-5.5s] %(message)s") self.log_file_handler = logging.FileHandler(log_file) self.log_file_handler.setFormatter(formatter) self.log_file_handler.setLevel(level=logging.DEBUG) view_logger.addHandler(self.log_file_handler) self.log_pte.setFormatter(formatter) view_logger.addHandler(self.log_pte) stream_handler = logging.StreamHandler(sys.stdout) stream_handler.setLevel(level=logging.INFO) stream_handler.setFormatter(formatter) view_logger.addHandler(stream_handler) def __del__(self): root_logger = logging.getLogger("VIEW") root_logger.removeHandler(self.log_pte) root_logger.removeHandler(self.log_file_handler)
import logging from PyQt5.QtWidgets import QPlainTextEdit, QGroupBox, QVBoxLayout from ..python_core.appdirs import get_app_log_dir import pathlib as pl import time import sys # solution copied from https://stackoverflow.com/questions/28655198/best-way-to-display-logs-in-pyqt class QPlainTextEditLogger(QPlainTextEdit, logging.Handler): def __init__(self, parent): super(QPlainTextEdit, self).__init__(parent) super(logging.Handler, self).__init__() self.setReadOnly(True) def emit(self, record): msg = self.format(record) text_cursor = self.textCursor() text_cursor.insertText(f"{msg}\n") self.setTextCursor(text_cursor) class LoggerGroupBox(QGroupBox): def __init__(self, parent, location_dir=None): super().__init__("Event Log", parent) if location_dir is None: location_dir = get_app_log_dir() log_dir = pl.Path(location_dir) log_dir.mkdir(exist_ok=True, parents=True) log_file = str(log_dir / f"started_at_{time.strftime('%Y-%m-%d-%H-%M-%S')}.log") vbox = QVBoxLayout(self) self.log_pte = QPlainTextEditLogger(parent) self.log_pte.setLevel(level=logging.INFO) vbox.addWidget(self.log_pte) view_logger = logging.getLogger("VIEW") view_logger.setLevel(level=logging.INFO) formatter = logging.Formatter("%(asctime)s [VIEW] [%(levelname)-5.5s] %(message)s") self.log_file_handler = logging.FileHandler(log_file) self.log_file_handler.setFormatter(formatter) self.log_file_handler.setLevel(level=logging.DEBUG) view_logger.addHandler(self.log_file_handler) self.log_pte.setFormatter(formatter) view_logger.addHandler(self.log_pte) stream_handler = logging.StreamHandler(sys.stdout) stream_handler.setLevel(level=logging.INFO) stream_handler.setFormatter(formatter) view_logger.addHandler(stream_handler) def __del__(self): root_logger = logging.getLogger("VIEW") root_logger.removeHandler(self.log_pte) root_logger.removeHandler(self.log_file_handler)
# -*- coding: utf-8 -*- '''The file contains functions for working with the database''' import base64 import time from os.path import isfile import sqlalchemy as sa from aiohttp_session.cookie_storage import EncryptedCookieStorage from envparse import env # Reading settings file if isfile('.env'): env.read_envfile('.env') # Database connection parameters obtained from .env def get_dsn(): '''DB connection string :return: ''' return f"dbname={env.str("PG_DATABASE")} user={env.str("PG_USERNAME")} " \ f"password={env.str("PG_PASSWORD")} host={env.str("PG_SERVER")}" def get_sekret_key(): '''SECRET_KEY for the session :return: ''' return EncryptedCookieStorage(base64.urlsafe_b64decode(env.str('SECRET_KEY'))) def get_timestamp_str(): '''TimeStamp string of the current timestamp for the base :return: ''' return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) metadata = sa.MetaData() # Table user tb_user = sa.Table( 'user', metadata, sa.Column('id', sa.Integer, primary_key=True, autoincrement=True), sa.Column('email', sa.String(255)), sa.Column('password', sa.String(255)), sa.Column('name', sa.String(255)), sa.Column('surname', sa.String(255)), sa.Column('create_at', sa.TIMESTAMP), sa.Column('delete_at', sa.TIMESTAMP)) # Table user_rule tb_user_rule = sa.Table( 'user_rule', metadata, sa.Column('id', sa.Integer, primary_key=True, autoincrement=True), sa.Column('rule', None, sa.ForeignKey('tb_rule.id')), sa.Column('user', None, sa.ForeignKey('tb_user.id'))) # Table rule tb_rule = sa.Table( 'rule', metadata, sa.Column('id', sa.Integer, primary_key=True, autoincrement=True), sa.Column('rule', sa.String(255)), sa.Column('comment', sa.String(255))) async def get_user_by_email(engine, email): '''User existence check :param engine: DB connection :param email: user email :return: a list of users ''' async with engine.acquire() as conn: async for row in conn.execute(tb_user.select().where(tb_user.c.email == email)): return { 'id': row[0], 'email': row[1], 'password': row[2], 'name': row[3], 'surname': row[4], 'create_at': row[5], 'delete_at': row[6] } async def get_user_rules(engine, user_id): '''Obtaining user rights by id :param engine: DB connection :param user_id: user id :return: user rights list ''' async with engine.acquire() as conn: rules = [] join = sa.join(tb_rule, tb_user_rule, tb_rule.c.id == tb_user_rule.c.rule) async for row in conn.execute( tb_rule.select().select_from(join).where(tb_user_rule.c.user == user_id)): rules.append(row[1]) return rules async def get_user_info(engine, user_id): '''Getting user data by id :param engine: DB connection :param user_id: user id :return: user information ''' async with engine.acquire() as conn: async for row in conn.execute(tb_user.select().where(tb_user.c.id == user_id)): return { 'id': row[0], 'email': row[1], 'password': row[2], 'name': row[3], 'surname': row[4], 'rules': await get_user_rules(engine=engine, user_id=user_id) } async def get_users(engine, admin): '''Retrieving user data :param engine: DB connection :param admin: Request data for admin user :return: a list of users ''' async with engine.acquire() as conn: users = [] where = '' if admin else 'WHERE u.delete_at is null' async for row in await conn.execute( f'''SELECT u.id, u.email, u.password, u.name, u.surname, u.delete_at, ARRAY( SELECT r.rule FROM "user_rule" as ur LEFT JOIN "rule" as r on ur.rule = r.id WHERE ur.user = u.id ) as "rules" FROM "user" as u {where} ORDER BY u.id;'''): # If the data is requested not by the Admin, then we do not show the admins if not admin and 'admin' in row[6]: continue users.append({ 'id': row[0], 'email': row[1], 'password': row[2], 'name': row[3], 'surname': row[4], 'delete': row[5] is not None, 'rules': row[6] }) return users async def get_rules(engine): '''Obtaining rights data :param engine: DB connection :return: list of rights ''' async with engine.acquire() as conn: rules = {} async for row in conn.execute(tb_rule.select()): # {'admin': 0} rules[row[1]] = row[0] return rules async def set_rules_for_user(engine, user_id, data): '''Setting / changing user rights :param engine: DB connection :param user_id: user id :param data: data for setting :return: ''' rules = await get_rules(engine) user_rules = await get_user_rules(engine, user_id) for rule, rule_id in rules.items(): # The user already has the current role and from the form flew to True # if rule in user_rules and data.get(rule, False) is True: # The user does not have the current role and from the form flew to False # if rule not in user_rules and data.get(rule, False) is False: # The user has a role, but False has arrived from the form - delete if rule in user_rules and data.get(rule, False) is False: async with engine.acquire() as conn: await conn.execute( tb_user_rule.delete(None) .where(tb_user_rule.c.user == user_id) .where(tb_user_rule.c.rule == rule_id)) # The user does not have roles, but True has arrived from the form - add if rule not in user_rules and data.get(rule, False) is True: async with engine.acquire() as conn: await conn.execute(tb_user_rule.insert(None).values(user=user_id, rule=rule_id)) async def set_delete_at_for_user(engine, user_id, restore=False): '''Delete user by id :param engine: DB connection :param user_id: id of the user to be deleted :return: ''' timestamp = 'null' if restore else f"'{get_timestamp_str()}'" async with engine.acquire() as conn: await conn.execute(f'''UPDATE "user" SET delete_at={timestamp} WHERE id={user_id};''') async def create_user(engine, data): '''User creation :param engine: DB connection :param data: new user data :return: ''' async with engine.acquire() as conn: user = await get_user_by_email(engine=engine, email=data['email']) if user is not None: raise Warning('A user with this email already exists.') user_id = await conn.scalar( tb_user.insert(None).values( email=data['email'], password=data['password'], name=data['name'], surname=data['surname'], create_at=get_timestamp_str())) await set_rules_for_user(engine=engine, user_id=user_id, data=data) async def update_user(engine, data): '''User data update :param engine: DB connection :param data: user data to update :return: ''' async with engine.acquire() as conn: # Check that the email matches the current one, or that it is unique in the database user = await get_user_by_email(engine=engine, email=data['email']) if user is not None and int(user['id']) != int(data['id']): raise Warning('A user with this email already exists') await conn.execute( sa.update(tb_user) .values({ 'email': data['email'], 'password': data['password'], 'name': data['name'], 'surname': data['surname'] }) .where(tb_user.c.id == int(data['id']))) await set_rules_for_user(engine=engine, user_id=int(data['id']), data=data)
# -*- coding: utf-8 -*- '''The file contains functions for working with the database''' import base64 import time from os.path import isfile import sqlalchemy as sa from aiohttp_session.cookie_storage import EncryptedCookieStorage from envparse import env # Reading settings file if isfile('.env'): env.read_envfile('.env') # Database connection parameters obtained from .env def get_dsn(): '''DB connection string :return: ''' return f"dbname={env.str('PG_DATABASE')} user={env.str('PG_USERNAME')} " \ f"password={env.str('PG_PASSWORD')} host={env.str('PG_SERVER')}" def get_sekret_key(): '''SECRET_KEY for the session :return: ''' return EncryptedCookieStorage(base64.urlsafe_b64decode(env.str('SECRET_KEY'))) def get_timestamp_str(): '''TimeStamp string of the current timestamp for the base :return: ''' return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) metadata = sa.MetaData() # Table user tb_user = sa.Table( 'user', metadata, sa.Column('id', sa.Integer, primary_key=True, autoincrement=True), sa.Column('email', sa.String(255)), sa.Column('password', sa.String(255)), sa.Column('name', sa.String(255)), sa.Column('surname', sa.String(255)), sa.Column('create_at', sa.TIMESTAMP), sa.Column('delete_at', sa.TIMESTAMP)) # Table user_rule tb_user_rule = sa.Table( 'user_rule', metadata, sa.Column('id', sa.Integer, primary_key=True, autoincrement=True), sa.Column('rule', None, sa.ForeignKey('tb_rule.id')), sa.Column('user', None, sa.ForeignKey('tb_user.id'))) # Table rule tb_rule = sa.Table( 'rule', metadata, sa.Column('id', sa.Integer, primary_key=True, autoincrement=True), sa.Column('rule', sa.String(255)), sa.Column('comment', sa.String(255))) async def get_user_by_email(engine, email): '''User existence check :param engine: DB connection :param email: user email :return: a list of users ''' async with engine.acquire() as conn: async for row in conn.execute(tb_user.select().where(tb_user.c.email == email)): return { 'id': row[0], 'email': row[1], 'password': row[2], 'name': row[3], 'surname': row[4], 'create_at': row[5], 'delete_at': row[6] } async def get_user_rules(engine, user_id): '''Obtaining user rights by id :param engine: DB connection :param user_id: user id :return: user rights list ''' async with engine.acquire() as conn: rules = [] join = sa.join(tb_rule, tb_user_rule, tb_rule.c.id == tb_user_rule.c.rule) async for row in conn.execute( tb_rule.select().select_from(join).where(tb_user_rule.c.user == user_id)): rules.append(row[1]) return rules async def get_user_info(engine, user_id): '''Getting user data by id :param engine: DB connection :param user_id: user id :return: user information ''' async with engine.acquire() as conn: async for row in conn.execute(tb_user.select().where(tb_user.c.id == user_id)): return { 'id': row[0], 'email': row[1], 'password': row[2], 'name': row[3], 'surname': row[4], 'rules': await get_user_rules(engine=engine, user_id=user_id) } async def get_users(engine, admin): '''Retrieving user data :param engine: DB connection :param admin: Request data for admin user :return: a list of users ''' async with engine.acquire() as conn: users = [] where = '' if admin else 'WHERE u.delete_at is null' async for row in await conn.execute( f'''SELECT u.id, u.email, u.password, u.name, u.surname, u.delete_at, ARRAY( SELECT r.rule FROM "user_rule" as ur LEFT JOIN "rule" as r on ur.rule = r.id WHERE ur.user = u.id ) as "rules" FROM "user" as u {where} ORDER BY u.id;'''): # If the data is requested not by the Admin, then we do not show the admins if not admin and 'admin' in row[6]: continue users.append({ 'id': row[0], 'email': row[1], 'password': row[2], 'name': row[3], 'surname': row[4], 'delete': row[5] is not None, 'rules': row[6] }) return users async def get_rules(engine): '''Obtaining rights data :param engine: DB connection :return: list of rights ''' async with engine.acquire() as conn: rules = {} async for row in conn.execute(tb_rule.select()): # {'admin': 0} rules[row[1]] = row[0] return rules async def set_rules_for_user(engine, user_id, data): '''Setting / changing user rights :param engine: DB connection :param user_id: user id :param data: data for setting :return: ''' rules = await get_rules(engine) user_rules = await get_user_rules(engine, user_id) for rule, rule_id in rules.items(): # The user already has the current role and from the form flew to True # if rule in user_rules and data.get(rule, False) is True: # The user does not have the current role and from the form flew to False # if rule not in user_rules and data.get(rule, False) is False: # The user has a role, but False has arrived from the form - delete if rule in user_rules and data.get(rule, False) is False: async with engine.acquire() as conn: await conn.execute( tb_user_rule.delete(None) .where(tb_user_rule.c.user == user_id) .where(tb_user_rule.c.rule == rule_id)) # The user does not have roles, but True has arrived from the form - add if rule not in user_rules and data.get(rule, False) is True: async with engine.acquire() as conn: await conn.execute(tb_user_rule.insert(None).values(user=user_id, rule=rule_id)) async def set_delete_at_for_user(engine, user_id, restore=False): '''Delete user by id :param engine: DB connection :param user_id: id of the user to be deleted :return: ''' timestamp = 'null' if restore else f"'{get_timestamp_str()}'" async with engine.acquire() as conn: await conn.execute(f'''UPDATE "user" SET delete_at={timestamp} WHERE id={user_id};''') async def create_user(engine, data): '''User creation :param engine: DB connection :param data: new user data :return: ''' async with engine.acquire() as conn: user = await get_user_by_email(engine=engine, email=data['email']) if user is not None: raise Warning('A user with this email already exists.') user_id = await conn.scalar( tb_user.insert(None).values( email=data['email'], password=data['password'], name=data['name'], surname=data['surname'], create_at=get_timestamp_str())) await set_rules_for_user(engine=engine, user_id=user_id, data=data) async def update_user(engine, data): '''User data update :param engine: DB connection :param data: user data to update :return: ''' async with engine.acquire() as conn: # Check that the email matches the current one, or that it is unique in the database user = await get_user_by_email(engine=engine, email=data['email']) if user is not None and int(user['id']) != int(data['id']): raise Warning('A user with this email already exists') await conn.execute( sa.update(tb_user) .values({ 'email': data['email'], 'password': data['password'], 'name': data['name'], 'surname': data['surname'] }) .where(tb_user.c.id == int(data['id']))) await set_rules_for_user(engine=engine, user_id=int(data['id']), data=data)
# -*- coding: utf-8 -*- """ Instructor Demo: Dicts. This script showcases basic operations of Python Dicts. """ # Initialize a dictionary containing top traders for each month in 2019 top_traders_2019 = { "january" : "Karen", "february" : "Harold", "march" : "Sam" } print() print(f"Dictionary: {top_traders_2019}") print() # Initialize a dictionary trading_pnl = { "title": "Trading Log", "03-18-2019": -224, "03-19-2019": 352, "03-20-2019": 252, "03-21-2019": 354, "03-22-2019": -544, "03-23-2019": -650, "03-24-2019": 56, "03-25-2019": 123, "03-26-2019": -43, "03-27-2019": 254, "03-28-2019": 325, "03-29-2019": -123, "03-30-2019": 47, "03-31-2019": 321, "04-01-2019": 123, "04-02-2019": 133, "04-03-2019": -151, "04-04-2019": 613, "04-05-2019": 232, "04-06-2019": -311 } # Print out dictionary, initial print() to serve as spacing between command line input print() print(f"Dictionary: {trading_pnl}") print() # Print out specific value of a key print(f"03-31-2019: {trading_pnl["03-31-2019"]}") print() # Add a new key-value pair trading_pnl["04-07-2019"] = 413 print(trading_pnl) print() # Modify a key value trading_pnl["04-07-2019"] = 542 print(trading_pnl) print() # Delete a key-value pair del trading_pnl["04-07-2019"] print(trading_pnl) print() # Check if key exists if "04-03-2019" in trading_pnl: print("Yes, '04-03-2019' is one of the keys in the trading_pnl dictionary") print() # Print out dict keys via a for loop for key in trading_pnl: print(f"Key: {key}") print() # Print out dict values for key in trading_pnl: print(f"Value: {trading_pnl[key]}") print() # Print out dict key-value pairs for key, value in trading_pnl.items(): print(f"Key: {key} Value: {value}") print()
# -*- coding: utf-8 -*- """ Instructor Demo: Dicts. This script showcases basic operations of Python Dicts. """ # Initialize a dictionary containing top traders for each month in 2019 top_traders_2019 = { "january" : "Karen", "february" : "Harold", "march" : "Sam" } print() print(f"Dictionary: {top_traders_2019}") print() # Initialize a dictionary trading_pnl = { "title": "Trading Log", "03-18-2019": -224, "03-19-2019": 352, "03-20-2019": 252, "03-21-2019": 354, "03-22-2019": -544, "03-23-2019": -650, "03-24-2019": 56, "03-25-2019": 123, "03-26-2019": -43, "03-27-2019": 254, "03-28-2019": 325, "03-29-2019": -123, "03-30-2019": 47, "03-31-2019": 321, "04-01-2019": 123, "04-02-2019": 133, "04-03-2019": -151, "04-04-2019": 613, "04-05-2019": 232, "04-06-2019": -311 } # Print out dictionary, initial print() to serve as spacing between command line input print() print(f"Dictionary: {trading_pnl}") print() # Print out specific value of a key print(f"03-31-2019: {trading_pnl['03-31-2019']}") print() # Add a new key-value pair trading_pnl["04-07-2019"] = 413 print(trading_pnl) print() # Modify a key value trading_pnl["04-07-2019"] = 542 print(trading_pnl) print() # Delete a key-value pair del trading_pnl["04-07-2019"] print(trading_pnl) print() # Check if key exists if "04-03-2019" in trading_pnl: print("Yes, '04-03-2019' is one of the keys in the trading_pnl dictionary") print() # Print out dict keys via a for loop for key in trading_pnl: print(f"Key: {key}") print() # Print out dict values for key in trading_pnl: print(f"Value: {trading_pnl[key]}") print() # Print out dict key-value pairs for key, value in trading_pnl.items(): print(f"Key: {key} Value: {value}") print()
import io from types import NoneType import utils from pprint import pprint def typeMapFromFlatDict(): union: dict[str, set] = {} for doc in utils.docs(progress_bar=True): for key, val in doc.items(): union.setdefault(key, set()) union[key].add(type(val)) return union def flatTypeMapToPythonClassString( typeMap: dict[str, set], name: str, indent: str = " ", table: str | None = None ): def extractTypeString(type_): if type_ is NoneType: return "None" else: return type_.__name__ def extractSATypeString(types: set): types = types - {NoneType} if ( (str in types) or (list in types) or (tuple in types) or (set in types) or (dict in types) ): return "sa.UnicodeText" if float in types: return "sa.Float" if int in types: return "sa.Integer" buffer = io.StringIO() if table is not None: buffer.write(f"@mapper_registry.mapped\n") buffer.write(f"@dataclass\n") buffer.write(f"class {name}:\n{indent}") if table is not None: buffer.write("__table__ = sa.Table(\n") buffer.write(f'{indent*2}"{table}",\n') buffer.write(f"{indent*2}mapper_registry.metadata,\n") buffer.write( f'{indent*2}sa.Column("_id", sa.Integer, autoincrement=True, primary_key=True),\n' ) buffer.write(f'{indent*2}sa.Column("_created", sa.DateTime, server_default=func.now()),\n') buffer.write(f'{indent*2}sa.Column("_last_updated", sa.DateTime, onupdate=func.now()),\n') buffer.write(f'{indent*2}sa.Column("_batch", sa.Integer),\n') for key, types in typeMap.items(): buffer.write(f'{indent*2}sa.Column("{key}", {extractSATypeString(types)}),\n') buffer.write(f"{indent})\n") buffer.write(f"{indent}_id: int = field(init=False)\n") buffer.write(f"{indent}_last_updated: datetime.datetime = field(init=False)\n") buffer.write(f"{indent}_batch: int = None\n{indent}") for key, types in typeMap.items(): buffer.write(f"{key}: ") buffer.write(f"{" | ".join(extractTypeString(t) for t in types)} = None") buffer.write(f"\n{indent}") print(buffer.getvalue()) buffer.close() if __name__ == "__main__": typemap = typeMapFromFlatDict() flatTypeMapToPythonClassString(typemap, "Doc", table="preview")
import io from types import NoneType import utils from pprint import pprint def typeMapFromFlatDict(): union: dict[str, set] = {} for doc in utils.docs(progress_bar=True): for key, val in doc.items(): union.setdefault(key, set()) union[key].add(type(val)) return union def flatTypeMapToPythonClassString( typeMap: dict[str, set], name: str, indent: str = " ", table: str | None = None ): def extractTypeString(type_): if type_ is NoneType: return "None" else: return type_.__name__ def extractSATypeString(types: set): types = types - {NoneType} if ( (str in types) or (list in types) or (tuple in types) or (set in types) or (dict in types) ): return "sa.UnicodeText" if float in types: return "sa.Float" if int in types: return "sa.Integer" buffer = io.StringIO() if table is not None: buffer.write(f"@mapper_registry.mapped\n") buffer.write(f"@dataclass\n") buffer.write(f"class {name}:\n{indent}") if table is not None: buffer.write("__table__ = sa.Table(\n") buffer.write(f'{indent*2}"{table}",\n') buffer.write(f"{indent*2}mapper_registry.metadata,\n") buffer.write( f'{indent*2}sa.Column("_id", sa.Integer, autoincrement=True, primary_key=True),\n' ) buffer.write(f'{indent*2}sa.Column("_created", sa.DateTime, server_default=func.now()),\n') buffer.write(f'{indent*2}sa.Column("_last_updated", sa.DateTime, onupdate=func.now()),\n') buffer.write(f'{indent*2}sa.Column("_batch", sa.Integer),\n') for key, types in typeMap.items(): buffer.write(f'{indent*2}sa.Column("{key}", {extractSATypeString(types)}),\n') buffer.write(f"{indent})\n") buffer.write(f"{indent}_id: int = field(init=False)\n") buffer.write(f"{indent}_last_updated: datetime.datetime = field(init=False)\n") buffer.write(f"{indent}_batch: int = None\n{indent}") for key, types in typeMap.items(): buffer.write(f"{key}: ") buffer.write(f"{' | '.join(extractTypeString(t) for t in types)} = None") buffer.write(f"\n{indent}") print(buffer.getvalue()) buffer.close() if __name__ == "__main__": typemap = typeMapFromFlatDict() flatTypeMapToPythonClassString(typemap, "Doc", table="preview")
# Lint as: python3 import json import logging import os import datasets from layoutlmft.data.utils import load_image, merge_bbox, normalize_bbox, simplify_bbox from transformers import AutoTokenizer _URL = "https://github.com/doc-analysis/XFUN/releases/download/v1.0/" _LANG = ["zh", "de", "es", "fr", "en", "it", "ja", "pt"] logger = logging.getLogger(__name__) class XFUNConfig(datasets.BuilderConfig): """BuilderConfig for XFUN.""" def __init__(self, lang, additional_langs=None, **kwargs): """ Args: lang: string, language for the input text **kwargs: keyword arguments forwarded to super. """ super(XFUNConfig, self).__init__(**kwargs) self.lang = lang self.additional_langs = additional_langs class XFUN(datasets.GeneratorBasedBuilder): """XFUN dataset.""" BUILDER_CONFIGS = [XFUNConfig(name=f"xfun.{lang}", lang=lang) for lang in _LANG] tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-base") def _info(self): return datasets.DatasetInfo( features=datasets.Features( { "id": datasets.Value("string"), "input_ids": datasets.Sequence(datasets.Value("int64")), "bbox": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))), "labels": datasets.Sequence( datasets.ClassLabel( names=["O", "B-QUESTION", "B-ANSWER", "B-HEADER", "I-ANSWER", "I-QUESTION", "I-HEADER"] ) ), "image": datasets.Array3D(shape=(3, 224, 224), dtype="uint8"), "entities": datasets.Sequence( { "start": datasets.Value("int64"), "end": datasets.Value("int64"), "label": datasets.ClassLabel(names=["HEADER", "QUESTION", "ANSWER"]), } ), "relations": datasets.Sequence( { "head": datasets.Value("int64"), "tail": datasets.Value("int64"), "start_index": datasets.Value("int64"), "end_index": datasets.Value("int64"), } ), } ), supervised_keys=None, ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" urls_to_download = { "train": [f"{_URL}{self.config.lang}.train.json", f"{_URL}{self.config.lang}.train.zip"], "val": [f"{_URL}{self.config.lang}.val.json", f"{_URL}{self.config.lang}.val.zip"], # "test": [f"{_URL}{self.config.lang}.test.json", f"{_URL}{self.config.lang}.test.zip"], } downloaded_files = dl_manager.download_and_extract(urls_to_download) train_files_for_many_langs = [downloaded_files["train"]] val_files_for_many_langs = [downloaded_files["val"]] # test_files_for_many_langs = [downloaded_files["test"]] if self.config.additional_langs: additional_langs = self.config.additional_langs.split("+") if "all" in additional_langs: additional_langs = [lang for lang in _LANG if lang != self.config.lang] for lang in additional_langs: urls_to_download = {"train": [f"{_URL}{lang}.train.json", f"{_URL}{lang}.train.zip"]} additional_downloaded_files = dl_manager.download_and_extract(urls_to_download) train_files_for_many_langs.append(additional_downloaded_files["train"]) logger.info(f"Training on {self.config.lang} with additional langs({self.config.additional_langs})") logger.info(f"Evaluating on {self.config.lang}") logger.info(f"Testing on {self.config.lang}") return [ datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepaths": train_files_for_many_langs}), datasets.SplitGenerator( name=datasets.Split.VALIDATION, gen_kwargs={"filepaths": val_files_for_many_langs} ), # datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepaths": test_files_for_many_langs}), ] def _generate_examples(self, filepaths): for filepath in filepaths: logger.info("Generating examples from = %s", filepath) with open(filepath[0], "r") as f: data = json.load(f) for doc in data["documents"]: doc["img"]["fpath"] = os.path.join(filepath[1], doc["img"]["fname"]) image, size = load_image(doc["img"]["fpath"]) document = doc["document"] tokenized_doc = {"input_ids": [], "bbox": [], "labels": []} entities = [] relations = [] id2label = {} entity_id_to_index_map = {} empty_entity = set() for line in document: if len(line["text"]) == 0: empty_entity.add(line["id"]) continue id2label[line["id"]] = line["label"] relations.extend([tuple(sorted(l)) for l in line["linking"]]) tokenized_inputs = self.tokenizer( line["text"], add_special_tokens=False, return_offsets_mapping=True, return_attention_mask=False, ) text_length = 0 ocr_length = 0 bbox = [] for token_id, offset in zip(tokenized_inputs["input_ids"], tokenized_inputs["offset_mapping"]): if token_id == 6: bbox.append(None) continue text_length += offset[1] - offset[0] tmp_box = [] while ocr_length < text_length: ocr_word = line["words"].pop(0) ocr_length += len( self.tokenizer._tokenizer.normalizer.normalize_str(ocr_word["text"].strip()) ) tmp_box.append(simplify_bbox(ocr_word["box"])) if len(tmp_box) == 0: tmp_box = last_box bbox.append(normalize_bbox(merge_bbox(tmp_box), size)) last_box = tmp_box # noqa bbox = [ [bbox[i + 1][0], bbox[i + 1][1], bbox[i + 1][0], bbox[i + 1][1]] if b is None else b for i, b in enumerate(bbox) ] if line["label"] == "other": label = ["O"] * len(bbox) else: label = [f"I-{line["label"].upper()}"] * len(bbox) label[0] = f"B-{line["label"].upper()}" tokenized_inputs.update({"bbox": bbox, "labels": label}) if label[0] != "O": entity_id_to_index_map[line["id"]] = len(entities) entities.append( { "start": len(tokenized_doc["input_ids"]), "end": len(tokenized_doc["input_ids"]) + len(tokenized_inputs["input_ids"]), "label": line["label"].upper(), } ) for i in tokenized_doc: tokenized_doc[i] = tokenized_doc[i] + tokenized_inputs[i] relations = list(set(relations)) relations = [rel for rel in relations if rel[0] not in empty_entity and rel[1] not in empty_entity] kvrelations = [] for rel in relations: pair = [id2label[rel[0]], id2label[rel[1]]] if pair == ["question", "answer"]: kvrelations.append( {"head": entity_id_to_index_map[rel[0]], "tail": entity_id_to_index_map[rel[1]]} ) elif pair == ["answer", "question"]: kvrelations.append( {"head": entity_id_to_index_map[rel[1]], "tail": entity_id_to_index_map[rel[0]]} ) else: continue def get_relation_span(rel): bound = [] for entity_index in [rel["head"], rel["tail"]]: bound.append(entities[entity_index]["start"]) bound.append(entities[entity_index]["end"]) return min(bound), max(bound) relations = sorted( [ { "head": rel["head"], "tail": rel["tail"], "start_index": get_relation_span(rel)[0], "end_index": get_relation_span(rel)[1], } for rel in kvrelations ], key=lambda x: x["head"], ) chunk_size = 512 for chunk_id, index in enumerate(range(0, len(tokenized_doc["input_ids"]), chunk_size)): item = {} for k in tokenized_doc: item[k] = tokenized_doc[k][index : index + chunk_size] entities_in_this_span = [] global_to_local_map = {} for entity_id, entity in enumerate(entities): if ( index <= entity["start"] < index + chunk_size and index <= entity["end"] < index + chunk_size ): entity["start"] = entity["start"] - index entity["end"] = entity["end"] - index global_to_local_map[entity_id] = len(entities_in_this_span) entities_in_this_span.append(entity) relations_in_this_span = [] for relation in relations: if ( index <= relation["start_index"] < index + chunk_size and index <= relation["end_index"] < index + chunk_size ): relations_in_this_span.append( { "head": global_to_local_map[relation["head"]], "tail": global_to_local_map[relation["tail"]], "start_index": relation["start_index"] - index, "end_index": relation["end_index"] - index, } ) item.update( { "id": f"{doc["id"]}_{chunk_id}", "image": image, "entities": entities_in_this_span, "relations": relations_in_this_span, } ) yield f"{doc["id"]}_{chunk_id}", item
# Lint as: python3 import json import logging import os import datasets from layoutlmft.data.utils import load_image, merge_bbox, normalize_bbox, simplify_bbox from transformers import AutoTokenizer _URL = "https://github.com/doc-analysis/XFUN/releases/download/v1.0/" _LANG = ["zh", "de", "es", "fr", "en", "it", "ja", "pt"] logger = logging.getLogger(__name__) class XFUNConfig(datasets.BuilderConfig): """BuilderConfig for XFUN.""" def __init__(self, lang, additional_langs=None, **kwargs): """ Args: lang: string, language for the input text **kwargs: keyword arguments forwarded to super. """ super(XFUNConfig, self).__init__(**kwargs) self.lang = lang self.additional_langs = additional_langs class XFUN(datasets.GeneratorBasedBuilder): """XFUN dataset.""" BUILDER_CONFIGS = [XFUNConfig(name=f"xfun.{lang}", lang=lang) for lang in _LANG] tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-base") def _info(self): return datasets.DatasetInfo( features=datasets.Features( { "id": datasets.Value("string"), "input_ids": datasets.Sequence(datasets.Value("int64")), "bbox": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))), "labels": datasets.Sequence( datasets.ClassLabel( names=["O", "B-QUESTION", "B-ANSWER", "B-HEADER", "I-ANSWER", "I-QUESTION", "I-HEADER"] ) ), "image": datasets.Array3D(shape=(3, 224, 224), dtype="uint8"), "entities": datasets.Sequence( { "start": datasets.Value("int64"), "end": datasets.Value("int64"), "label": datasets.ClassLabel(names=["HEADER", "QUESTION", "ANSWER"]), } ), "relations": datasets.Sequence( { "head": datasets.Value("int64"), "tail": datasets.Value("int64"), "start_index": datasets.Value("int64"), "end_index": datasets.Value("int64"), } ), } ), supervised_keys=None, ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" urls_to_download = { "train": [f"{_URL}{self.config.lang}.train.json", f"{_URL}{self.config.lang}.train.zip"], "val": [f"{_URL}{self.config.lang}.val.json", f"{_URL}{self.config.lang}.val.zip"], # "test": [f"{_URL}{self.config.lang}.test.json", f"{_URL}{self.config.lang}.test.zip"], } downloaded_files = dl_manager.download_and_extract(urls_to_download) train_files_for_many_langs = [downloaded_files["train"]] val_files_for_many_langs = [downloaded_files["val"]] # test_files_for_many_langs = [downloaded_files["test"]] if self.config.additional_langs: additional_langs = self.config.additional_langs.split("+") if "all" in additional_langs: additional_langs = [lang for lang in _LANG if lang != self.config.lang] for lang in additional_langs: urls_to_download = {"train": [f"{_URL}{lang}.train.json", f"{_URL}{lang}.train.zip"]} additional_downloaded_files = dl_manager.download_and_extract(urls_to_download) train_files_for_many_langs.append(additional_downloaded_files["train"]) logger.info(f"Training on {self.config.lang} with additional langs({self.config.additional_langs})") logger.info(f"Evaluating on {self.config.lang}") logger.info(f"Testing on {self.config.lang}") return [ datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepaths": train_files_for_many_langs}), datasets.SplitGenerator( name=datasets.Split.VALIDATION, gen_kwargs={"filepaths": val_files_for_many_langs} ), # datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepaths": test_files_for_many_langs}), ] def _generate_examples(self, filepaths): for filepath in filepaths: logger.info("Generating examples from = %s", filepath) with open(filepath[0], "r") as f: data = json.load(f) for doc in data["documents"]: doc["img"]["fpath"] = os.path.join(filepath[1], doc["img"]["fname"]) image, size = load_image(doc["img"]["fpath"]) document = doc["document"] tokenized_doc = {"input_ids": [], "bbox": [], "labels": []} entities = [] relations = [] id2label = {} entity_id_to_index_map = {} empty_entity = set() for line in document: if len(line["text"]) == 0: empty_entity.add(line["id"]) continue id2label[line["id"]] = line["label"] relations.extend([tuple(sorted(l)) for l in line["linking"]]) tokenized_inputs = self.tokenizer( line["text"], add_special_tokens=False, return_offsets_mapping=True, return_attention_mask=False, ) text_length = 0 ocr_length = 0 bbox = [] for token_id, offset in zip(tokenized_inputs["input_ids"], tokenized_inputs["offset_mapping"]): if token_id == 6: bbox.append(None) continue text_length += offset[1] - offset[0] tmp_box = [] while ocr_length < text_length: ocr_word = line["words"].pop(0) ocr_length += len( self.tokenizer._tokenizer.normalizer.normalize_str(ocr_word["text"].strip()) ) tmp_box.append(simplify_bbox(ocr_word["box"])) if len(tmp_box) == 0: tmp_box = last_box bbox.append(normalize_bbox(merge_bbox(tmp_box), size)) last_box = tmp_box # noqa bbox = [ [bbox[i + 1][0], bbox[i + 1][1], bbox[i + 1][0], bbox[i + 1][1]] if b is None else b for i, b in enumerate(bbox) ] if line["label"] == "other": label = ["O"] * len(bbox) else: label = [f"I-{line['label'].upper()}"] * len(bbox) label[0] = f"B-{line['label'].upper()}" tokenized_inputs.update({"bbox": bbox, "labels": label}) if label[0] != "O": entity_id_to_index_map[line["id"]] = len(entities) entities.append( { "start": len(tokenized_doc["input_ids"]), "end": len(tokenized_doc["input_ids"]) + len(tokenized_inputs["input_ids"]), "label": line["label"].upper(), } ) for i in tokenized_doc: tokenized_doc[i] = tokenized_doc[i] + tokenized_inputs[i] relations = list(set(relations)) relations = [rel for rel in relations if rel[0] not in empty_entity and rel[1] not in empty_entity] kvrelations = [] for rel in relations: pair = [id2label[rel[0]], id2label[rel[1]]] if pair == ["question", "answer"]: kvrelations.append( {"head": entity_id_to_index_map[rel[0]], "tail": entity_id_to_index_map[rel[1]]} ) elif pair == ["answer", "question"]: kvrelations.append( {"head": entity_id_to_index_map[rel[1]], "tail": entity_id_to_index_map[rel[0]]} ) else: continue def get_relation_span(rel): bound = [] for entity_index in [rel["head"], rel["tail"]]: bound.append(entities[entity_index]["start"]) bound.append(entities[entity_index]["end"]) return min(bound), max(bound) relations = sorted( [ { "head": rel["head"], "tail": rel["tail"], "start_index": get_relation_span(rel)[0], "end_index": get_relation_span(rel)[1], } for rel in kvrelations ], key=lambda x: x["head"], ) chunk_size = 512 for chunk_id, index in enumerate(range(0, len(tokenized_doc["input_ids"]), chunk_size)): item = {} for k in tokenized_doc: item[k] = tokenized_doc[k][index : index + chunk_size] entities_in_this_span = [] global_to_local_map = {} for entity_id, entity in enumerate(entities): if ( index <= entity["start"] < index + chunk_size and index <= entity["end"] < index + chunk_size ): entity["start"] = entity["start"] - index entity["end"] = entity["end"] - index global_to_local_map[entity_id] = len(entities_in_this_span) entities_in_this_span.append(entity) relations_in_this_span = [] for relation in relations: if ( index <= relation["start_index"] < index + chunk_size and index <= relation["end_index"] < index + chunk_size ): relations_in_this_span.append( { "head": global_to_local_map[relation["head"]], "tail": global_to_local_map[relation["tail"]], "start_index": relation["start_index"] - index, "end_index": relation["end_index"] - index, } ) item.update( { "id": f"{doc['id']}_{chunk_id}", "image": image, "entities": entities_in_this_span, "relations": relations_in_this_span, } ) yield f"{doc['id']}_{chunk_id}", item
from unittest import TestCase from tests import abspath from pytezos.repl.interpreter import Interpreter from pytezos.michelson.converter import michelson_to_micheline from pytezos.repl.parser import parse_expression class OpcodeTestnot_binary_61(TestCase): def setUp(self): self.maxDiff = None self.i = Interpreter(debug=True) def test_opcode_not_binary_61(self): res = self.i.execute(f'INCLUDE "{abspath('opcodes/contracts/not_binary.tz')}"') self.assertTrue(res['success']) res = self.i.execute('RUN (Right 8) None') self.assertTrue(res['success']) exp_val_expr = michelson_to_micheline('(Some -9)') exp_val = parse_expression(exp_val_expr, res['result']['storage'].type_expr) self.assertEqual(exp_val, res['result']['storage']._val)
from unittest import TestCase from tests import abspath from pytezos.repl.interpreter import Interpreter from pytezos.michelson.converter import michelson_to_micheline from pytezos.repl.parser import parse_expression class OpcodeTestnot_binary_61(TestCase): def setUp(self): self.maxDiff = None self.i = Interpreter(debug=True) def test_opcode_not_binary_61(self): res = self.i.execute(f'INCLUDE "{abspath("opcodes/contracts/not_binary.tz")}"') self.assertTrue(res['success']) res = self.i.execute('RUN (Right 8) None') self.assertTrue(res['success']) exp_val_expr = michelson_to_micheline('(Some -9)') exp_val = parse_expression(exp_val_expr, res['result']['storage'].type_expr) self.assertEqual(exp_val, res['result']['storage']._val)
# # Copyright (c) 2019-2021, ETH Zurich. All rights reserved. # # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause # import logging import os import jwt import stat import datetime import hashlib import tempfile import json import functools from flask import request, jsonify, g import requests import urllib import base64 import io import re import time import threading # Checks if an environment variable injected to F7T is a valid True value # var <- object # returns -> boolean def get_boolean_var(var): # ensure variable to be a string var = str(var) # True, true or TRUE # Yes, yes or YES # 1 return var.upper() == "TRUE" or var.upper() == "YES" or var == "1" debug = get_boolean_var(os.environ.get("F7T_DEBUG_MODE", False)) AUTH_HEADER_NAME = 'Authorization' realm_pubkey=os.environ.get("F7T_REALM_RSA_PUBLIC_KEY", '') if realm_pubkey != '': # headers are inserted here, must not be present realm_pubkey = realm_pubkey.strip('\'"') # remove '"' realm_pubkey = '-----BEGIN PUBLIC KEY-----\n' + realm_pubkey + '\n-----END PUBLIC KEY-----' realm_pubkey_type = os.environ.get("F7T_REALM_RSA_TYPE").strip('\'"') AUTH_AUDIENCE = os.environ.get("F7T_AUTH_TOKEN_AUD", '').strip('\'"') ALLOWED_USERS = os.environ.get("F7T_AUTH_ALLOWED_USERS", '').strip('\'"').split(";") AUTH_REQUIRED_SCOPE = os.environ.get("F7T_AUTH_REQUIRED_SCOPE", '').strip('\'"') AUTH_ROLE = os.environ.get("F7T_AUTH_ROLE", '').strip('\'"') CERTIFICATOR_URL = os.environ.get("F7T_CERTIFICATOR_URL") TASKS_URL = os.environ.get("F7T_TASKS_URL") F7T_SSH_CERTIFICATE_WRAPPER = get_boolean_var(os.environ.get("F7T_SSH_CERTIFICATE_WRAPPER", False)) # Fobidden chars on user path/parameters: wihtout scapes: < > | ; " ' & \ [ ] ( ) x00-x1F \x60 # r'...' specifies it's a regular expression with special treatment for \ FORBIDDEN_INPUT_CHARS = r'[\<\>\|\;\"\'\&\\\[\]\(\)\x00-\x1F\x60]' # OPA endpoint OPA_USE = get_boolean_var(os.environ.get("F7T_OPA_USE",False)) OPA_URL = os.environ.get("F7T_OPA_URL","http://localhost:8181").strip('\'"') POLICY_PATH = os.environ.get("F7T_POLICY_PATH","v1/data/f7t/authz").strip('\'"') ### SSL parameters USE_SSL = get_boolean_var(os.environ.get("F7T_USE_SSL", False)) SSL_CRT = os.environ.get("F7T_SSL_CRT", "") SSL_KEY = os.environ.get("F7T_SSL_KEY", "") TRACER_HEADER = "uber-trace-id" # checks JWT from Keycloak, optionally validates signature. It only receives the content of header's auth pair (not key:content) def check_header(header): if debug: logging.info('debug: header: ' + header) # header = "Bearer ey...", remove first 7 chars try: if realm_pubkey == '': if not debug: logging.warning("WARNING: REALM_RSA_PUBLIC_KEY is empty, JWT tokens are NOT verified, setup is not set to debug.") decoded = jwt.decode(header[7:], verify=False) else: if AUTH_AUDIENCE == '': decoded = jwt.decode(header[7:], realm_pubkey, algorithms=realm_pubkey_type, options={'verify_aud': False}) else: decoded = jwt.decode(header[7:], realm_pubkey, algorithms=realm_pubkey_type, audience=AUTH_AUDIENCE) if AUTH_REQUIRED_SCOPE != "": if AUTH_REQUIRED_SCOPE not in decoded["scope"].split(): return False return True except jwt.exceptions.InvalidSignatureError: logging.error("JWT invalid signature", exc_info=True) except jwt.ExpiredSignatureError: logging.error("JWT token has expired", exc_info=True) except jwt.InvalidAudienceError: logging.error("JWT token invalid audience", exc_info=True) except jwt.exceptions.InvalidAlgorithmError: logging.error("JWT invalid signature algorithm", exc_info=True) except Exception: logging.error("Bad header or JWT, general exception raised", exc_info=True) return False # returns username def get_username(header): # header = "Bearer ey...", remove first 7 chars try: if realm_pubkey == '': decoded = jwt.decode(header[7:], verify=False) else: decoded = jwt.decode(header[7:], realm_pubkey, algorithms=realm_pubkey_type, options={'verify_aud': False}) # check if it's a service account token try: if AUTH_ROLE in decoded["realm_access"]["roles"]: clientId = decoded["clientId"] username = decoded["resource_access"][clientId]["roles"][0] return username return decoded['preferred_username'] except Exception: return decoded['preferred_username'] except jwt.exceptions.InvalidSignatureError: logging.error("JWT invalid signature", exc_info=True) except jwt.ExpiredSignatureError: logging.error("JWT token has expired", exc_info=True) except jwt.InvalidAudienceError: logging.error("JWT token invalid audience", exc_info=True) except jwt.exceptions.InvalidAlgorithmError: logging.error("JWT invalid signature algorithm", exc_info=True) except Exception: logging.error("Bad header or JWT, general exception raised", exc_info=True) return None # function to check if pattern is in string def in_str(stringval,words): try: stringval.index(words) return True except ValueError: return False # SSH certificates creation # returns pub key certificate name def create_certificate(headers, cluster_name, cluster_addr, command=None, options=None, exp_time=None): """ Args: cluster_name = public name of system to be executed cluster_addr = private DNS or IP of the system command = command to be executed with the certificate (required) option = parameters and options to be executed with {command} exp_time = expiration time for SSH certificate """ reqURL = f"{CERTIFICATOR_URL}/?cluster={cluster_name}&addr={cluster_addr}" if command: logging.info(f"\tCommand: {command}") reqURL += "&command=" + base64.urlsafe_b64encode(command.encode()).decode() if options: logging.info(f"\tOptions (truncated): {options:80}") reqURL += "&option=" + base64.urlsafe_b64encode(options.encode()).decode() if exp_time: logging.info(f"\tExpiration: {exp_time} [s]") reqURL += f"&exptime={exp_time}" else: logging.error('Tried to create certificate without command') return [None, 1, 'Internal error'] if debug: username = get_username(headers[AUTH_HEADER_NAME]) logging.info(f"Create certificate for user {username}") if options: # may contain Storage URL logging.info(f"\tOptions (complete): {options}") logging.info(f"Request URL: {reqURL}") try: resp = requests.get(reqURL, headers=headers, verify= (SSL_CRT if USE_SSL else False) ) if resp.status_code != 200: return [None, resp.status_code, resp.json()["description"]] jcert = resp.json() # create temp dir to store certificate for this request td = tempfile.mkdtemp(prefix="dummy") os.symlink(os.getcwd() + "/user-key.pub", td + "/user-key.pub") # link on temp dir os.symlink(os.getcwd() + "/user-key", td + "/user-key") # link on temp dir certf = open(td + "/user-key-cert.pub", 'w') certf.write(jcert["certificate"]) certf.close() # stat.S_IRUSR -> owner has read permission os.chmod(td + "/user-key-cert.pub", stat.S_IRUSR) # keys: [pub_cert, pub_key, priv_key, temp_dir] return [td + "/user-key-cert.pub", td + "/user-key.pub", td + "/user-key", td] except requests.exceptions.SSLError as ssle: logging.error(f"(-2) -> {ssle}") logging.error(f"(-2) -> {ssle.strerror}") return [None, -2, ssle] except IOError as ioe: logging.error(f"({ioe.errno}) -> {ioe.strerror}", exc_info=True) return [None, ioe.errno, ioe.strerror] except Exception as e: logging.error(f"({type(e)}) -> {e}", exc_info=True) return [None, -1, e] # execute remote commands with Paramiko: def exec_remote_command(headers, system_name, system_addr, action, file_transfer=None, file_content=None): import paramiko, socket logging.info(f'System name: {system_name} - action: {action}') if file_transfer == "storage_cert": # storage is using a previously generated cert, save cert list from content # cert_list: list of 4 elements that contains # [0] path to the public certificate # [1] path to the public key for user # [2] path to the priv key for user # [3] path to the dir containing 3 previous files cert_list = file_content username = headers else: # get certificate: # if OK returns: [pub_cert, pub_key, priv_key, temp_dir] # if FAILED returns: [None, errno, strerror] cert_list = create_certificate(headers, system_name, system_addr, command=action) if cert_list[0] == None: result = {"error": cert_list[1], "msg": cert_list[2]} return result username = get_username(headers[AUTH_HEADER_NAME]) [pub_cert, pub_key, priv_key, temp_dir] = cert_list # ------------------- # remote exec with paramiko try: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ipaddr = system_addr.split(':') host = ipaddr[0] if len(ipaddr) == 1: port = 22 else: port = int(ipaddr[1]) client.connect(hostname=host, port=port, username=username, key_filename=pub_cert, allow_agent=False, look_for_keys=False, timeout=10) if F7T_SSH_CERTIFICATE_WRAPPER: if debug: logging.info(f"Using F7T_SSH_CERTIFICATE_WRAPPER.") # read cert to send it as a command to the server with open(pub_cert, 'r') as cert_file: cert = cert_file.read().rstrip("\n") # remove newline at the end action = cert stdin, stdout, stderr = client.exec_command(action) if file_transfer == "upload": # uploads use "cat", so write to stdin stdin.channel.sendall(file_content) stdin.channel.shutdown_write() #stdin.channel.close() output = "" error = "" finished = 0 stderr_errno = -2 stdout_errno = -2 stderr_errda = "" stdout_errda = "" # poll process status since directly using recv_exit_status() could result # in a permanent hang when remote output is larger than the current Transport or session’s window_size while True: if stderr.channel.exit_status_ready(): logging.info(f"stderr channel exit status ready") stderr_errno = stderr.channel.recv_exit_status() endtime = time.time() + 30 eof_received = True while not stderr.channel.eof_received: # time.sleep(0.5) if time.time() > endtime: stderr.channel.close() eof_received = False break if eof_received: error = "".join(stderr.readlines()) # error = stderr.read() # clean "tput: No ..." lines at error output stderr_errda = clean_err_output(error) break # else: # time.sleep(5) #for i in range(0,10): while True: if stdout.channel.exit_status_ready(): logging.info(f"stdout channel exit status ready") stdout_errno = stdout.channel.recv_exit_status() endtime = time.time() + 30 eof_received = True while not stdout.channel.eof_received: # time.sleep(0.5) if time.time() > endtime: stdout.channel.close() eof_received = False break if eof_received: output = "".join(stdout.readlines()) # error = stderr.read() it hangs # clean "tput: No ..." lines at error output stdout_errda = clean_err_output(output) break # else: # time.sleep(5) if file_transfer == "download": outlines = output else: # replace newlines with $ for parsing outlines = output.replace('\n', '$')[:-1] # hiding success results from utilities/download, since output is the content of the file if file_transfer == "download": if stderr_errno !=0: logging.info(f"stderr: ({stderr_errno}) --> {stderr_errda}") logging.info(f"stdout: ({stdout_errno}) --> {stdout_errda}") logging.info(f"stdout: ({stdout_errno}) --> {outlines}") else: logging.info(f"stderr: ({stderr_errno}) --> Download OK (content hidden)") logging.info(f"stdout: ({stdout_errno}) --> Download OK (content hidden)") else: logging.info(f"stderr: ({stderr_errno}) --> {stderr_errda}") logging.info(f"stdout: ({stdout_errno}) --> {stdout_errda}") logging.info(f"stdout: ({stdout_errno}) --> {outlines}") if stderr_errno == 0: if stderr_errda and not (in_str(stderr_errda,"Could not chdir to home directory") or in_str(stderr_errda,"scancel: Terminating job")): result = {"error": 1, "msg": stderr_errda} elif in_str(stdout_errda, "No such file"): # in case that error is 0 and the msg is on the stdout (like with some file) result = {"error": 1, "msg": stdout_errda} elif in_str(stdout_errda, "no read permission"): # in case that error is 0 and the msg is on the stdout (like with some file) result = {"error": 1, "msg": stdout_errda} elif in_str(stdout_errda, "cannot open"): # in case that error is 0 and the msg is on the stdout (like with some file) result = {"error": 1, "msg": stdout_errda} else: result = {"error": 0, "msg": outlines} elif stderr_errno > 0: if stderr_errno == 7: result = {"error": 7, "msg": "Failed to connect to staging area server"} else: result = {"error": stderr_errno, "msg": stderr_errda or stdout_errda} elif len(stderr_errda) > 0: result = {"error": 1, "msg": stderr_errda} elif stdout_errno == -2: result = {"error": -2, "msg": "Receive ready timeout exceeded"} elif stderr_errno == -1: result = {"error": -1, "msg": "No exit status was provided by the server"} # first if paramiko exception raise except paramiko.ssh_exception.NoValidConnectionsError as e: logging.error(type(e), exc_info=True) if e.errors: for k, v in e.errors.items(): logging.error(f"errorno: {v.errno}") logging.error(f"strerr: {v.strerror}") result = {"error": v.errno, "msg": v.strerror} except socket.gaierror as e: logging.error(type(e), exc_info=True) logging.error(e.errno) logging.error(e.strerror) result = {"error": e.errno, "msg": e.strerror} except paramiko.ssh_exception.SSHException as e: logging.error(type(e), exc_info=True) logging.error(e) result = {"error": 1, "msg": str(e)} # second: time out except socket.timeout as e: logging.error(type(e), exc_info=True) # timeout has not errno logging.error(e) result = {"error": 1, "msg": e.strerror} except Exception as e: logging.error(type(e), exc_info=True) result = {"error": 1, "msg": str(e)} finally: client.close() os.remove(pub_cert) os.remove(pub_key) os.remove(priv_key) os.rmdir(temp_dir) # hiding results from utilities/download, since output is the content of the file if file_transfer == "download": logging.info(f"Result: status_code {result["error"]} -> Utilities download") else: logging.info(f"Result: status_code {result["error"]} -> {result["msg"]}") return result # clean TERM errors on stderr # resaon: some servers produces this error becuase don't set a TERM def clean_err_output(tex): lines = "" # python3 tex comes as a byte object, needs to be decoded to a str #tex = tex.decode('utf-8') for t in tex.split('\n'): if t != 'tput: No value for $TERM and no -T specified': lines += t return lines def parse_io_error(retval, operation, path): """ As command ended with error, create message to return to user Args: retval (from exec_remote_command) operation, path: return: jsonify('error message'), error_code (4xx), optional_header """ header = '' if retval["error"] == 13: # IOError 13: Permission denied header = {"X-Permission-Denied": "User does not have permissions to access machine or paths"} elif retval["error"] == 2: # IOError 2: no such file header = {"X-Invalid-Path": f"{path} is invalid."} elif retval["error"] == -2: # IOError -2: name or service not known header = {"X-Machine-Not-Available": "Machine is not available"} elif retval["error"] == 118: header = {"X-Permission-Denied": "Internal SSH error"} elif in_str(retval["msg"],"Permission") or in_str(retval["msg"],"OPENSSH"): header = {"X-Permission-Denied": "User does not have permissions to access machine or paths"} return jsonify(description = f"Failed to {operation}"), 400, header # function to call create task entry API in Queue FS, returns task_id for new task def create_task(headers, service=None): # returns {"task_id":task_id} # first try to get up task microservice: try: # X-Firecrest-Service: service that created the task headers["X-Firecrest-Service"] = service req = requests.post(f"{TASKS_URL}/", headers=headers, verify=(SSL_CRT if USE_SSL else False)) except requests.exceptions.ConnectionError as e: logging.error(type(e), exc_info=True) logging.error(e) return -1 if req.status_code != 201: return -1 logging.info(json.loads(req.content)) resp = json.loads(req.content) task_id = resp["hash_id"] return task_id # function to call update task entry API in Queue FS def update_task(task_id, headers, status, msg=None, is_json=False): logging.info(f"Update {TASKS_URL}/{task_id} -> status: {status}") data = {"status": status, "msg": msg} if is_json: req = requests.put(f"{TASKS_URL}/{task_id}", json=data, headers=headers, verify=(SSL_CRT if USE_SSL else False)) else: req = requests.put(f"{TASKS_URL}/{task_id}", data=data, headers=headers, verify=(SSL_CRT if USE_SSL else False)) resp = json.loads(req.content) return resp # function to call update task entry API in Queue FS def expire_task(task_id, headers, service): logging.info(f"{TASKS_URL}/expire/{task_id}") try: headers["X-Firecrest-Service"] = service req = requests.post(f"{TASKS_URL}/expire/{task_id}", headers=headers, verify=(SSL_CRT if USE_SSL else False)) except Exception as e: logging.error(type(e)) logging.error(e.args) if not req.ok: logging.info(req.json()) return False return True # function to check task status: def get_task_status(task_id, headers): logging.info(f"{TASKS_URL}/{task_id}") try: retval = requests.get(f"{TASKS_URL}/{task_id}", headers=headers, verify=(SSL_CRT if USE_SSL else False)) if retval.status_code != 200: return -1 data = retval.json() logging.info(data["task"]["status"]) return data["task"]["status"] except Exception as e: logging.error(type(e), exc_info=True) logging.error(e) return -1 # checks if {path} is a valid file (exists and user in {auth_header} has read permissions) def is_valid_file(path, headers, system_name, system_addr): ID = headers.get(TRACER_HEADER, '') # checks user accessibility to path using head command with 0 bytes action = f"ID={ID} head -c 1 -- '{path}' > /dev/null" retval = exec_remote_command(headers, system_name, system_addr, action) logging.info(retval) if retval["error"] != 0: error_str=retval["msg"] if retval["error"] == 113: return {"result":False, "headers":{"X-Machine-Not-Available":"Machine is not available"} } if retval["error"] == 124: return {"result":False, "headers":{"X-Timeout": "Command has finished with timeout signal"}} # error no such file if in_str(error_str,"No such file"): return {"result":False, "headers":{"X-Invalid-Path": f"{path} is an invalid path."}} # permission denied if in_str(error_str,"Permission denied") or in_str(error_str,"OPENSSH"): return {"result":False, "headers":{"X-Permission-Denied": "User does not have permissions to access machine or path"}} if in_str(error_str, "directory"): return {"result":False, "headers":{"X-A-Directory": f"{path} is a directory"}} return {"result":False, "headers":{"X-Error": retval["msg"]}} return {"result":True} # checks if {path} is a valid directory # 'path' should exists and be accesible to the user (write permissions) # def is_valid_dir(path, headers, system_name, system_addr): # create an empty file for testing path accesibility # test file is a hidden file and has a timestamp in order to not overwrite other files created by user # after this, file should be deleted timestamp = datetime.datetime.today().strftime("%Y-%m-%dT%H:%M:%S.%f") # using a hash hashedTS = hashlib.md5() hashedTS.update(timestamp.encode("utf-8")) tempFileName = f".firecrest.{hashedTS.hexdigest()}" ID = headers.get(TRACER_HEADER, '') action = f"ID={ID} touch -- '{path}/{tempFileName}'" retval = exec_remote_command(headers, system_name, system_addr, action) logging.info(retval) if retval["error"] != 0: error_str=retval["msg"] if retval["error"] == 113: return {"result":False, "headers":{"X-Machine-Not-Available":"Machine is not available"} } if retval["error"] == 124: return {"result":False, "headers":{"X-Timeout": "Command has finished with timeout signal"}} # error no such file if in_str(error_str,"No such file"): return {"result":False, "headers":{"X-Invalid-Path": f"{path} is an invalid path."}} # permission denied if in_str(error_str,"Permission denied") or in_str(error_str,"OPENSSH"): return {"result":False, "headers":{"X-Permission-Denied": "User does not have permissions to access machine or path"}} # not a directory if in_str(error_str,"Not a directory"): return {"result":False, "headers":{"X-Not-A-Directory": f"{path} is not a directory"}} return {"result":False, "headers":{"X-Error": retval["msg"]}} # delete test file created action = f"ID={ID} rm -- '{path}/{tempFileName}'" retval = exec_remote_command(headers, system_name, system_addr, action) return {"result":True} # wrapper to check if AUTH header is correct # decorator use: # # @app.route("/endpoint", methods=["GET","..."]) # @check_auth_header # def function_that_check_header(): # ..... def check_auth_header(func): @functools.wraps(func) def wrapper_check_auth_header(*args, **kwargs): try: auth_header = request.headers[AUTH_HEADER_NAME] except KeyError: logging.error("No Auth Header given") return jsonify(description="No Auth Header given"), 401 if not check_header(auth_header): return jsonify(description="Invalid header"), 401 return func(*args, **kwargs) return wrapper_check_auth_header # check user authorization on endpoint # using Open Policy Agent # # use: # check_user_auth(username,system) def check_user_auth(username,system): # check if OPA is active if OPA_USE: try: input = {"input":{"user": f"{username}", "system": f"{system}"}} if debug: logging.info(f"OPA: enabled, using {OPA_URL}/{POLICY_PATH}") resp_opa = requests.post(f"{OPA_URL}/{POLICY_PATH}", json=input) logging.info(resp_opa.content) if resp_opa.json()["result"]["allow"]: logging.info(f"User {username} authorized by OPA") return {"allow": True, "description":f"User {username} authorized", "status_code": 200 } else: logging.error(f"User {username} NOT authorized by OPA") return {"allow": False, "description":f"User {username} not authorized in {system}", "status_code": 401} except requests.exceptions.RequestException as e: logging.error(e.args) return {"allow": False, "description":"Authorization server error", "status_code": 404} return {"allow": True, "description":"Authorization method not active", "status_code": 200 } # Checks each paramiko command output on a error execution # error_str: strerr (or strout) of the command # error_code: errno of the command # service_msg: service output in the "description" json response def check_command_error(error_str, error_code, service_msg): if error_code == -2: header = {"X-Machine-Not-Available": "Machine is not available"} return {"description": service_msg, "status_code": 400, "header": header} if error_code == 113: header = {"X-Machine-Not-Available":"Machine is not available"} return {"description": service_msg, "status_code": 400, "header": header} if error_code == 124: header = {"X-Timeout": "Command has finished with timeout signal"} return {"description": service_msg, "status_code": 400, "header": header} if error_code == 118: header = {"X-Error": "Command execution is not allowed in machine"} return {"description": service_msg, "status_code": 400, "header": header} # When certificate doesn't match SSH configuration if in_str(error_str,"OPENSSH"): header = {"X-Permission-Denied": "User does not have permissions to access machine"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str,"cannot access"): header={"X-Invalid-Path":"path is an invalid path"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str,"No such file"): if in_str(error_str,"cannot stat"): header={"X-Not-Found":"sourcePath not found"} return {"description": service_msg, "status_code": 400, "header": header} # copy: cannot create, rename: cannot move if in_str(error_str, "cannot create") or in_str(error_str,"cannot move"): header = {"X-Invalid-Path": "sourcePath and/or targetPath are invalid paths"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str,"cannot remove"): header = {"X-Invalid-Path": "path is an invalid path."} return {"description": service_msg, "status_code": 400, "header": header} header={"X-Invalid-Path":"path is an invalid path"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str,"cannot open"): header = {"X-Permission-Denied": "User does not have permissions to access path"} return {"description":service_msg, "status_code": 400, "header": header} if in_str(error_str,"Permission denied"): header = {"X-Permission-Denied": "User does not have permissions to access path"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str,"directory"): header = {"X-A-Directory": "path is a directory, can't checksum directories"} return {"description": service_msg, "status_code": 400, "header": header} # if already exists, not overwrite (-i) if in_str(error_str,"overwrite"): header = {"X-Exists": "targetPath already exists"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str,"not permitted"): header = {"X-Permission-Denied": "User does not have permissions to access path"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str,"invalid group"): header = {"X-Invalid-Group": "group is an invalid group"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str,"invalid user"): header = {"X-Invalid-Owner": "owner is an invalid user"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str, "invalid mode"): header = {"X-Invalid-Mode": "mode is an invalid mode"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str, "read permission"): header = {"X-Permission-Denied": "User does not have permissions to access path"} return {"description": service_msg, "status_code": 400, "header": header} header = {"X-Error": error_str} return {"description": service_msg, "error": error_str, "status_code": 400, "header": header} ## Test if user provided text is not empty and has no invalid chars def validate_input(text): if text == None: return "not specified" if text == "": return "is empty" if re.search(FORBIDDEN_INPUT_CHARS, text) != None: logging.warning(f'Forbidden char on: {base64.urlsafe_b64encode(text.encode()).decode()}') return "has invalid char" return "" # formatter is executed for every log class LogRequestFormatter(logging.Formatter): def format(self, record): try: # try to get TID from Flask g object, it's set on @app.before_request on each microservice record.TID = g.TID except: try: record.TID = threading.current_thread().name except: record.TID = 'notid' return super().format(record)
# # Copyright (c) 2019-2021, ETH Zurich. All rights reserved. # # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause # import logging import os import jwt import stat import datetime import hashlib import tempfile import json import functools from flask import request, jsonify, g import requests import urllib import base64 import io import re import time import threading # Checks if an environment variable injected to F7T is a valid True value # var <- object # returns -> boolean def get_boolean_var(var): # ensure variable to be a string var = str(var) # True, true or TRUE # Yes, yes or YES # 1 return var.upper() == "TRUE" or var.upper() == "YES" or var == "1" debug = get_boolean_var(os.environ.get("F7T_DEBUG_MODE", False)) AUTH_HEADER_NAME = 'Authorization' realm_pubkey=os.environ.get("F7T_REALM_RSA_PUBLIC_KEY", '') if realm_pubkey != '': # headers are inserted here, must not be present realm_pubkey = realm_pubkey.strip('\'"') # remove '"' realm_pubkey = '-----BEGIN PUBLIC KEY-----\n' + realm_pubkey + '\n-----END PUBLIC KEY-----' realm_pubkey_type = os.environ.get("F7T_REALM_RSA_TYPE").strip('\'"') AUTH_AUDIENCE = os.environ.get("F7T_AUTH_TOKEN_AUD", '').strip('\'"') ALLOWED_USERS = os.environ.get("F7T_AUTH_ALLOWED_USERS", '').strip('\'"').split(";") AUTH_REQUIRED_SCOPE = os.environ.get("F7T_AUTH_REQUIRED_SCOPE", '').strip('\'"') AUTH_ROLE = os.environ.get("F7T_AUTH_ROLE", '').strip('\'"') CERTIFICATOR_URL = os.environ.get("F7T_CERTIFICATOR_URL") TASKS_URL = os.environ.get("F7T_TASKS_URL") F7T_SSH_CERTIFICATE_WRAPPER = get_boolean_var(os.environ.get("F7T_SSH_CERTIFICATE_WRAPPER", False)) # Fobidden chars on user path/parameters: wihtout scapes: < > | ; " ' & \ [ ] ( ) x00-x1F \x60 # r'...' specifies it's a regular expression with special treatment for \ FORBIDDEN_INPUT_CHARS = r'[\<\>\|\;\"\'\&\\\[\]\(\)\x00-\x1F\x60]' # OPA endpoint OPA_USE = get_boolean_var(os.environ.get("F7T_OPA_USE",False)) OPA_URL = os.environ.get("F7T_OPA_URL","http://localhost:8181").strip('\'"') POLICY_PATH = os.environ.get("F7T_POLICY_PATH","v1/data/f7t/authz").strip('\'"') ### SSL parameters USE_SSL = get_boolean_var(os.environ.get("F7T_USE_SSL", False)) SSL_CRT = os.environ.get("F7T_SSL_CRT", "") SSL_KEY = os.environ.get("F7T_SSL_KEY", "") TRACER_HEADER = "uber-trace-id" # checks JWT from Keycloak, optionally validates signature. It only receives the content of header's auth pair (not key:content) def check_header(header): if debug: logging.info('debug: header: ' + header) # header = "Bearer ey...", remove first 7 chars try: if realm_pubkey == '': if not debug: logging.warning("WARNING: REALM_RSA_PUBLIC_KEY is empty, JWT tokens are NOT verified, setup is not set to debug.") decoded = jwt.decode(header[7:], verify=False) else: if AUTH_AUDIENCE == '': decoded = jwt.decode(header[7:], realm_pubkey, algorithms=realm_pubkey_type, options={'verify_aud': False}) else: decoded = jwt.decode(header[7:], realm_pubkey, algorithms=realm_pubkey_type, audience=AUTH_AUDIENCE) if AUTH_REQUIRED_SCOPE != "": if AUTH_REQUIRED_SCOPE not in decoded["scope"].split(): return False return True except jwt.exceptions.InvalidSignatureError: logging.error("JWT invalid signature", exc_info=True) except jwt.ExpiredSignatureError: logging.error("JWT token has expired", exc_info=True) except jwt.InvalidAudienceError: logging.error("JWT token invalid audience", exc_info=True) except jwt.exceptions.InvalidAlgorithmError: logging.error("JWT invalid signature algorithm", exc_info=True) except Exception: logging.error("Bad header or JWT, general exception raised", exc_info=True) return False # returns username def get_username(header): # header = "Bearer ey...", remove first 7 chars try: if realm_pubkey == '': decoded = jwt.decode(header[7:], verify=False) else: decoded = jwt.decode(header[7:], realm_pubkey, algorithms=realm_pubkey_type, options={'verify_aud': False}) # check if it's a service account token try: if AUTH_ROLE in decoded["realm_access"]["roles"]: clientId = decoded["clientId"] username = decoded["resource_access"][clientId]["roles"][0] return username return decoded['preferred_username'] except Exception: return decoded['preferred_username'] except jwt.exceptions.InvalidSignatureError: logging.error("JWT invalid signature", exc_info=True) except jwt.ExpiredSignatureError: logging.error("JWT token has expired", exc_info=True) except jwt.InvalidAudienceError: logging.error("JWT token invalid audience", exc_info=True) except jwt.exceptions.InvalidAlgorithmError: logging.error("JWT invalid signature algorithm", exc_info=True) except Exception: logging.error("Bad header or JWT, general exception raised", exc_info=True) return None # function to check if pattern is in string def in_str(stringval,words): try: stringval.index(words) return True except ValueError: return False # SSH certificates creation # returns pub key certificate name def create_certificate(headers, cluster_name, cluster_addr, command=None, options=None, exp_time=None): """ Args: cluster_name = public name of system to be executed cluster_addr = private DNS or IP of the system command = command to be executed with the certificate (required) option = parameters and options to be executed with {command} exp_time = expiration time for SSH certificate """ reqURL = f"{CERTIFICATOR_URL}/?cluster={cluster_name}&addr={cluster_addr}" if command: logging.info(f"\tCommand: {command}") reqURL += "&command=" + base64.urlsafe_b64encode(command.encode()).decode() if options: logging.info(f"\tOptions (truncated): {options:80}") reqURL += "&option=" + base64.urlsafe_b64encode(options.encode()).decode() if exp_time: logging.info(f"\tExpiration: {exp_time} [s]") reqURL += f"&exptime={exp_time}" else: logging.error('Tried to create certificate without command') return [None, 1, 'Internal error'] if debug: username = get_username(headers[AUTH_HEADER_NAME]) logging.info(f"Create certificate for user {username}") if options: # may contain Storage URL logging.info(f"\tOptions (complete): {options}") logging.info(f"Request URL: {reqURL}") try: resp = requests.get(reqURL, headers=headers, verify= (SSL_CRT if USE_SSL else False) ) if resp.status_code != 200: return [None, resp.status_code, resp.json()["description"]] jcert = resp.json() # create temp dir to store certificate for this request td = tempfile.mkdtemp(prefix="dummy") os.symlink(os.getcwd() + "/user-key.pub", td + "/user-key.pub") # link on temp dir os.symlink(os.getcwd() + "/user-key", td + "/user-key") # link on temp dir certf = open(td + "/user-key-cert.pub", 'w') certf.write(jcert["certificate"]) certf.close() # stat.S_IRUSR -> owner has read permission os.chmod(td + "/user-key-cert.pub", stat.S_IRUSR) # keys: [pub_cert, pub_key, priv_key, temp_dir] return [td + "/user-key-cert.pub", td + "/user-key.pub", td + "/user-key", td] except requests.exceptions.SSLError as ssle: logging.error(f"(-2) -> {ssle}") logging.error(f"(-2) -> {ssle.strerror}") return [None, -2, ssle] except IOError as ioe: logging.error(f"({ioe.errno}) -> {ioe.strerror}", exc_info=True) return [None, ioe.errno, ioe.strerror] except Exception as e: logging.error(f"({type(e)}) -> {e}", exc_info=True) return [None, -1, e] # execute remote commands with Paramiko: def exec_remote_command(headers, system_name, system_addr, action, file_transfer=None, file_content=None): import paramiko, socket logging.info(f'System name: {system_name} - action: {action}') if file_transfer == "storage_cert": # storage is using a previously generated cert, save cert list from content # cert_list: list of 4 elements that contains # [0] path to the public certificate # [1] path to the public key for user # [2] path to the priv key for user # [3] path to the dir containing 3 previous files cert_list = file_content username = headers else: # get certificate: # if OK returns: [pub_cert, pub_key, priv_key, temp_dir] # if FAILED returns: [None, errno, strerror] cert_list = create_certificate(headers, system_name, system_addr, command=action) if cert_list[0] == None: result = {"error": cert_list[1], "msg": cert_list[2]} return result username = get_username(headers[AUTH_HEADER_NAME]) [pub_cert, pub_key, priv_key, temp_dir] = cert_list # ------------------- # remote exec with paramiko try: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ipaddr = system_addr.split(':') host = ipaddr[0] if len(ipaddr) == 1: port = 22 else: port = int(ipaddr[1]) client.connect(hostname=host, port=port, username=username, key_filename=pub_cert, allow_agent=False, look_for_keys=False, timeout=10) if F7T_SSH_CERTIFICATE_WRAPPER: if debug: logging.info(f"Using F7T_SSH_CERTIFICATE_WRAPPER.") # read cert to send it as a command to the server with open(pub_cert, 'r') as cert_file: cert = cert_file.read().rstrip("\n") # remove newline at the end action = cert stdin, stdout, stderr = client.exec_command(action) if file_transfer == "upload": # uploads use "cat", so write to stdin stdin.channel.sendall(file_content) stdin.channel.shutdown_write() #stdin.channel.close() output = "" error = "" finished = 0 stderr_errno = -2 stdout_errno = -2 stderr_errda = "" stdout_errda = "" # poll process status since directly using recv_exit_status() could result # in a permanent hang when remote output is larger than the current Transport or session’s window_size while True: if stderr.channel.exit_status_ready(): logging.info(f"stderr channel exit status ready") stderr_errno = stderr.channel.recv_exit_status() endtime = time.time() + 30 eof_received = True while not stderr.channel.eof_received: # time.sleep(0.5) if time.time() > endtime: stderr.channel.close() eof_received = False break if eof_received: error = "".join(stderr.readlines()) # error = stderr.read() # clean "tput: No ..." lines at error output stderr_errda = clean_err_output(error) break # else: # time.sleep(5) #for i in range(0,10): while True: if stdout.channel.exit_status_ready(): logging.info(f"stdout channel exit status ready") stdout_errno = stdout.channel.recv_exit_status() endtime = time.time() + 30 eof_received = True while not stdout.channel.eof_received: # time.sleep(0.5) if time.time() > endtime: stdout.channel.close() eof_received = False break if eof_received: output = "".join(stdout.readlines()) # error = stderr.read() it hangs # clean "tput: No ..." lines at error output stdout_errda = clean_err_output(output) break # else: # time.sleep(5) if file_transfer == "download": outlines = output else: # replace newlines with $ for parsing outlines = output.replace('\n', '$')[:-1] # hiding success results from utilities/download, since output is the content of the file if file_transfer == "download": if stderr_errno !=0: logging.info(f"stderr: ({stderr_errno}) --> {stderr_errda}") logging.info(f"stdout: ({stdout_errno}) --> {stdout_errda}") logging.info(f"stdout: ({stdout_errno}) --> {outlines}") else: logging.info(f"stderr: ({stderr_errno}) --> Download OK (content hidden)") logging.info(f"stdout: ({stdout_errno}) --> Download OK (content hidden)") else: logging.info(f"stderr: ({stderr_errno}) --> {stderr_errda}") logging.info(f"stdout: ({stdout_errno}) --> {stdout_errda}") logging.info(f"stdout: ({stdout_errno}) --> {outlines}") if stderr_errno == 0: if stderr_errda and not (in_str(stderr_errda,"Could not chdir to home directory") or in_str(stderr_errda,"scancel: Terminating job")): result = {"error": 1, "msg": stderr_errda} elif in_str(stdout_errda, "No such file"): # in case that error is 0 and the msg is on the stdout (like with some file) result = {"error": 1, "msg": stdout_errda} elif in_str(stdout_errda, "no read permission"): # in case that error is 0 and the msg is on the stdout (like with some file) result = {"error": 1, "msg": stdout_errda} elif in_str(stdout_errda, "cannot open"): # in case that error is 0 and the msg is on the stdout (like with some file) result = {"error": 1, "msg": stdout_errda} else: result = {"error": 0, "msg": outlines} elif stderr_errno > 0: if stderr_errno == 7: result = {"error": 7, "msg": "Failed to connect to staging area server"} else: result = {"error": stderr_errno, "msg": stderr_errda or stdout_errda} elif len(stderr_errda) > 0: result = {"error": 1, "msg": stderr_errda} elif stdout_errno == -2: result = {"error": -2, "msg": "Receive ready timeout exceeded"} elif stderr_errno == -1: result = {"error": -1, "msg": "No exit status was provided by the server"} # first if paramiko exception raise except paramiko.ssh_exception.NoValidConnectionsError as e: logging.error(type(e), exc_info=True) if e.errors: for k, v in e.errors.items(): logging.error(f"errorno: {v.errno}") logging.error(f"strerr: {v.strerror}") result = {"error": v.errno, "msg": v.strerror} except socket.gaierror as e: logging.error(type(e), exc_info=True) logging.error(e.errno) logging.error(e.strerror) result = {"error": e.errno, "msg": e.strerror} except paramiko.ssh_exception.SSHException as e: logging.error(type(e), exc_info=True) logging.error(e) result = {"error": 1, "msg": str(e)} # second: time out except socket.timeout as e: logging.error(type(e), exc_info=True) # timeout has not errno logging.error(e) result = {"error": 1, "msg": e.strerror} except Exception as e: logging.error(type(e), exc_info=True) result = {"error": 1, "msg": str(e)} finally: client.close() os.remove(pub_cert) os.remove(pub_key) os.remove(priv_key) os.rmdir(temp_dir) # hiding results from utilities/download, since output is the content of the file if file_transfer == "download": logging.info(f"Result: status_code {result['error']} -> Utilities download") else: logging.info(f"Result: status_code {result['error']} -> {result['msg']}") return result # clean TERM errors on stderr # resaon: some servers produces this error becuase don't set a TERM def clean_err_output(tex): lines = "" # python3 tex comes as a byte object, needs to be decoded to a str #tex = tex.decode('utf-8') for t in tex.split('\n'): if t != 'tput: No value for $TERM and no -T specified': lines += t return lines def parse_io_error(retval, operation, path): """ As command ended with error, create message to return to user Args: retval (from exec_remote_command) operation, path: return: jsonify('error message'), error_code (4xx), optional_header """ header = '' if retval["error"] == 13: # IOError 13: Permission denied header = {"X-Permission-Denied": "User does not have permissions to access machine or paths"} elif retval["error"] == 2: # IOError 2: no such file header = {"X-Invalid-Path": f"{path} is invalid."} elif retval["error"] == -2: # IOError -2: name or service not known header = {"X-Machine-Not-Available": "Machine is not available"} elif retval["error"] == 118: header = {"X-Permission-Denied": "Internal SSH error"} elif in_str(retval["msg"],"Permission") or in_str(retval["msg"],"OPENSSH"): header = {"X-Permission-Denied": "User does not have permissions to access machine or paths"} return jsonify(description = f"Failed to {operation}"), 400, header # function to call create task entry API in Queue FS, returns task_id for new task def create_task(headers, service=None): # returns {"task_id":task_id} # first try to get up task microservice: try: # X-Firecrest-Service: service that created the task headers["X-Firecrest-Service"] = service req = requests.post(f"{TASKS_URL}/", headers=headers, verify=(SSL_CRT if USE_SSL else False)) except requests.exceptions.ConnectionError as e: logging.error(type(e), exc_info=True) logging.error(e) return -1 if req.status_code != 201: return -1 logging.info(json.loads(req.content)) resp = json.loads(req.content) task_id = resp["hash_id"] return task_id # function to call update task entry API in Queue FS def update_task(task_id, headers, status, msg=None, is_json=False): logging.info(f"Update {TASKS_URL}/{task_id} -> status: {status}") data = {"status": status, "msg": msg} if is_json: req = requests.put(f"{TASKS_URL}/{task_id}", json=data, headers=headers, verify=(SSL_CRT if USE_SSL else False)) else: req = requests.put(f"{TASKS_URL}/{task_id}", data=data, headers=headers, verify=(SSL_CRT if USE_SSL else False)) resp = json.loads(req.content) return resp # function to call update task entry API in Queue FS def expire_task(task_id, headers, service): logging.info(f"{TASKS_URL}/expire/{task_id}") try: headers["X-Firecrest-Service"] = service req = requests.post(f"{TASKS_URL}/expire/{task_id}", headers=headers, verify=(SSL_CRT if USE_SSL else False)) except Exception as e: logging.error(type(e)) logging.error(e.args) if not req.ok: logging.info(req.json()) return False return True # function to check task status: def get_task_status(task_id, headers): logging.info(f"{TASKS_URL}/{task_id}") try: retval = requests.get(f"{TASKS_URL}/{task_id}", headers=headers, verify=(SSL_CRT if USE_SSL else False)) if retval.status_code != 200: return -1 data = retval.json() logging.info(data["task"]["status"]) return data["task"]["status"] except Exception as e: logging.error(type(e), exc_info=True) logging.error(e) return -1 # checks if {path} is a valid file (exists and user in {auth_header} has read permissions) def is_valid_file(path, headers, system_name, system_addr): ID = headers.get(TRACER_HEADER, '') # checks user accessibility to path using head command with 0 bytes action = f"ID={ID} head -c 1 -- '{path}' > /dev/null" retval = exec_remote_command(headers, system_name, system_addr, action) logging.info(retval) if retval["error"] != 0: error_str=retval["msg"] if retval["error"] == 113: return {"result":False, "headers":{"X-Machine-Not-Available":"Machine is not available"} } if retval["error"] == 124: return {"result":False, "headers":{"X-Timeout": "Command has finished with timeout signal"}} # error no such file if in_str(error_str,"No such file"): return {"result":False, "headers":{"X-Invalid-Path": f"{path} is an invalid path."}} # permission denied if in_str(error_str,"Permission denied") or in_str(error_str,"OPENSSH"): return {"result":False, "headers":{"X-Permission-Denied": "User does not have permissions to access machine or path"}} if in_str(error_str, "directory"): return {"result":False, "headers":{"X-A-Directory": f"{path} is a directory"}} return {"result":False, "headers":{"X-Error": retval["msg"]}} return {"result":True} # checks if {path} is a valid directory # 'path' should exists and be accesible to the user (write permissions) # def is_valid_dir(path, headers, system_name, system_addr): # create an empty file for testing path accesibility # test file is a hidden file and has a timestamp in order to not overwrite other files created by user # after this, file should be deleted timestamp = datetime.datetime.today().strftime("%Y-%m-%dT%H:%M:%S.%f") # using a hash hashedTS = hashlib.md5() hashedTS.update(timestamp.encode("utf-8")) tempFileName = f".firecrest.{hashedTS.hexdigest()}" ID = headers.get(TRACER_HEADER, '') action = f"ID={ID} touch -- '{path}/{tempFileName}'" retval = exec_remote_command(headers, system_name, system_addr, action) logging.info(retval) if retval["error"] != 0: error_str=retval["msg"] if retval["error"] == 113: return {"result":False, "headers":{"X-Machine-Not-Available":"Machine is not available"} } if retval["error"] == 124: return {"result":False, "headers":{"X-Timeout": "Command has finished with timeout signal"}} # error no such file if in_str(error_str,"No such file"): return {"result":False, "headers":{"X-Invalid-Path": f"{path} is an invalid path."}} # permission denied if in_str(error_str,"Permission denied") or in_str(error_str,"OPENSSH"): return {"result":False, "headers":{"X-Permission-Denied": "User does not have permissions to access machine or path"}} # not a directory if in_str(error_str,"Not a directory"): return {"result":False, "headers":{"X-Not-A-Directory": f"{path} is not a directory"}} return {"result":False, "headers":{"X-Error": retval["msg"]}} # delete test file created action = f"ID={ID} rm -- '{path}/{tempFileName}'" retval = exec_remote_command(headers, system_name, system_addr, action) return {"result":True} # wrapper to check if AUTH header is correct # decorator use: # # @app.route("/endpoint", methods=["GET","..."]) # @check_auth_header # def function_that_check_header(): # ..... def check_auth_header(func): @functools.wraps(func) def wrapper_check_auth_header(*args, **kwargs): try: auth_header = request.headers[AUTH_HEADER_NAME] except KeyError: logging.error("No Auth Header given") return jsonify(description="No Auth Header given"), 401 if not check_header(auth_header): return jsonify(description="Invalid header"), 401 return func(*args, **kwargs) return wrapper_check_auth_header # check user authorization on endpoint # using Open Policy Agent # # use: # check_user_auth(username,system) def check_user_auth(username,system): # check if OPA is active if OPA_USE: try: input = {"input":{"user": f"{username}", "system": f"{system}"}} if debug: logging.info(f"OPA: enabled, using {OPA_URL}/{POLICY_PATH}") resp_opa = requests.post(f"{OPA_URL}/{POLICY_PATH}", json=input) logging.info(resp_opa.content) if resp_opa.json()["result"]["allow"]: logging.info(f"User {username} authorized by OPA") return {"allow": True, "description":f"User {username} authorized", "status_code": 200 } else: logging.error(f"User {username} NOT authorized by OPA") return {"allow": False, "description":f"User {username} not authorized in {system}", "status_code": 401} except requests.exceptions.RequestException as e: logging.error(e.args) return {"allow": False, "description":"Authorization server error", "status_code": 404} return {"allow": True, "description":"Authorization method not active", "status_code": 200 } # Checks each paramiko command output on a error execution # error_str: strerr (or strout) of the command # error_code: errno of the command # service_msg: service output in the "description" json response def check_command_error(error_str, error_code, service_msg): if error_code == -2: header = {"X-Machine-Not-Available": "Machine is not available"} return {"description": service_msg, "status_code": 400, "header": header} if error_code == 113: header = {"X-Machine-Not-Available":"Machine is not available"} return {"description": service_msg, "status_code": 400, "header": header} if error_code == 124: header = {"X-Timeout": "Command has finished with timeout signal"} return {"description": service_msg, "status_code": 400, "header": header} if error_code == 118: header = {"X-Error": "Command execution is not allowed in machine"} return {"description": service_msg, "status_code": 400, "header": header} # When certificate doesn't match SSH configuration if in_str(error_str,"OPENSSH"): header = {"X-Permission-Denied": "User does not have permissions to access machine"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str,"cannot access"): header={"X-Invalid-Path":"path is an invalid path"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str,"No such file"): if in_str(error_str,"cannot stat"): header={"X-Not-Found":"sourcePath not found"} return {"description": service_msg, "status_code": 400, "header": header} # copy: cannot create, rename: cannot move if in_str(error_str, "cannot create") or in_str(error_str,"cannot move"): header = {"X-Invalid-Path": "sourcePath and/or targetPath are invalid paths"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str,"cannot remove"): header = {"X-Invalid-Path": "path is an invalid path."} return {"description": service_msg, "status_code": 400, "header": header} header={"X-Invalid-Path":"path is an invalid path"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str,"cannot open"): header = {"X-Permission-Denied": "User does not have permissions to access path"} return {"description":service_msg, "status_code": 400, "header": header} if in_str(error_str,"Permission denied"): header = {"X-Permission-Denied": "User does not have permissions to access path"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str,"directory"): header = {"X-A-Directory": "path is a directory, can't checksum directories"} return {"description": service_msg, "status_code": 400, "header": header} # if already exists, not overwrite (-i) if in_str(error_str,"overwrite"): header = {"X-Exists": "targetPath already exists"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str,"not permitted"): header = {"X-Permission-Denied": "User does not have permissions to access path"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str,"invalid group"): header = {"X-Invalid-Group": "group is an invalid group"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str,"invalid user"): header = {"X-Invalid-Owner": "owner is an invalid user"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str, "invalid mode"): header = {"X-Invalid-Mode": "mode is an invalid mode"} return {"description": service_msg, "status_code": 400, "header": header} if in_str(error_str, "read permission"): header = {"X-Permission-Denied": "User does not have permissions to access path"} return {"description": service_msg, "status_code": 400, "header": header} header = {"X-Error": error_str} return {"description": service_msg, "error": error_str, "status_code": 400, "header": header} ## Test if user provided text is not empty and has no invalid chars def validate_input(text): if text == None: return "not specified" if text == "": return "is empty" if re.search(FORBIDDEN_INPUT_CHARS, text) != None: logging.warning(f'Forbidden char on: {base64.urlsafe_b64encode(text.encode()).decode()}') return "has invalid char" return "" # formatter is executed for every log class LogRequestFormatter(logging.Formatter): def format(self, record): try: # try to get TID from Flask g object, it's set on @app.before_request on each microservice record.TID = g.TID except: try: record.TID = threading.current_thread().name except: record.TID = 'notid' return super().format(record)
# -*- coding: utf-8 -*- """Tools for working with epoched data.""" # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Matti Hämäläinen <msh@nmr.mgh.harvard.edu> # Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de> # Denis Engemann <denis.engemann@gmail.com> # Mainak Jas <mainak@neuro.hut.fi> # Stefan Appelhoff <stefan.appelhoff@mailbox.org> # # License: BSD-3-Clause from functools import partial from collections import Counter from copy import deepcopy import json import operator import os.path as op import numpy as np from .io.utils import _construct_bids_filename from .io.write import (start_and_end_file, start_block, end_block, write_int, write_float, write_float_matrix, write_double_matrix, write_complex_float_matrix, write_complex_double_matrix, write_id, write_string, _get_split_size, _NEXT_FILE_BUFFER, INT32_MAX) from .io.meas_info import (read_meas_info, write_meas_info, _merge_info, _ensure_infos_match) from .io.open import fiff_open, _get_next_fname from .io.tree import dir_tree_find from .io.tag import read_tag, read_tag_info from .io.constants import FIFF from .io.fiff.raw import _get_fname_rep from .io.pick import (channel_indices_by_type, channel_type, pick_channels, pick_info, _pick_data_channels, _DATA_CH_TYPES_SPLIT, _picks_to_idx) from .io.proj import setup_proj, ProjMixin from .io.base import BaseRaw, TimeMixin, _get_ch_factors from .bem import _check_origin from .evoked import EvokedArray, _check_decim from .baseline import rescale, _log_rescale, _check_baseline from .channels.channels import (ContainsMixin, UpdateChannelsMixin, SetChannelsMixin, InterpolationMixin) from .filter import detrend, FilterMixin, _check_fun from .parallel import parallel_func from .event import (_read_events_fif, make_fixed_length_events, match_event_names) from .fixes import rng_uniform from .viz import (plot_epochs, plot_epochs_psd, plot_epochs_psd_topomap, plot_epochs_image, plot_topo_image_epochs, plot_drop_log) from .utils import (_check_fname, check_fname, logger, verbose, _time_mask, check_random_state, warn, _pl, sizeof_fmt, SizeMixin, copy_function_doc_to_method_doc, _check_pandas_installed, _check_preload, GetEpochsMixin, _prepare_read_metadata, _prepare_write_metadata, _check_event_id, _gen_events, _check_option, _check_combine, ShiftTimeMixin, _build_data_frame, _check_pandas_index_arguments, _convert_times, _scale_dataframe_data, _check_time_format, object_size, _on_missing, _validate_type, _ensure_events, _path_like, _VerboseDep) from .utils.docs import fill_doc from .annotations import (_write_annotations, _read_annotations_fif, EpochAnnotationsMixin) def _pack_reject_params(epochs): reject_params = dict() for key in ('reject', 'flat', 'reject_tmin', 'reject_tmax'): val = getattr(epochs, key, None) if val is not None: reject_params[key] = val return reject_params def _save_split(epochs, fname, part_idx, n_parts, fmt, split_naming, overwrite): """Split epochs. Anything new added to this function also needs to be added to BaseEpochs.save to account for new file sizes. """ # insert index in filename base, ext = op.splitext(fname) if part_idx > 0: if split_naming == 'neuromag': fname = '%s-%d%s' % (base, part_idx, ext) else: assert split_naming == 'bids' fname = _construct_bids_filename(base, ext, part_idx, validate=False) _check_fname(fname, overwrite=overwrite) next_fname = None if part_idx < n_parts - 1: if split_naming == 'neuromag': next_fname = '%s-%d%s' % (base, part_idx + 1, ext) else: assert split_naming == 'bids' next_fname = _construct_bids_filename(base, ext, part_idx + 1, validate=False) next_idx = part_idx + 1 else: next_idx = None with start_and_end_file(fname) as fid: _save_part(fid, epochs, fmt, n_parts, next_fname, next_idx) def _save_part(fid, epochs, fmt, n_parts, next_fname, next_idx): info = epochs.info meas_id = info['meas_id'] start_block(fid, FIFF.FIFFB_MEAS) write_id(fid, FIFF.FIFF_BLOCK_ID) if info['meas_id'] is not None: write_id(fid, FIFF.FIFF_PARENT_BLOCK_ID, info['meas_id']) # Write measurement info write_meas_info(fid, info) # One or more evoked data sets start_block(fid, FIFF.FIFFB_PROCESSED_DATA) start_block(fid, FIFF.FIFFB_MNE_EPOCHS) # write events out after getting data to ensure bad events are dropped data = epochs.get_data() _check_option('fmt', fmt, ['single', 'double']) if np.iscomplexobj(data): if fmt == 'single': write_function = write_complex_float_matrix elif fmt == 'double': write_function = write_complex_double_matrix else: if fmt == 'single': write_function = write_float_matrix elif fmt == 'double': write_function = write_double_matrix # Epoch annotations are written if there are any annotations = getattr(epochs, 'annotations', []) if annotations is not None and len(annotations): _write_annotations(fid, annotations) # write Epoch event windows start_block(fid, FIFF.FIFFB_MNE_EVENTS) write_int(fid, FIFF.FIFF_MNE_EVENT_LIST, epochs.events.T) write_string(fid, FIFF.FIFF_DESCRIPTION, _event_id_string(epochs.event_id)) end_block(fid, FIFF.FIFFB_MNE_EVENTS) # Metadata if epochs.metadata is not None: start_block(fid, FIFF.FIFFB_MNE_METADATA) metadata = _prepare_write_metadata(epochs.metadata) write_string(fid, FIFF.FIFF_DESCRIPTION, metadata) end_block(fid, FIFF.FIFFB_MNE_METADATA) # First and last sample first = int(round(epochs.tmin * info['sfreq'])) # round just to be safe last = first + len(epochs.times) - 1 write_int(fid, FIFF.FIFF_FIRST_SAMPLE, first) write_int(fid, FIFF.FIFF_LAST_SAMPLE, last) # write raw original sampling rate write_float(fid, FIFF.FIFF_MNE_EPOCHS_RAW_SFREQ, epochs._raw_sfreq) # save baseline if epochs.baseline is not None: bmin, bmax = epochs.baseline write_float(fid, FIFF.FIFF_MNE_BASELINE_MIN, bmin) write_float(fid, FIFF.FIFF_MNE_BASELINE_MAX, bmax) # The epochs itself decal = np.empty(info['nchan']) for k in range(info['nchan']): decal[k] = 1.0 / (info['chs'][k]['cal'] * info['chs'][k].get('scale', 1.0)) data *= decal[np.newaxis, :, np.newaxis] write_function(fid, FIFF.FIFF_EPOCH, data) # undo modifications to data data /= decal[np.newaxis, :, np.newaxis] write_string(fid, FIFF.FIFF_MNE_EPOCHS_DROP_LOG, json.dumps(epochs.drop_log)) reject_params = _pack_reject_params(epochs) if reject_params: write_string(fid, FIFF.FIFF_MNE_EPOCHS_REJECT_FLAT, json.dumps(reject_params)) write_int(fid, FIFF.FIFF_MNE_EPOCHS_SELECTION, epochs.selection) # And now write the next file info in case epochs are split on disk if next_fname is not None and n_parts > 1: start_block(fid, FIFF.FIFFB_REF) write_int(fid, FIFF.FIFF_REF_ROLE, FIFF.FIFFV_ROLE_NEXT_FILE) write_string(fid, FIFF.FIFF_REF_FILE_NAME, op.basename(next_fname)) if meas_id is not None: write_id(fid, FIFF.FIFF_REF_FILE_ID, meas_id) write_int(fid, FIFF.FIFF_REF_FILE_NUM, next_idx) end_block(fid, FIFF.FIFFB_REF) end_block(fid, FIFF.FIFFB_MNE_EPOCHS) end_block(fid, FIFF.FIFFB_PROCESSED_DATA) end_block(fid, FIFF.FIFFB_MEAS) def _event_id_string(event_id): return ';'.join([k + ':' + str(v) for k, v in event_id.items()]) def _merge_events(events, event_id, selection): """Merge repeated events.""" event_id = event_id.copy() new_events = events.copy() event_idxs_to_delete = list() unique_events, counts = np.unique(events[:, 0], return_counts=True) for ev in unique_events[counts > 1]: # indices at which the non-unique events happened idxs = (events[:, 0] == ev).nonzero()[0] # Figure out new value for events[:, 1]. Set to 0, if mixed vals exist unique_priors = np.unique(events[idxs, 1]) new_prior = unique_priors[0] if len(unique_priors) == 1 else 0 # If duplicate time samples have same event val, "merge" == "drop" # and no new event_id key will be created ev_vals = np.unique(events[idxs, 2]) if len(ev_vals) <= 1: new_event_val = ev_vals[0] # Else, make a new event_id for the merged event else: # Find all event_id keys involved in duplicated events. These # keys will be merged to become a new entry in "event_id" event_id_keys = list(event_id.keys()) event_id_vals = list(event_id.values()) new_key_comps = [event_id_keys[event_id_vals.index(value)] for value in ev_vals] # Check if we already have an entry for merged keys of duplicate # events ... if yes, reuse it for key in event_id: if set(key.split('/')) == set(new_key_comps): new_event_val = event_id[key] break # Else, find an unused value for the new key and make an entry into # the event_id dict else: ev_vals = np.unique( np.concatenate((list(event_id.values()), events[:, 1:].flatten()), axis=0)) if ev_vals[0] > 1: new_event_val = 1 else: diffs = np.diff(ev_vals) idx = np.where(diffs > 1)[0] idx = -1 if len(idx) == 0 else idx[0] new_event_val = ev_vals[idx] + 1 new_event_id_key = '/'.join(sorted(new_key_comps)) event_id[new_event_id_key] = int(new_event_val) # Replace duplicate event times with merged event and remember which # duplicate indices to delete later new_events[idxs[0], 1] = new_prior new_events[idxs[0], 2] = new_event_val event_idxs_to_delete.extend(idxs[1:]) # Delete duplicate event idxs new_events = np.delete(new_events, event_idxs_to_delete, 0) new_selection = np.delete(selection, event_idxs_to_delete, 0) return new_events, event_id, new_selection def _handle_event_repeated(events, event_id, event_repeated, selection, drop_log): """Handle repeated events. Note that drop_log will be modified inplace """ assert len(events) == len(selection) selection = np.asarray(selection) unique_events, u_ev_idxs = np.unique(events[:, 0], return_index=True) # Return early if no duplicates if len(unique_events) == len(events): return events, event_id, selection, drop_log # Else, we have duplicates. Triage ... _check_option('event_repeated', event_repeated, ['error', 'drop', 'merge']) drop_log = list(drop_log) if event_repeated == 'error': raise RuntimeError('Event time samples were not unique. Consider ' 'setting the `event_repeated` parameter."') elif event_repeated == 'drop': logger.info('Multiple event values for single event times found. ' 'Keeping the first occurrence and dropping all others.') new_events = events[u_ev_idxs] new_selection = selection[u_ev_idxs] drop_ev_idxs = np.setdiff1d(selection, new_selection) for idx in drop_ev_idxs: drop_log[idx] = drop_log[idx] + ('DROP DUPLICATE',) selection = new_selection elif event_repeated == 'merge': logger.info('Multiple event values for single event times found. ' 'Creating new event value to reflect simultaneous events.') new_events, event_id, new_selection = \ _merge_events(events, event_id, selection) drop_ev_idxs = np.setdiff1d(selection, new_selection) for idx in drop_ev_idxs: drop_log[idx] = drop_log[idx] + ('MERGE DUPLICATE',) selection = new_selection drop_log = tuple(drop_log) # Remove obsolete kv-pairs from event_id after handling keys = new_events[:, 1:].flatten() event_id = {k: v for k, v in event_id.items() if v in keys} return new_events, event_id, selection, drop_log @fill_doc class BaseEpochs(ProjMixin, ContainsMixin, UpdateChannelsMixin, ShiftTimeMixin, SetChannelsMixin, InterpolationMixin, FilterMixin, TimeMixin, SizeMixin, GetEpochsMixin, EpochAnnotationsMixin, _VerboseDep): """Abstract base class for `~mne.Epochs`-type classes. .. warning:: This class provides basic functionality and should never be instantiated directly. Parameters ---------- %(info_not_none)s data : ndarray | None If ``None``, data will be read from the Raw object. If ndarray, must be of shape (n_epochs, n_channels, n_times). %(events_epochs)s %(event_id)s %(epochs_tmin_tmax)s %(baseline_epochs)s Defaults to ``(None, 0)``, i.e. beginning of the the data until time point zero. %(epochs_raw)s %(picks_all)s %(reject_epochs)s %(flat)s %(decim)s %(epochs_reject_tmin_tmax)s %(epochs_detrend)s %(proj_epochs)s %(epochs_on_missing)s preload_at_end : bool %(epochs_preload)s selection : iterable | None Iterable of indices of selected epochs. If ``None``, will be automatically generated, corresponding to all non-zero events. drop_log : tuple | None Tuple of tuple of strings indicating which epochs have been marked to be ignored. filename : str | None The filename (if the epochs are read from disk). %(epochs_metadata)s %(epochs_event_repeated)s %(verbose)s raw_sfreq : float The original Raw object sampling rate. If None, then it is set to ``info['sfreq']``. annotations : instance of mne.Annotations | None Annotations to set. Notes ----- The ``BaseEpochs`` class is public to allow for stable type-checking in user code (i.e., ``isinstance(my_epochs, BaseEpochs)``) but should not be used as a constructor for Epochs objects (use instead :class:`mne.Epochs`). """ @verbose def __init__(self, info, data, events, event_id=None, tmin=-0.2, tmax=0.5, baseline=(None, 0), raw=None, picks=None, reject=None, flat=None, decim=1, reject_tmin=None, reject_tmax=None, detrend=None, proj=True, on_missing='raise', preload_at_end=False, selection=None, drop_log=None, filename=None, metadata=None, event_repeated='error', *, verbose=None, raw_sfreq=None, annotations=None): # noqa: D102 if events is not None: # RtEpochs can have events=None events = _ensure_events(events) events_max = events.max() if events_max > INT32_MAX: raise ValueError( f'events array values must not exceed {INT32_MAX}, ' f'got {events_max}') event_id = _check_event_id(event_id, events) self.event_id = event_id del event_id if events is not None: # RtEpochs can have events=None for key, val in self.event_id.items(): if val not in events[:, 2]: msg = ('No matching events found for %s ' '(event id %i)' % (key, val)) _on_missing(on_missing, msg) # ensure metadata matches original events size self.selection = np.arange(len(events)) self.events = events # same as self.metadata = metadata, but suppress log in favor # of logging below (after setting self.selection) GetEpochsMixin.metadata.fset(self, metadata, verbose=False) del events values = list(self.event_id.values()) selected = np.where(np.in1d(self.events[:, 2], values))[0] if selection is None: selection = selected else: selection = np.array(selection, int) if selection.shape != (len(selected),): raise ValueError('selection must be shape %s got shape %s' % (selected.shape, selection.shape)) self.selection = selection if drop_log is None: self.drop_log = tuple( () if k in self.selection else ('IGNORED',) for k in range(max(len(self.events), max(self.selection) + 1))) else: self.drop_log = drop_log self.events = self.events[selected] self.events, self.event_id, self.selection, self.drop_log = \ _handle_event_repeated( self.events, self.event_id, event_repeated, self.selection, self.drop_log) # then subselect sub = np.where(np.in1d(selection, self.selection))[0] if isinstance(metadata, list): metadata = [metadata[s] for s in sub] elif metadata is not None: metadata = metadata.iloc[sub] # Remove temporarily set metadata from above, and set # again to get the correct log ("adding metadata", instead of # "replacing existing metadata") GetEpochsMixin.metadata.fset(self, None, verbose=False) self.metadata = metadata del metadata n_events = len(self.events) if n_events > 1: if np.diff(self.events.astype(np.int64)[:, 0]).min() <= 0: warn('The events passed to the Epochs constructor are not ' 'chronologically ordered.', RuntimeWarning) if n_events > 0: logger.info('%d matching events found' % n_events) else: raise ValueError('No desired events found.') else: self.drop_log = tuple() self.selection = np.array([], int) self.metadata = metadata # do not set self.events here, let subclass do it if (detrend not in [None, 0, 1]) or isinstance(detrend, bool): raise ValueError('detrend must be None, 0, or 1') self.detrend = detrend self._raw = raw info._check_consistency() self.picks = _picks_to_idx(info, picks, none='all', exclude=(), allow_empty=False) self.info = pick_info(info, self.picks) del info self._current = 0 if data is None: self.preload = False self._data = None self._do_baseline = True else: assert decim == 1 if data.ndim != 3 or data.shape[2] != \ round((tmax - tmin) * self.info['sfreq']) + 1: raise RuntimeError('bad data shape') if data.shape[0] != len(self.events): raise ValueError( 'The number of epochs and the number of events must match') self.preload = True self._data = data self._do_baseline = False self._offset = None if tmin > tmax: raise ValueError('tmin has to be less than or equal to tmax') # Handle times sfreq = float(self.info['sfreq']) start_idx = int(round(tmin * sfreq)) self._raw_times = np.arange(start_idx, int(round(tmax * sfreq)) + 1) / sfreq self._set_times(self._raw_times) # check reject_tmin and reject_tmax if reject_tmin is not None: if (np.isclose(reject_tmin, tmin)): # adjust for potential small deviations due to sampling freq reject_tmin = self.tmin elif reject_tmin < tmin: raise ValueError(f'reject_tmin needs to be None or >= tmin ' f'(got {reject_tmin})') if reject_tmax is not None: if (np.isclose(reject_tmax, tmax)): # adjust for potential small deviations due to sampling freq reject_tmax = self.tmax elif reject_tmax > tmax: raise ValueError(f'reject_tmax needs to be None or <= tmax ' f'(got {reject_tmax})') if (reject_tmin is not None) and (reject_tmax is not None): if reject_tmin >= reject_tmax: raise ValueError(f'reject_tmin ({reject_tmin}) needs to be ' f' < reject_tmax ({reject_tmax})') self.reject_tmin = reject_tmin self.reject_tmax = reject_tmax # decimation self._decim = 1 self.decimate(decim) # baseline correction: replace `None` tuple elements with actual times self.baseline = _check_baseline(baseline, times=self.times, sfreq=self.info['sfreq']) if self.baseline is not None and self.baseline != baseline: logger.info(f'Setting baseline interval to ' f'[{self.baseline[0]}, {self.baseline[1]}] sec') logger.info(_log_rescale(self.baseline)) # setup epoch rejection self.reject = None self.flat = None self._reject_setup(reject, flat) # do the rest valid_proj = [True, 'delayed', False] if proj not in valid_proj: raise ValueError('"proj" must be one of %s, not %s' % (valid_proj, proj)) if proj == 'delayed': self._do_delayed_proj = True logger.info('Entering delayed SSP mode.') else: self._do_delayed_proj = False activate = False if self._do_delayed_proj else proj self._projector, self.info = setup_proj(self.info, False, activate=activate) if preload_at_end: assert self._data is None assert self.preload is False self.load_data() # this will do the projection elif proj is True and self._projector is not None and data is not None: # let's make sure we project if data was provided and proj # requested # we could do this with np.einsum, but iteration should be # more memory safe in most instances for ii, epoch in enumerate(self._data): self._data[ii] = np.dot(self._projector, epoch) self._filename = str(filename) if filename is not None else filename if raw_sfreq is None: raw_sfreq = self.info['sfreq'] self._raw_sfreq = raw_sfreq self._check_consistency() self.set_annotations(annotations) def _check_consistency(self): """Check invariants of epochs object.""" if hasattr(self, 'events'): assert len(self.selection) == len(self.events) assert len(self.drop_log) >= len(self.events) assert len(self.selection) == sum( (len(dl) == 0 for dl in self.drop_log)) assert hasattr(self, '_times_readonly') assert not self.times.flags['WRITEABLE'] assert isinstance(self.drop_log, tuple) assert all(isinstance(log, tuple) for log in self.drop_log) assert all(isinstance(s, str) for log in self.drop_log for s in log) def reset_drop_log_selection(self): """Reset the drop_log and selection entries. This method will simplify ``self.drop_log`` and ``self.selection`` so that they are meaningless (tuple of empty tuples and increasing integers, respectively). This can be useful when concatenating many Epochs instances, as ``drop_log`` can accumulate many entries which can become problematic when saving. """ self.selection = np.arange(len(self.events)) self.drop_log = (tuple(),) * len(self.events) self._check_consistency() def load_data(self): """Load the data if not already preloaded. Returns ------- epochs : instance of Epochs The epochs object. Notes ----- This function operates in-place. .. versionadded:: 0.10.0 """ if self.preload: return self self._data = self._get_data() self.preload = True self._do_baseline = False self._decim_slice = slice(None, None, None) self._decim = 1 self._raw_times = self.times assert self._data.shape[-1] == len(self.times) self._raw = None # shouldn't need it anymore return self @verbose def decimate(self, decim, offset=0, verbose=None): """Decimate the epochs. Parameters ---------- %(decim)s %(decim_offset)s %(verbose)s Returns ------- epochs : instance of Epochs The decimated Epochs object. See Also -------- mne.Evoked.decimate mne.Epochs.resample mne.io.Raw.resample Notes ----- %(decim_notes)s If ``decim`` is 1, this method does not copy the underlying data. .. versionadded:: 0.10.0 References ---------- .. footbibliography:: """ decim, offset, new_sfreq = _check_decim(self.info, decim, offset) start_idx = int(round(-self._raw_times[0] * (self.info['sfreq'] * self._decim))) self._decim *= decim i_start = start_idx % self._decim + offset decim_slice = slice(i_start, None, self._decim) with self.info._unlock(): self.info['sfreq'] = new_sfreq if self.preload: if decim != 1: self._data = self._data[:, :, decim_slice].copy() self._raw_times = self._raw_times[decim_slice].copy() else: self._data = np.ascontiguousarray(self._data) self._decim_slice = slice(None) self._decim = 1 else: self._decim_slice = decim_slice self._set_times(self._raw_times[self._decim_slice]) return self @verbose def apply_baseline(self, baseline=(None, 0), *, verbose=None): """Baseline correct epochs. Parameters ---------- %(baseline_epochs)s Defaults to ``(None, 0)``, i.e. beginning of the the data until time point zero. %(verbose)s Returns ------- epochs : instance of Epochs The baseline-corrected Epochs object. Notes ----- Baseline correction can be done multiple times, but can never be reverted once the data has been loaded. .. versionadded:: 0.10.0 """ baseline = _check_baseline(baseline, times=self.times, sfreq=self.info['sfreq']) if self.preload: if self.baseline is not None and baseline is None: raise RuntimeError('You cannot remove baseline correction ' 'from preloaded data once it has been ' 'applied.') self._do_baseline = True picks = self._detrend_picks rescale(self._data, self.times, baseline, copy=False, picks=picks) self._do_baseline = False else: # logging happens in "rescale" in "if" branch logger.info(_log_rescale(baseline)) # For EpochsArray and Epochs, this is already True: # assert self._do_baseline is True # ... but for EpochsFIF it's not, so let's set it explicitly self._do_baseline = True self.baseline = baseline return self def _reject_setup(self, reject, flat): """Set self._reject_time and self._channel_type_idx.""" idx = channel_indices_by_type(self.info) reject = deepcopy(reject) if reject is not None else dict() flat = deepcopy(flat) if flat is not None else dict() for rej, kind in zip((reject, flat), ('reject', 'flat')): if not isinstance(rej, dict): raise TypeError('reject and flat must be dict or None, not %s' % type(rej)) bads = set(rej.keys()) - set(idx.keys()) if len(bads) > 0: raise KeyError('Unknown channel types found in %s: %s' % (kind, bads)) for key in idx.keys(): # don't throw an error if rejection/flat would do nothing if len(idx[key]) == 0 and (np.isfinite(reject.get(key, np.inf)) or flat.get(key, -1) >= 0): # This is where we could eventually add e.g. # self.allow_missing_reject_keys check to allow users to # provide keys that don't exist in data raise ValueError("No %s channel found. Cannot reject based on " "%s." % (key.upper(), key.upper())) # check for invalid values for rej, kind in zip((reject, flat), ('Rejection', 'Flat')): for key, val in rej.items(): if val is None or val < 0: raise ValueError('%s value must be a number >= 0, not "%s"' % (kind, val)) # now check to see if our rejection and flat are getting more # restrictive old_reject = self.reject if self.reject is not None else dict() old_flat = self.flat if self.flat is not None else dict() bad_msg = ('{kind}["{key}"] == {new} {op} {old} (old value), new ' '{kind} values must be at least as stringent as ' 'previous ones') # copy thresholds for channel types that were used previously, but not # passed this time for key in set(old_reject) - set(reject): reject[key] = old_reject[key] # make sure new thresholds are at least as stringent as the old ones for key in reject: if key in old_reject and reject[key] > old_reject[key]: raise ValueError( bad_msg.format(kind='reject', key=key, new=reject[key], old=old_reject[key], op='>')) # same for flat thresholds for key in set(old_flat) - set(flat): flat[key] = old_flat[key] for key in flat: if key in old_flat and flat[key] < old_flat[key]: raise ValueError( bad_msg.format(kind='flat', key=key, new=flat[key], old=old_flat[key], op='<')) # after validation, set parameters self._bad_dropped = False self._channel_type_idx = idx self.reject = reject if len(reject) > 0 else None self.flat = flat if len(flat) > 0 else None if (self.reject_tmin is None) and (self.reject_tmax is None): self._reject_time = None else: if self.reject_tmin is None: reject_imin = None else: idxs = np.nonzero(self.times >= self.reject_tmin)[0] reject_imin = idxs[0] if self.reject_tmax is None: reject_imax = None else: idxs = np.nonzero(self.times <= self.reject_tmax)[0] reject_imax = idxs[-1] self._reject_time = slice(reject_imin, reject_imax) @verbose # verbose is used by mne-realtime def _is_good_epoch(self, data, verbose=None): """Determine if epoch is good.""" if isinstance(data, str): return False, (data,) if data is None: return False, ('NO_DATA',) n_times = len(self.times) if data.shape[1] < n_times: # epoch is too short ie at the end of the data return False, ('TOO_SHORT',) if self.reject is None and self.flat is None: return True, None else: if self._reject_time is not None: data = data[:, self._reject_time] return _is_good(data, self.ch_names, self._channel_type_idx, self.reject, self.flat, full_report=True, ignore_chs=self.info['bads']) @verbose def _detrend_offset_decim(self, epoch, picks, verbose=None): """Aux Function: detrend, baseline correct, offset, decim. Note: operates inplace """ if (epoch is None) or isinstance(epoch, str): return epoch # Detrend if self.detrend is not None: # We explicitly detrend just data channels (not EMG, ECG, EOG which # are processed by baseline correction) use_picks = _pick_data_channels(self.info, exclude=()) epoch[use_picks] = detrend(epoch[use_picks], self.detrend, axis=1) # Baseline correct if self._do_baseline: rescale( epoch, self._raw_times, self.baseline, picks=picks, copy=False, verbose=False) # Decimate if necessary (i.e., epoch not preloaded) epoch = epoch[:, self._decim_slice] # handle offset if self._offset is not None: epoch += self._offset return epoch def iter_evoked(self, copy=False): """Iterate over epochs as a sequence of Evoked objects. The Evoked objects yielded will each contain a single epoch (i.e., no averaging is performed). This method resets the object iteration state to the first epoch. Parameters ---------- copy : bool If False copies of data and measurement info will be omitted to save time. """ self.__iter__() while True: try: out = self.__next__(True) except StopIteration: break data, event_id = out tmin = self.times[0] info = self.info if copy: info = deepcopy(self.info) data = data.copy() yield EvokedArray(data, info, tmin, comment=str(event_id)) def subtract_evoked(self, evoked=None): """Subtract an evoked response from each epoch. Can be used to exclude the evoked response when analyzing induced activity, see e.g. [1]_. Parameters ---------- evoked : instance of Evoked | None The evoked response to subtract. If None, the evoked response is computed from Epochs itself. Returns ------- self : instance of Epochs The modified instance (instance is also modified inplace). References ---------- .. [1] David et al. "Mechanisms of evoked and induced responses in MEG/EEG", NeuroImage, vol. 31, no. 4, pp. 1580-1591, July 2006. """ logger.info('Subtracting Evoked from Epochs') if evoked is None: picks = _pick_data_channels(self.info, exclude=[]) evoked = self.average(picks) # find the indices of the channels to use picks = pick_channels(evoked.ch_names, include=self.ch_names) # make sure the omitted channels are not data channels if len(picks) < len(self.ch_names): sel_ch = [evoked.ch_names[ii] for ii in picks] diff_ch = list(set(self.ch_names).difference(sel_ch)) diff_idx = [self.ch_names.index(ch) for ch in diff_ch] diff_types = [channel_type(self.info, idx) for idx in diff_idx] bad_idx = [diff_types.index(t) for t in diff_types if t in _DATA_CH_TYPES_SPLIT] if len(bad_idx) > 0: bad_str = ', '.join([diff_ch[ii] for ii in bad_idx]) raise ValueError('The following data channels are missing ' 'in the evoked response: %s' % bad_str) logger.info(' The following channels are not included in the ' 'subtraction: %s' % ', '.join(diff_ch)) # make sure the times match if (len(self.times) != len(evoked.times) or np.max(np.abs(self.times - evoked.times)) >= 1e-7): raise ValueError('Epochs and Evoked object do not contain ' 'the same time points.') # handle SSPs if not self.proj and evoked.proj: warn('Evoked has SSP applied while Epochs has not.') if self.proj and not evoked.proj: evoked = evoked.copy().apply_proj() # find the indices of the channels to use in Epochs ep_picks = [self.ch_names.index(evoked.ch_names[ii]) for ii in picks] # do the subtraction if self.preload: self._data[:, ep_picks, :] -= evoked.data[picks][None, :, :] else: if self._offset is None: self._offset = np.zeros((len(self.ch_names), len(self.times)), dtype=np.float64) self._offset[ep_picks] -= evoked.data[picks] logger.info('[done]') return self @fill_doc def average(self, picks=None, method="mean", by_event_type=False): """Compute an average over epochs. Parameters ---------- %(picks_all_data)s method : str | callable How to combine the data. If "mean"/"median", the mean/median are returned. Otherwise, must be a callable which, when passed an array of shape (n_epochs, n_channels, n_time) returns an array of shape (n_channels, n_time). Note that due to file type limitations, the kind for all these will be "average". %(by_event_type)s Returns ------- %(by_event_type_returns_average)s Notes ----- Computes an average of all epochs in the instance, even if they correspond to different conditions. To average by condition, do ``epochs[condition].average()`` for each condition separately. When picks is None and epochs contain only ICA channels, no channels are selected, resulting in an error. This is because ICA channels are not considered data channels (they are of misc type) and only data channels are selected when picks is None. The ``method`` parameter allows e.g. robust averaging. For example, one could do: >>> from scipy.stats import trim_mean # doctest:+SKIP >>> trim = lambda x: trim_mean(x, 0.1, axis=0) # doctest:+SKIP >>> epochs.average(method=trim) # doctest:+SKIP This would compute the trimmed mean. """ if by_event_type: evokeds = list() for event_type in self.event_id.keys(): ev = self[event_type]._compute_aggregate(picks=picks, mode=method) ev.comment = event_type evokeds.append(ev) else: evokeds = self._compute_aggregate(picks=picks, mode=method) return evokeds @fill_doc def standard_error(self, picks=None, by_event_type=False): """Compute standard error over epochs. Parameters ---------- %(picks_all_data)s %(by_event_type)s Returns ------- %(by_event_type_returns_stderr)s """ return self.average(picks=picks, method="std", by_event_type=by_event_type) def _compute_aggregate(self, picks, mode='mean'): """Compute the mean, median, or std over epochs and return Evoked.""" # if instance contains ICA channels they won't be included unless picks # is specified if picks is None: check_ICA = [x.startswith('ICA') for x in self.ch_names] if np.all(check_ICA): raise TypeError('picks must be specified (i.e. not None) for ' 'ICA channel data') elif np.any(check_ICA): warn('ICA channels will not be included unless explicitly ' 'selected in picks') n_channels = len(self.ch_names) n_times = len(self.times) if self.preload: n_events = len(self.events) fun = _check_combine(mode, valid=('mean', 'median', 'std')) data = fun(self._data) assert len(self.events) == len(self._data) if data.shape != self._data.shape[1:]: raise RuntimeError( 'You passed a function that resulted n data of shape {}, ' 'but it should be {}.'.format( data.shape, self._data.shape[1:])) else: if mode not in {"mean", "std"}: raise ValueError("If data are not preloaded, can only compute " "mean or standard deviation.") data = np.zeros((n_channels, n_times)) n_events = 0 for e in self: if np.iscomplexobj(e): data = data.astype(np.complex128) data += e n_events += 1 if n_events > 0: data /= n_events else: data.fill(np.nan) # convert to stderr if requested, could do in one pass but do in # two (slower) in case there are large numbers if mode == "std": data_mean = data.copy() data.fill(0.) for e in self: data += (e - data_mean) ** 2 data = np.sqrt(data / n_events) if mode == "std": kind = 'standard_error' data /= np.sqrt(n_events) else: kind = "average" return self._evoked_from_epoch_data(data, self.info, picks, n_events, kind, self._name) @property def _name(self): """Give a nice string representation based on event ids.""" if len(self.event_id) == 1: comment = next(iter(self.event_id.keys())) else: count = Counter(self.events[:, 2]) comments = list() for key, value in self.event_id.items(): comments.append('%.2f × %s' % ( float(count[value]) / len(self.events), key)) comment = ' + '.join(comments) return comment def _evoked_from_epoch_data(self, data, info, picks, n_events, kind, comment): """Create an evoked object from epoch data.""" info = deepcopy(info) # don't apply baseline correction; we'll set evoked.baseline manually evoked = EvokedArray(data, info, tmin=self.times[0], comment=comment, nave=n_events, kind=kind, baseline=None) evoked.baseline = self.baseline # the above constructor doesn't recreate the times object precisely # due to numerical precision issues evoked.times = self.times.copy() # pick channels picks = _picks_to_idx(self.info, picks, 'data_or_ica', ()) ch_names = [evoked.ch_names[p] for p in picks] evoked.pick_channels(ch_names) if len(evoked.info['ch_names']) == 0: raise ValueError('No data channel found when averaging.') if evoked.nave < 1: warn('evoked object is empty (based on less than 1 epoch)') return evoked @property def ch_names(self): """Channel names.""" return self.info['ch_names'] @copy_function_doc_to_method_doc(plot_epochs) def plot(self, picks=None, scalings=None, n_epochs=20, n_channels=20, title=None, events=None, event_color=None, order=None, show=True, block=False, decim='auto', noise_cov=None, butterfly=False, show_scrollbars=True, show_scalebars=True, epoch_colors=None, event_id=None, group_by='type'): return plot_epochs(self, picks=picks, scalings=scalings, n_epochs=n_epochs, n_channels=n_channels, title=title, events=events, event_color=event_color, order=order, show=show, block=block, decim=decim, noise_cov=noise_cov, butterfly=butterfly, show_scrollbars=show_scrollbars, show_scalebars=show_scalebars, epoch_colors=epoch_colors, event_id=event_id, group_by=group_by) @copy_function_doc_to_method_doc(plot_epochs_psd) def plot_psd(self, fmin=0, fmax=np.inf, tmin=None, tmax=None, proj=False, bandwidth=None, adaptive=False, low_bias=True, normalization='length', picks=None, ax=None, color='black', xscale='linear', area_mode='std', area_alpha=0.33, dB=True, estimate='auto', show=True, n_jobs=1, average=False, line_alpha=None, spatial_colors=True, sphere=None, exclude='bads', verbose=None): return plot_epochs_psd(self, fmin=fmin, fmax=fmax, tmin=tmin, tmax=tmax, proj=proj, bandwidth=bandwidth, adaptive=adaptive, low_bias=low_bias, normalization=normalization, picks=picks, ax=ax, color=color, xscale=xscale, area_mode=area_mode, area_alpha=area_alpha, dB=dB, estimate=estimate, show=show, n_jobs=n_jobs, average=average, line_alpha=line_alpha, spatial_colors=spatial_colors, sphere=sphere, exclude=exclude, verbose=verbose) @copy_function_doc_to_method_doc(plot_epochs_psd_topomap) def plot_psd_topomap(self, bands=None, tmin=None, tmax=None, proj=False, bandwidth=None, adaptive=False, low_bias=True, normalization='length', ch_type=None, cmap=None, agg_fun=None, dB=True, n_jobs=1, normalize=False, cbar_fmt='auto', outlines='head', axes=None, show=True, sphere=None, vlim=(None, None), verbose=None): return plot_epochs_psd_topomap( self, bands=bands, tmin=tmin, tmax=tmax, proj=proj, bandwidth=bandwidth, adaptive=adaptive, low_bias=low_bias, normalization=normalization, ch_type=ch_type, cmap=cmap, agg_fun=agg_fun, dB=dB, n_jobs=n_jobs, normalize=normalize, cbar_fmt=cbar_fmt, outlines=outlines, axes=axes, show=show, sphere=sphere, vlim=vlim, verbose=verbose) @copy_function_doc_to_method_doc(plot_topo_image_epochs) def plot_topo_image(self, layout=None, sigma=0., vmin=None, vmax=None, colorbar=None, order=None, cmap='RdBu_r', layout_scale=.95, title=None, scalings=None, border='none', fig_facecolor='k', fig_background=None, font_color='w', show=True): return plot_topo_image_epochs( self, layout=layout, sigma=sigma, vmin=vmin, vmax=vmax, colorbar=colorbar, order=order, cmap=cmap, layout_scale=layout_scale, title=title, scalings=scalings, border=border, fig_facecolor=fig_facecolor, fig_background=fig_background, font_color=font_color, show=show) @verbose def drop_bad(self, reject='existing', flat='existing', verbose=None): """Drop bad epochs without retaining the epochs data. Should be used before slicing operations. .. warning:: This operation is slow since all epochs have to be read from disk. To avoid reading epochs from disk multiple times, use :meth:`mne.Epochs.load_data()`. .. note:: To constrain the time period used for estimation of signal quality, set ``epochs.reject_tmin`` and ``epochs.reject_tmax``, respectively. Parameters ---------- %(reject_drop_bad)s %(flat_drop_bad)s %(verbose)s Returns ------- epochs : instance of Epochs The epochs with bad epochs dropped. Operates in-place. Notes ----- Dropping bad epochs can be done multiple times with different ``reject`` and ``flat`` parameters. However, once an epoch is dropped, it is dropped forever, so if more lenient thresholds may subsequently be applied, `epochs.copy <mne.Epochs.copy>` should be used. """ if reject == 'existing': if flat == 'existing' and self._bad_dropped: return reject = self.reject if flat == 'existing': flat = self.flat if any(isinstance(rej, str) and rej != 'existing' for rej in (reject, flat)): raise ValueError('reject and flat, if strings, must be "existing"') self._reject_setup(reject, flat) self._get_data(out=False, verbose=verbose) return self def drop_log_stats(self, ignore=('IGNORED',)): """Compute the channel stats based on a drop_log from Epochs. Parameters ---------- ignore : list The drop reasons to ignore. Returns ------- perc : float Total percentage of epochs dropped. See Also -------- plot_drop_log """ return _drop_log_stats(self.drop_log, ignore) @copy_function_doc_to_method_doc(plot_drop_log) def plot_drop_log(self, threshold=0, n_max_plot=20, subject=None, color=(0.9, 0.9, 0.9), width=0.8, ignore=('IGNORED',), show=True): if not self._bad_dropped: raise ValueError("You cannot use plot_drop_log since bad " "epochs have not yet been dropped. " "Use epochs.drop_bad().") return plot_drop_log(self.drop_log, threshold, n_max_plot, subject, color=color, width=width, ignore=ignore, show=show) @copy_function_doc_to_method_doc(plot_epochs_image) def plot_image(self, picks=None, sigma=0., vmin=None, vmax=None, colorbar=True, order=None, show=True, units=None, scalings=None, cmap=None, fig=None, axes=None, overlay_times=None, combine=None, group_by=None, evoked=True, ts_args=None, title=None, clear=False): return plot_epochs_image(self, picks=picks, sigma=sigma, vmin=vmin, vmax=vmax, colorbar=colorbar, order=order, show=show, units=units, scalings=scalings, cmap=cmap, fig=fig, axes=axes, overlay_times=overlay_times, combine=combine, group_by=group_by, evoked=evoked, ts_args=ts_args, title=title, clear=clear) @verbose def drop(self, indices, reason='USER', verbose=None): """Drop epochs based on indices or boolean mask. .. note:: The indices refer to the current set of undropped epochs rather than the complete set of dropped and undropped epochs. They are therefore not necessarily consistent with any external indices (e.g., behavioral logs). To drop epochs based on external criteria, do not use the ``preload=True`` flag when constructing an Epochs object, and call this method before calling the :meth:`mne.Epochs.drop_bad` or :meth:`mne.Epochs.load_data` methods. Parameters ---------- indices : array of int or bool Set epochs to remove by specifying indices to remove or a boolean mask to apply (where True values get removed). Events are correspondingly modified. reason : str Reason for dropping the epochs ('ECG', 'timeout', 'blink' etc). Default: 'USER'. %(verbose)s Returns ------- epochs : instance of Epochs The epochs with indices dropped. Operates in-place. """ indices = np.atleast_1d(indices) if indices.ndim > 1: raise ValueError("indices must be a scalar or a 1-d array") if indices.dtype == bool: indices = np.where(indices)[0] try_idx = np.where(indices < 0, indices + len(self.events), indices) out_of_bounds = (try_idx < 0) | (try_idx >= len(self.events)) if out_of_bounds.any(): first = indices[out_of_bounds][0] raise IndexError("Epoch index %d is out of bounds" % first) keep = np.setdiff1d(np.arange(len(self.events)), try_idx) self._getitem(keep, reason, copy=False, drop_event_id=False) count = len(try_idx) logger.info('Dropped %d epoch%s: %s' % (count, _pl(count), ', '.join(map(str, np.sort(try_idx))))) return self def _get_epoch_from_raw(self, idx, verbose=None): """Get a given epoch from disk.""" raise NotImplementedError def _project_epoch(self, epoch): """Process a raw epoch based on the delayed param.""" # whenever requested, the first epoch is being projected. if (epoch is None) or isinstance(epoch, str): # can happen if t < 0 or reject based on annotations return epoch proj = self._do_delayed_proj or self.proj if self._projector is not None and proj is True: epoch = np.dot(self._projector, epoch) return epoch @verbose def _get_data(self, out=True, picks=None, item=None, *, units=None, tmin=None, tmax=None, verbose=None): """Load all data, dropping bad epochs along the way. Parameters ---------- out : bool Return the data. Setting this to False is used to reject bad epochs without caching all the data, which saves memory. %(picks_all)s item : slice | array-like | str | list | None See docstring of get_data method. %(units)s tmin : int | float | None Start time of data to get in seconds. tmax : int | float | None End time of data to get in seconds. %(verbose)s """ start, stop = self._handle_tmin_tmax(tmin, tmax) if item is None: item = slice(None) elif not self._bad_dropped: raise ValueError( 'item must be None in epochs.get_data() unless bads have been ' 'dropped. Consider using epochs.drop_bad().') select = self._item_to_select(item) # indices or slice use_idx = np.arange(len(self.events))[select] n_events = len(use_idx) # in case there are no good events if self.preload: # we will store our result in our existing array data = self._data else: # we start out with an empty array, allocate only if necessary data = np.empty((0, len(self.info['ch_names']), len(self.times))) msg = (f'for {n_events} events and {len(self._raw_times)} ' 'original time points') if self._decim > 1: msg += ' (prior to decimation)' if getattr(self._raw, "preload", False): logger.info(f'Using data from preloaded Raw {msg} ...') else: logger.info(f'Loading data {msg} ...') orig_picks = picks if orig_picks is None: picks = _picks_to_idx(self.info, picks, "all", exclude=()) else: picks = _picks_to_idx(self.info, picks) # handle units param only if we are going to return data (out==True) if (units is not None) and out: ch_factors = _get_ch_factors(self, units, picks) if self._bad_dropped: if not out: return if self.preload: data = data[select] if orig_picks is not None: data = data[:, picks] if units is not None: data *= ch_factors[:, np.newaxis] if start != 0 or stop != self.times.size: data = data[..., start:stop] return data # we need to load from disk, drop, and return data detrend_picks = self._detrend_picks for ii, idx in enumerate(use_idx): # faster to pre-allocate memory here epoch_noproj = self._get_epoch_from_raw(idx) epoch_noproj = self._detrend_offset_decim( epoch_noproj, detrend_picks) if self._do_delayed_proj: epoch_out = epoch_noproj else: epoch_out = self._project_epoch(epoch_noproj) if ii == 0: data = np.empty((n_events, len(self.ch_names), len(self.times)), dtype=epoch_out.dtype) data[ii] = epoch_out else: # bads need to be dropped, this might occur after a preload # e.g., when calling drop_bad w/new params good_idx = [] n_out = 0 drop_log = list(self.drop_log) assert n_events == len(self.selection) if not self.preload: detrend_picks = self._detrend_picks for idx, sel in enumerate(self.selection): if self.preload: # from memory if self._do_delayed_proj: epoch_noproj = self._data[idx] epoch = self._project_epoch(epoch_noproj) else: epoch_noproj = None epoch = self._data[idx] else: # from disk epoch_noproj = self._get_epoch_from_raw(idx) epoch_noproj = self._detrend_offset_decim( epoch_noproj, detrend_picks) epoch = self._project_epoch(epoch_noproj) epoch_out = epoch_noproj if self._do_delayed_proj else epoch is_good, bad_tuple = self._is_good_epoch( epoch, verbose=verbose) if not is_good: assert isinstance(bad_tuple, tuple) assert all(isinstance(x, str) for x in bad_tuple) drop_log[sel] = drop_log[sel] + bad_tuple continue good_idx.append(idx) # store the epoch if there is a reason to (output or update) if out or self.preload: # faster to pre-allocate, then trim as necessary if n_out == 0 and not self.preload: data = np.empty((n_events, epoch_out.shape[0], epoch_out.shape[1]), dtype=epoch_out.dtype, order='C') data[n_out] = epoch_out n_out += 1 self.drop_log = tuple(drop_log) del drop_log self._bad_dropped = True logger.info("%d bad epochs dropped" % (n_events - len(good_idx))) # adjust the data size if there is a reason to (output or update) if out or self.preload: if data.flags['OWNDATA'] and data.flags['C_CONTIGUOUS']: data.resize((n_out,) + data.shape[1:], refcheck=False) else: data = data[:n_out] if self.preload: self._data = data # Now update our properties (excepd data, which is already fixed) self._getitem(good_idx, None, copy=False, drop_event_id=False, select_data=False) if out: if orig_picks is not None: data = data[:, picks] if units is not None: data *= ch_factors[:, np.newaxis] if start != 0 or stop != self.times.size: data = data[..., start:stop] return data else: return None @property def _detrend_picks(self): if self._do_baseline: return _pick_data_channels( self.info, with_ref_meg=True, with_aux=True, exclude=()) else: return [] @fill_doc def get_data(self, picks=None, item=None, units=None, tmin=None, tmax=None): """Get all epochs as a 3D array. Parameters ---------- %(picks_all)s item : slice | array-like | str | list | None The items to get. See :meth:`mne.Epochs.__getitem__` for a description of valid options. This can be substantially faster for obtaining an ndarray than :meth:`~mne.Epochs.__getitem__` for repeated access on large Epochs objects. None (default) is an alias for ``slice(None)``. .. versionadded:: 0.20 %(units)s .. versionadded:: 0.24 tmin : int | float | None Start time of data to get in seconds. .. versionadded:: 0.24.0 tmax : int | float | None End time of data to get in seconds. .. versionadded:: 0.24.0 Returns ------- data : array of shape (n_epochs, n_channels, n_times) A view on epochs data. """ return self._get_data(picks=picks, item=item, units=units, tmin=tmin, tmax=tmax) @verbose def apply_function(self, fun, picks=None, dtype=None, n_jobs=1, channel_wise=True, verbose=None, **kwargs): """Apply a function to a subset of channels. %(applyfun_summary_epochs)s Parameters ---------- %(applyfun_fun)s %(picks_all_data_noref)s %(applyfun_dtype)s %(n_jobs)s %(applyfun_chwise_epo)s %(verbose)s %(kwarg_fun)s Returns ------- self : instance of Epochs The epochs object with transformed data. """ _check_preload(self, 'epochs.apply_function') picks = _picks_to_idx(self.info, picks, exclude=(), with_ref_meg=False) if not callable(fun): raise ValueError('fun needs to be a function') data_in = self._data if dtype is not None and dtype != self._data.dtype: self._data = self._data.astype(dtype) if channel_wise: if n_jobs == 1: _fun = partial(_check_fun, fun, **kwargs) # modify data inplace to save memory for idx in picks: self._data[:, idx, :] = np.apply_along_axis( _fun, -1, data_in[:, idx, :]) else: # use parallel function parallel, p_fun, _ = parallel_func(_check_fun, n_jobs) data_picks_new = parallel(p_fun( fun, data_in[:, p, :], **kwargs) for p in picks) for pp, p in enumerate(picks): self._data[:, p, :] = data_picks_new[pp] else: self._data = _check_fun(fun, data_in, **kwargs) return self @property def times(self): """Time vector in seconds.""" return self._times_readonly def _set_times(self, times): """Set self._times_readonly (and make it read only).""" # naming used to indicate that it shouldn't be # changed directly, but rather via this method self._times_readonly = times.copy() self._times_readonly.flags['WRITEABLE'] = False @property def tmin(self): """First time point.""" return self.times[0] @property def filename(self): """The filename.""" return self._filename @property def tmax(self): """Last time point.""" return self.times[-1] def __repr__(self): """Build string representation.""" s = ' %s events ' % len(self.events) s += '(all good)' if self._bad_dropped else '(good & bad)' s += ', %g - %g sec' % (self.tmin, self.tmax) s += ', baseline ' if self.baseline is None: s += 'off' else: s += f'{self.baseline[0]:g} – {self.baseline[1]:g} sec' if self.baseline != _check_baseline( self.baseline, times=self.times, sfreq=self.info['sfreq'], on_baseline_outside_data='adjust'): s += ' (baseline period was cropped after baseline correction)' s += ', ~%s' % (sizeof_fmt(self._size),) s += ', data%s loaded' % ('' if self.preload else ' not') s += ', with metadata' if self.metadata is not None else '' max_events = 10 counts = ['%r: %i' % (k, sum(self.events[:, 2] == v)) for k, v in list(self.event_id.items())[:max_events]] if len(self.event_id) > 0: s += ',' + '\n '.join([''] + counts) if len(self.event_id) > max_events: not_shown_events = len(self.event_id) - max_events s += f"\n and {not_shown_events} more events ..." class_name = self.__class__.__name__ class_name = 'Epochs' if class_name == 'BaseEpochs' else class_name return '<%s | %s>' % (class_name, s) def _repr_html_(self): from .html_templates import repr_templates_env if self.baseline is None: baseline = 'off' else: baseline = tuple([f'{b:.3f}' for b in self.baseline]) baseline = f'{baseline[0]} – {baseline[1]} sec' if isinstance(self.event_id, dict): event_strings = [] for k, v in sorted(self.event_id.items()): n_events = sum(self.events[:, 2] == v) event_strings.append(f'{k}: {n_events}') elif isinstance(self.event_id, list): event_strings = [] for k in self.event_id: n_events = sum(self.events[:, 2] == k) event_strings.append(f'{k}: {n_events}') elif isinstance(self.event_id, int): n_events = len(self.events[:, 2]) event_strings = [f'{self.event_id}: {n_events}'] else: event_strings = None t = repr_templates_env.get_template('epochs.html.jinja') t = t.render(epochs=self, baseline=baseline, events=event_strings) return t @verbose def crop(self, tmin=None, tmax=None, include_tmax=True, verbose=None): """Crop a time interval from the epochs. Parameters ---------- tmin : float | None Start time of selection in seconds. tmax : float | None End time of selection in seconds. %(include_tmax)s %(verbose)s Returns ------- epochs : instance of Epochs The cropped epochs object, modified in-place. Notes ----- %(notes_tmax_included_by_default)s """ # XXX this could be made to work on non-preloaded data... _check_preload(self, 'Modifying data of epochs') if tmin is None: tmin = self.tmin elif tmin < self.tmin: warn('tmin is not in epochs time interval. tmin is set to ' 'epochs.tmin') tmin = self.tmin if tmax is None: tmax = self.tmax elif tmax > self.tmax: warn('tmax is not in epochs time interval. tmax is set to ' 'epochs.tmax') tmax = self.tmax include_tmax = True tmask = _time_mask(self.times, tmin, tmax, sfreq=self.info['sfreq'], include_tmax=include_tmax) self._set_times(self.times[tmask]) self._raw_times = self._raw_times[tmask] self._data = self._data[:, :, tmask] # Adjust rejection period if self.reject_tmin is not None and self.reject_tmin < self.tmin: logger.info( f'reject_tmin is not in epochs time interval. ' f'Setting reject_tmin to epochs.tmin ({self.tmin} sec)') self.reject_tmin = self.tmin if self.reject_tmax is not None and self.reject_tmax > self.tmax: logger.info( f'reject_tmax is not in epochs time interval. ' f'Setting reject_tmax to epochs.tmax ({self.tmax} sec)') self.reject_tmax = self.tmax return self def copy(self): """Return copy of Epochs instance. Returns ------- epochs : instance of Epochs A copy of the object. """ return deepcopy(self) def __deepcopy__(self, memodict): """Make a deepcopy.""" cls = self.__class__ result = cls.__new__(cls) for k, v in self.__dict__.items(): # drop_log is immutable and _raw is private (and problematic to # deepcopy) if k in ('drop_log', '_raw', '_times_readonly'): memodict[id(v)] = v else: v = deepcopy(v, memodict) result.__dict__[k] = v return result @verbose def save(self, fname, split_size='2GB', fmt='single', overwrite=False, split_naming='neuromag', verbose=True): """Save epochs in a fif file. Parameters ---------- fname : str The name of the file, which should end with ``-epo.fif`` or ``-epo.fif.gz``. split_size : str | int Large raw files are automatically split into multiple pieces. This parameter specifies the maximum size of each piece. If the parameter is an integer, it specifies the size in Bytes. It is also possible to pass a human-readable string, e.g., 100MB. Note: Due to FIFF file limitations, the maximum split size is 2GB. .. versionadded:: 0.10.0 fmt : str Format to save data. Valid options are 'double' or 'single' for 64- or 32-bit float, or for 128- or 64-bit complex numbers respectively. Note: Data are processed with double precision. Choosing single-precision, the saved data will slightly differ due to the reduction in precision. .. versionadded:: 0.17 %(overwrite)s To overwrite original file (the same one that was loaded), data must be preloaded upon reading. This defaults to True in 0.18 but will change to False in 0.19. .. versionadded:: 0.18 %(split_naming)s .. versionadded:: 0.24 %(verbose)s Notes ----- Bad epochs will be dropped before saving the epochs to disk. """ check_fname(fname, 'epochs', ('-epo.fif', '-epo.fif.gz', '_epo.fif', '_epo.fif.gz')) # check for file existence and expand `~` if present fname = _check_fname(fname=fname, overwrite=overwrite) split_size_bytes = _get_split_size(split_size) _check_option('fmt', fmt, ['single', 'double']) # to know the length accurately. The get_data() call would drop # bad epochs anyway self.drop_bad() # total_size tracks sizes that get split # over_size tracks overhead (tags, things that get written to each) if len(self) == 0: warn('Saving epochs with no data') total_size = 0 else: d = self[0].get_data() # this should be guaranteed by subclasses assert d.dtype in ('>f8', '<f8', '>c16', '<c16') total_size = d.nbytes * len(self) self._check_consistency() over_size = 0 if fmt == "single": total_size //= 2 # 64bit data converted to 32bit before writing. over_size += 32 # FIF tags # Account for all the other things we write, too # 1. meas_id block plus main epochs block over_size += 132 # 2. measurement info (likely slight overestimate, but okay) over_size += object_size(self.info) + 16 * len(self.info) # 3. events and event_id in its own block total_size += self.events.size * 4 over_size += len(_event_id_string(self.event_id)) + 72 # 4. Metadata in a block of its own if self.metadata is not None: total_size += len(_prepare_write_metadata(self.metadata)) over_size += 56 # 5. first sample, last sample, baseline over_size += 40 * (self.baseline is not None) + 40 # 6. drop log: gets written to each, with IGNORE for ones that are # not part of it. So make a fake one with all having entries. drop_size = len(json.dumps(self.drop_log)) + 16 drop_size += 8 * (len(self.selection) - 1) # worst case: all but one over_size += drop_size # 7. reject params reject_params = _pack_reject_params(self) if reject_params: over_size += len(json.dumps(reject_params)) + 16 # 8. selection total_size += self.selection.size * 4 over_size += 16 # 9. end of file tags over_size += _NEXT_FILE_BUFFER logger.debug(f' Overhead size: {str(over_size).rjust(15)}') logger.debug(f' Splittable size: {str(total_size).rjust(15)}') logger.debug(f' Split size: {str(split_size_bytes).rjust(15)}') # need at least one per n_epochs = len(self) n_per = total_size // n_epochs if n_epochs else 0 min_size = n_per + over_size if split_size_bytes < min_size: raise ValueError( f'The split size {split_size} is too small to safely write ' 'the epochs contents, minimum split size is ' f'{sizeof_fmt(min_size)} ({min_size} bytes)') # This is like max(int(ceil(total_size / split_size)), 1) but cleaner n_parts = max( (total_size - 1) // (split_size_bytes - over_size) + 1, 1) assert n_parts >= 1, n_parts if n_parts > 1: logger.info(f'Splitting into {n_parts} parts') if n_parts > 100: # This must be an error raise ValueError( f'Split size {split_size} would result in writing ' f'{n_parts} files') if len(self.drop_log) > 100000: warn(f'epochs.drop_log contains {len(self.drop_log)} entries ' f'which will incur up to a {sizeof_fmt(drop_size)} writing ' f'overhead (per split file), consider using ' f'epochs.reset_drop_log_selection() prior to writing') epoch_idxs = np.array_split(np.arange(n_epochs), n_parts) for part_idx, epoch_idx in enumerate(epoch_idxs): this_epochs = self[epoch_idx] if n_parts > 1 else self # avoid missing event_ids in splits this_epochs.event_id = self.event_id _save_split(this_epochs, fname, part_idx, n_parts, fmt, split_naming, overwrite) @verbose def export(self, fname, fmt='auto', *, overwrite=False, verbose=None): """Export Epochs to external formats. Supported formats: EEGLAB (set, uses :mod:`eeglabio`) %(export_warning)s Parameters ---------- %(export_params_fname)s %(export_params_fmt)s %(overwrite)s .. versionadded:: 0.24.1 %(verbose)s Notes ----- .. versionadded:: 0.24 %(export_warning_note_epochs)s %(export_eeglab_note)s """ from .export import export_epochs export_epochs(fname, self, fmt, overwrite=overwrite, verbose=verbose) def equalize_event_counts(self, event_ids=None, method='mintime'): """Equalize the number of trials in each condition. It tries to make the remaining epochs occurring as close as possible in time. This method works based on the idea that if there happened to be some time-varying (like on the scale of minutes) noise characteristics during a recording, they could be compensated for (to some extent) in the equalization process. This method thus seeks to reduce any of those effects by minimizing the differences in the times of the events within a `~mne.Epochs` instance. For example, if one event type occurred at time points ``[1, 2, 3, 4, 120, 121]`` and the another one at ``[3.5, 4.5, 120.5, 121.5]``, this method would remove the events at times ``[1, 2]`` for the first event type – and not the events at times ``[120, 121]``. Parameters ---------- event_ids : None | list | dict The event types to equalize. If ``None`` (default), equalize the counts of **all** event types present in the `~mne.Epochs` instance. If a list, each element can either be a string (event name) or a list of strings. In the case where one of the entries is a list of strings, event types in that list will be grouped together before equalizing trial counts across conditions. If a dictionary, the keys are considered as the event names whose counts to equalize, i.e., passing ``dict(A=1, B=2)`` will have the same effect as passing ``['A', 'B']``. This is useful if you intend to pass an ``event_id`` dictionary that was used when creating `~mne.Epochs`. In the case where partial matching is used (using ``/`` in the event names), the event types will be matched according to the provided tags, that is, processing works as if the ``event_ids`` matched by the provided tags had been supplied instead. The ``event_ids`` must identify non-overlapping subsets of the epochs. method : str If ``'truncate'``, events will be truncated from the end of each type of events. If ``'mintime'``, timing differences between each event type will be minimized. Returns ------- epochs : instance of Epochs The modified instance. It is modified in-place. indices : array of int Indices from the original events list that were dropped. Notes ----- For example (if ``epochs.event_id`` was ``{'Left': 1, 'Right': 2, 'Nonspatial':3}``: epochs.equalize_event_counts([['Left', 'Right'], 'Nonspatial']) would equalize the number of trials in the ``'Nonspatial'`` condition with the total number of trials in the ``'Left'`` and ``'Right'`` conditions combined. If multiple indices are provided (e.g. ``'Left'`` and ``'Right'`` in the example above), it is not guaranteed that after equalization the conditions will contribute equally. E.g., it is possible to end up with 70 ``'Nonspatial'`` epochs, 69 ``'Left'`` and 1 ``'Right'``. .. versionchanged:: 0.23 Default to equalizing all events in the passed instance if no event names were specified explicitly. """ from collections.abc import Iterable _validate_type(event_ids, types=(Iterable, None), item_name='event_ids', type_name='list-like or None') if isinstance(event_ids, str): raise TypeError(f'event_ids must be list-like or None, but ' f'received a string: {event_ids}') if event_ids is None: event_ids = list(self.event_id) elif not event_ids: raise ValueError('event_ids must have at least one element') if not self._bad_dropped: self.drop_bad() # figure out how to equalize eq_inds = list() # deal with hierarchical tags ids = self.event_id orig_ids = list(event_ids) tagging = False if "/" in "".join(ids): # make string inputs a list of length 1 event_ids = [[x] if isinstance(x, str) else x for x in event_ids] for ids_ in event_ids: # check if tagging is attempted if any([id_ not in ids for id_ in ids_]): tagging = True # 1. treat everything that's not in event_id as a tag # 2a. for tags, find all the event_ids matched by the tags # 2b. for non-tag ids, just pass them directly # 3. do this for every input event_ids = [[k for k in ids if all((tag in k.split("/") for tag in id_))] # ids matching all tags if all(id__ not in ids for id__ in id_) else id_ # straight pass for non-tag inputs for id_ in event_ids] for ii, id_ in enumerate(event_ids): if len(id_) == 0: raise KeyError(f"{orig_ids[ii]} not found in the epoch " "object's event_id.") elif len({sub_id in ids for sub_id in id_}) != 1: err = ("Don't mix hierarchical and regular event_ids" " like in \'%s\'." % ", ".join(id_)) raise ValueError(err) # raise for non-orthogonal tags if tagging is True: events_ = [set(self[x].events[:, 0]) for x in event_ids] doubles = events_[0].intersection(events_[1]) if len(doubles): raise ValueError("The two sets of epochs are " "overlapping. Provide an " "orthogonal selection.") for eq in event_ids: eq_inds.append(self._keys_to_idx(eq)) event_times = [self.events[e, 0] for e in eq_inds] indices = _get_drop_indices(event_times, method) # need to re-index indices indices = np.concatenate([e[idx] for e, idx in zip(eq_inds, indices)]) self.drop(indices, reason='EQUALIZED_COUNT') # actually remove the indices return self, indices @verbose def to_data_frame(self, picks=None, index=None, scalings=None, copy=True, long_format=False, time_format='ms', *, verbose=None): """Export data in tabular structure as a pandas DataFrame. Channels are converted to columns in the DataFrame. By default, additional columns "time", "epoch" (epoch number), and "condition" (epoch event description) are added, unless ``index`` is not ``None`` (in which case the columns specified in ``index`` will be used to form the DataFrame's index instead). Parameters ---------- %(picks_all)s %(df_index_epo)s Valid string values are 'time', 'epoch', and 'condition'. Defaults to ``None``. %(df_scalings)s %(df_copy)s %(df_longform_epo)s %(df_time_format)s .. versionadded:: 0.20 %(verbose)s Returns ------- %(df_return)s """ # check pandas once here, instead of in each private utils function pd = _check_pandas_installed() # noqa # arg checking valid_index_args = ['time', 'epoch', 'condition'] valid_time_formats = ['ms', 'timedelta'] index = _check_pandas_index_arguments(index, valid_index_args) time_format = _check_time_format(time_format, valid_time_formats) # get data picks = _picks_to_idx(self.info, picks, 'all', exclude=()) data = self.get_data()[:, picks, :] times = self.times n_epochs, n_picks, n_times = data.shape data = np.hstack(data).T # (time*epochs) x signals if copy: data = data.copy() data = _scale_dataframe_data(self, data, picks, scalings) # prepare extra columns / multiindex mindex = list() times = np.tile(times, n_epochs) times = _convert_times(self, times, time_format) mindex.append(('time', times)) rev_event_id = {v: k for k, v in self.event_id.items()} conditions = [rev_event_id[k] for k in self.events[:, 2]] mindex.append(('condition', np.repeat(conditions, n_times))) mindex.append(('epoch', np.repeat(self.selection, n_times))) assert all(len(mdx) == len(mindex[0]) for mdx in mindex) # build DataFrame df = _build_data_frame(self, data, picks, long_format, mindex, index, default_index=['condition', 'epoch', 'time']) return df def as_type(self, ch_type='grad', mode='fast'): """Compute virtual epochs using interpolated fields. .. Warning:: Using virtual epochs to compute inverse can yield unexpected results. The virtual channels have ``'_v'`` appended at the end of the names to emphasize that the data contained in them are interpolated. Parameters ---------- ch_type : str The destination channel type. It can be 'mag' or 'grad'. mode : str Either ``'accurate'`` or ``'fast'``, determines the quality of the Legendre polynomial expansion used. ``'fast'`` should be sufficient for most applications. Returns ------- epochs : instance of mne.EpochsArray The transformed epochs object containing only virtual channels. Notes ----- This method returns a copy and does not modify the data it operates on. It also returns an EpochsArray instance. .. versionadded:: 0.20.0 """ from .forward import _as_meg_type_inst return _as_meg_type_inst(self, ch_type=ch_type, mode=mode) def _drop_log_stats(drop_log, ignore=('IGNORED',)): """Compute drop log stats. Parameters ---------- drop_log : list of list Epoch drop log from Epochs.drop_log. ignore : list The drop reasons to ignore. Returns ------- perc : float Total percentage of epochs dropped. """ if not isinstance(drop_log, tuple) or \ not all(isinstance(d, tuple) for d in drop_log) or \ not all(isinstance(s, str) for d in drop_log for s in d): raise TypeError('drop_log must be a tuple of tuple of str') perc = 100 * np.mean([len(d) > 0 for d in drop_log if not any(r in ignore for r in d)]) return perc def make_metadata(events, event_id, tmin, tmax, sfreq, row_events=None, keep_first=None, keep_last=None): """Generate metadata from events for use with `mne.Epochs`. This function mimics the epoching process (it constructs time windows around time-locked "events of interest") and collates information about any other events that occurred within those time windows. The information is returned as a :class:`pandas.DataFrame` suitable for use as `~mne.Epochs` metadata: one row per time-locked event, and columns indicating presence/absence and latency of each ancillary event type. The function will also return a new ``events`` array and ``event_id`` dictionary that correspond to the generated metadata. Parameters ---------- events : array, shape (m, 3) The :term:`events array <events>`. By default, the returned metadata :class:`~pandas.DataFrame` will have as many rows as the events array. To create rows for only a subset of events, pass the ``row_events`` parameter. event_id : dict A mapping from event names (keys) to event IDs (values). The event names will be incorporated as columns of the returned metadata :class:`~pandas.DataFrame`. tmin, tmax : float Start and end of the time interval for metadata generation in seconds, relative to the time-locked event of the respective time window. .. note:: If you are planning to attach the generated metadata to `~mne.Epochs` and intend to include only events that fall inside your epochs time interval, pass the same ``tmin`` and ``tmax`` values here as you use for your epochs. sfreq : float The sampling frequency of the data from which the events array was extracted. row_events : list of str | str | None Event types around which to create the time windows / for which to create **rows** in the returned metadata :class:`pandas.DataFrame`. If provided, the string(s) must be keys of ``event_id``. If ``None`` (default), rows are created for **all** event types present in ``event_id``. keep_first : str | list of str | None Specify subsets of :term:`hierarchical event descriptors` (HEDs, inspired by :footcite:`BigdelyShamloEtAl2013`) matching events of which the **first occurrence** within each time window shall be stored in addition to the original events. .. note:: There is currently no way to retain **all** occurrences of a repeated event. The ``keep_first`` parameter can be used to specify subsets of HEDs, effectively creating a new event type that is the union of all events types described by the matching HED pattern. Only the very first event of this set will be kept. For example, you might have two response events types, ``response/left`` and ``response/right``; and in trials with both responses occurring, you want to keep only the first response. In this case, you can pass ``keep_first='response'``. This will add two new columns to the metadata: ``response``, indicating at what **time** the event occurred, relative to the time-locked event; and ``first_response``, stating which **type** (``'left'`` or ``'right'``) of event occurred. To match specific subsets of HEDs describing different sets of events, pass a list of these subsets, e.g. ``keep_first=['response', 'stimulus']``. If ``None`` (default), no event aggregation will take place and no new columns will be created. .. note:: By default, this function will always retain the first instance of any event in each time window. For example, if a time window contains two ``'response'`` events, the generated ``response`` column will automatically refer to the first of the two events. In this specific case, it is therefore **not** necessary to make use of the ``keep_first`` parameter – unless you need to differentiate between two types of responses, like in the example above. keep_last : list of str | None Same as ``keep_first``, but for keeping only the **last** occurrence of matching events. The column indicating the **type** of an event ``myevent`` will be named ``last_myevent``. Returns ------- metadata : pandas.DataFrame Metadata for each row event, with the following columns: - ``event_name``, with strings indicating the name of the time-locked event ("row event") for that specific time window - one column per event type in ``event_id``, with the same name; floats indicating the latency of the event in seconds, relative to the time-locked event - if applicable, additional columns named after the ``keep_first`` and ``keep_last`` event types; floats indicating the latency of the event in seconds, relative to the time-locked event - if applicable, additional columns ``first_{event_type}`` and ``last_{event_type}`` for ``keep_first`` and ``keep_last`` event types, respetively; the values will be strings indicating which event types were matched by the provided HED patterns events : array, shape (n, 3) The events corresponding to the generated metadata, i.e. one time-locked event per row. event_id : dict The event dictionary corresponding to the new events array. This will be identical to the input dictionary unless ``row_events`` is supplied, in which case it will only contain the events provided there. Notes ----- The time window used for metadata generation need not correspond to the time window used to create the `~mne.Epochs`, to which the metadata will be attached; it may well be much shorter or longer, or not overlap at all, if desired. The can be useful, for example, to include events that occurred before or after an epoch, e.g. during the inter-trial interval. .. versionadded:: 0.23 References ---------- .. footbibliography:: """ pd = _check_pandas_installed() _validate_type(event_id, types=(dict,), item_name='event_id') _validate_type(row_events, types=(None, str, list, tuple), item_name='row_events') _validate_type(keep_first, types=(None, str, list, tuple), item_name='keep_first') _validate_type(keep_last, types=(None, str, list, tuple), item_name='keep_last') if not event_id: raise ValueError('event_id dictionary must contain at least one entry') def _ensure_list(x): if x is None: return [] elif isinstance(x, str): return [x] else: return list(x) row_events = _ensure_list(row_events) keep_first = _ensure_list(keep_first) keep_last = _ensure_list(keep_last) keep_first_and_last = set(keep_first) & set(keep_last) if keep_first_and_last: raise ValueError(f'The event names in keep_first and keep_last must ' f'be mutually exclusive. Specified in both: ' f'{', '.join(sorted(keep_first_and_last))}') del keep_first_and_last for param_name, values in dict(keep_first=keep_first, keep_last=keep_last).items(): for first_last_event_name in values: try: match_event_names(event_id, [first_last_event_name]) except KeyError: raise ValueError( f'Event "{first_last_event_name}", specified in ' f'{param_name}, cannot be found in event_id dictionary') event_name_diff = sorted(set(row_events) - set(event_id.keys())) if event_name_diff: raise ValueError( f'Present in row_events, but missing from event_id: ' f'{', '.join(event_name_diff)}') del event_name_diff # First and last sample of each epoch, relative to the time-locked event # This follows the approach taken in mne.Epochs start_sample = int(round(tmin * sfreq)) stop_sample = int(round(tmax * sfreq)) + 1 # Make indexing easier # We create the DataFrame before subsetting the events so we end up with # indices corresponding to the original event indices. Not used for now, # but might come in handy sometime later events_df = pd.DataFrame(events, columns=('sample', 'prev_id', 'id')) id_to_name_map = {v: k for k, v in event_id.items()} # Only keep events that are of interest events = events[np.in1d(events[:, 2], list(event_id.values()))] events_df = events_df.loc[events_df['id'].isin(event_id.values()), :] # Prepare & condition the metadata DataFrame # Avoid column name duplications if the exact same event name appears in # event_id.keys() and keep_first / keep_last simultaneously keep_first_cols = [col for col in keep_first if col not in event_id] keep_last_cols = [col for col in keep_last if col not in event_id] first_cols = [f'first_{col}' for col in keep_first_cols] last_cols = [f'last_{col}' for col in keep_last_cols] columns = ['event_name', *event_id.keys(), *keep_first_cols, *keep_last_cols, *first_cols, *last_cols] data = np.empty((len(events_df), len(columns))) metadata = pd.DataFrame(data=data, columns=columns, index=events_df.index) # Event names metadata.iloc[:, 0] = '' # Event times start_idx = 1 stop_idx = (start_idx + len(event_id.keys()) + len(keep_first_cols + keep_last_cols)) metadata.iloc[:, start_idx:stop_idx] = np.nan # keep_first and keep_last names start_idx = stop_idx metadata.iloc[:, start_idx:] = None # We're all set, let's iterate over all eventns and fill in in the # respective cells in the metadata. We will subset this to include only # `row_events` later for row_event in events_df.itertuples(name='RowEvent'): row_idx = row_event.Index metadata.loc[row_idx, 'event_name'] = \ id_to_name_map[row_event.id] # Determine which events fall into the current epoch window_start_sample = row_event.sample + start_sample window_stop_sample = row_event.sample + stop_sample events_in_window = events_df.loc[ (events_df['sample'] >= window_start_sample) & (events_df['sample'] <= window_stop_sample), :] assert not events_in_window.empty # Store the metadata for event in events_in_window.itertuples(name='Event'): event_sample = event.sample - row_event.sample event_time = event_sample / sfreq event_time = 0 if np.isclose(event_time, 0) else event_time event_name = id_to_name_map[event.id] if not np.isnan(metadata.loc[row_idx, event_name]): # Event already exists in current time window! assert metadata.loc[row_idx, event_name] <= event_time if event_name not in keep_last: continue metadata.loc[row_idx, event_name] = event_time # Handle keep_first and keep_last event aggregation for event_group_name in keep_first + keep_last: if event_name not in match_event_names( event_id, [event_group_name] ): continue if event_group_name in keep_first: first_last_col = f'first_{event_group_name}' else: first_last_col = f'last_{event_group_name}' old_time = metadata.loc[row_idx, event_group_name] if not np.isnan(old_time): if ((event_group_name in keep_first and old_time <= event_time) or (event_group_name in keep_last and old_time >= event_time)): continue if event_group_name not in event_id: # This is an HED. Strip redundant information from the # event name name = (event_name .replace(event_group_name, '') .replace('//', '/') .strip('/')) metadata.loc[row_idx, first_last_col] = name del name metadata.loc[row_idx, event_group_name] = event_time # Only keep rows of interest if row_events: event_id_timelocked = {name: val for name, val in event_id.items() if name in row_events} events = events[np.in1d(events[:, 2], list(event_id_timelocked.values()))] metadata = metadata.loc[ metadata['event_name'].isin(event_id_timelocked)] assert len(events) == len(metadata) event_id = event_id_timelocked return metadata, events, event_id @fill_doc class Epochs(BaseEpochs): """Epochs extracted from a Raw instance. Parameters ---------- %(epochs_raw)s %(events_epochs)s %(event_id)s %(epochs_tmin_tmax)s %(baseline_epochs)s Defaults to ``(None, 0)``, i.e. beginning of the the data until time point zero. %(picks_all)s preload : bool %(epochs_preload)s %(reject_epochs)s %(flat)s %(proj_epochs)s %(decim)s %(epochs_reject_tmin_tmax)s %(epochs_detrend)s %(epochs_on_missing)s %(reject_by_annotation_epochs)s %(epochs_metadata)s %(epochs_event_repeated)s %(verbose)s Attributes ---------- %(info_not_none)s event_id : dict Names of conditions corresponding to event_ids. ch_names : list of string List of channel names. selection : array List of indices of selected events (not dropped or ignored etc.). For example, if the original event array had 4 events and the second event has been dropped, this attribute would be np.array([0, 2, 3]). preload : bool Indicates whether epochs are in memory. drop_log : tuple of tuple A tuple of the same length as the event array used to initialize the Epochs object. If the i-th original event is still part of the selection, drop_log[i] will be an empty tuple; otherwise it will be a tuple of the reasons the event is not longer in the selection, e.g.: - 'IGNORED' If it isn't part of the current subset defined by the user - 'NO_DATA' or 'TOO_SHORT' If epoch didn't contain enough data names of channels that exceeded the amplitude threshold - 'EQUALIZED_COUNTS' See :meth:`~mne.Epochs.equalize_event_counts` - 'USER' For user-defined reasons (see :meth:`~mne.Epochs.drop`). filename : str The filename of the object. times : ndarray Time vector in seconds. Goes from ``tmin`` to ``tmax``. Time interval between consecutive time samples is equal to the inverse of the sampling frequency. See Also -------- mne.epochs.combine_event_ids mne.Epochs.equalize_event_counts Notes ----- When accessing data, Epochs are detrended, baseline-corrected, and decimated, then projectors are (optionally) applied. For indexing and slicing using ``epochs[...]``, see :meth:`mne.Epochs.__getitem__`. All methods for iteration over objects (using :meth:`mne.Epochs.__iter__`, :meth:`mne.Epochs.iter_evoked` or :meth:`mne.Epochs.next`) use the same internal state. If ``event_repeated`` is set to ``'merge'``, the coinciding events (duplicates) will be merged into a single event_id and assigned a new id_number as:: event_id['{event_id_1}/{event_id_2}/...'] = new_id_number For example with the event_id ``{'aud': 1, 'vis': 2}`` and the events ``[[0, 0, 1], [0, 0, 2]]``, the "merge" behavior will update both event_id and events to be: ``{'aud/vis': 3}`` and ``[[0, 0, 3]]`` respectively. There is limited support for :class:`~mne.Annotations` in the :class:`~mne.Epochs` class. Currently annotations that are present in the :class:`~mne.io.Raw` object will be preserved in the resulting :class:`~mne.Epochs` object, but: 1. It is not yet possible to add annotations to the Epochs object programmatically (via code) or interactively (through the plot window) 2. Concatenating :class:`~mne.Epochs` objects that contain annotations is not supported, and any annotations will be dropped when concatenating. 3. Annotations will be lost on save. """ @verbose def __init__(self, raw, events, event_id=None, tmin=-0.2, tmax=0.5, baseline=(None, 0), picks=None, preload=False, reject=None, flat=None, proj=True, decim=1, reject_tmin=None, reject_tmax=None, detrend=None, on_missing='raise', reject_by_annotation=True, metadata=None, event_repeated='error', verbose=None): # noqa: D102 if not isinstance(raw, BaseRaw): raise ValueError('The first argument to `Epochs` must be an ' 'instance of mne.io.BaseRaw') info = deepcopy(raw.info) # proj is on when applied in Raw proj = proj or raw.proj self.reject_by_annotation = reject_by_annotation # keep track of original sfreq (needed for annotations) raw_sfreq = raw.info['sfreq'] # call BaseEpochs constructor super(Epochs, self).__init__( info, None, events, event_id, tmin, tmax, metadata=metadata, baseline=baseline, raw=raw, picks=picks, reject=reject, flat=flat, decim=decim, reject_tmin=reject_tmin, reject_tmax=reject_tmax, detrend=detrend, proj=proj, on_missing=on_missing, preload_at_end=preload, event_repeated=event_repeated, verbose=verbose, raw_sfreq=raw_sfreq, annotations=raw.annotations) @verbose def _get_epoch_from_raw(self, idx, verbose=None): """Load one epoch from disk. Returns ------- data : array | str | None If string, it's details on rejection reason. If array, it's the data in the desired range (good segment) If None, it means no data is available. """ if self._raw is None: # This should never happen, as raw=None only if preload=True raise ValueError('An error has occurred, no valid raw file found. ' 'Please report this to the mne-python ' 'developers.') sfreq = self._raw.info['sfreq'] event_samp = self.events[idx, 0] # Read a data segment from "start" to "stop" in samples first_samp = self._raw.first_samp start = int(round(event_samp + self._raw_times[0] * sfreq)) start -= first_samp stop = start + len(self._raw_times) # reject_tmin, and reject_tmax need to be converted to samples to # check the reject_by_annotation boundaries: reject_start, reject_stop reject_tmin = self.reject_tmin if reject_tmin is None: reject_tmin = self._raw_times[0] reject_start = int(round(event_samp + reject_tmin * sfreq)) reject_start -= first_samp reject_tmax = self.reject_tmax if reject_tmax is None: reject_tmax = self._raw_times[-1] diff = int(round((self._raw_times[-1] - reject_tmax) * sfreq)) reject_stop = stop - diff logger.debug(' Getting epoch for %d-%d' % (start, stop)) data = self._raw._check_bad_segment(start, stop, self.picks, reject_start, reject_stop, self.reject_by_annotation) return data @fill_doc class EpochsArray(BaseEpochs): """Epochs object from numpy array. Parameters ---------- data : array, shape (n_epochs, n_channels, n_times) The channels' time series for each epoch. See notes for proper units of measure. %(info_not_none)s Consider using :func:`mne.create_info` to populate this structure. events : None | array of int, shape (n_events, 3) The events typically returned by the read_events function. If some events don't match the events of interest as specified by event_id, they will be marked as 'IGNORED' in the drop log. If None (default), all event values are set to 1 and event time-samples are set to range(n_epochs). tmin : float Start time before event. If nothing provided, defaults to 0. event_id : int | list of int | dict | None The id of the event to consider. If dict, the keys can later be used to access associated events. Example: dict(auditory=1, visual=3). If int, a dict will be created with the id as string. If a list, all events with the IDs specified in the list are used. If None, all events will be used with and a dict is created with string integer names corresponding to the event id integers. %(reject_epochs)s %(flat)s reject_tmin : scalar | None Start of the time window used to reject epochs (with the default None, the window will start with tmin). reject_tmax : scalar | None End of the time window used to reject epochs (with the default None, the window will end with tmax). %(baseline_epochs)s Defaults to ``None``, i.e. no baseline correction. proj : bool | 'delayed' Apply SSP projection vectors. See :class:`mne.Epochs` for details. on_missing : str See :class:`mne.Epochs` docstring for details. metadata : instance of pandas.DataFrame | None See :class:`mne.Epochs` docstring for details. .. versionadded:: 0.16 selection : ndarray | None The selection compared to the original set of epochs. Can be None to use ``np.arange(len(events))``. .. versionadded:: 0.16 %(verbose)s See Also -------- create_info EvokedArray io.RawArray Notes ----- Proper units of measure: * V: eeg, eog, seeg, dbs, emg, ecg, bio, ecog * T: mag * T/m: grad * M: hbo, hbr * Am: dipole * AU: misc EpochsArray does not set `Annotations`. If you would like to create simulated data with Annotations that are then preserved in the Epochs object, you would use `mne.io.RawArray` first and then create an `mne.Epochs` object. """ @verbose def __init__(self, data, info, events=None, tmin=0, event_id=None, reject=None, flat=None, reject_tmin=None, reject_tmax=None, baseline=None, proj=True, on_missing='raise', metadata=None, selection=None, verbose=None): # noqa: D102 dtype = np.complex128 if np.any(np.iscomplex(data)) else np.float64 data = np.asanyarray(data, dtype=dtype) if data.ndim != 3: raise ValueError('Data must be a 3D array of shape (n_epochs, ' 'n_channels, n_samples)') if len(info['ch_names']) != data.shape[1]: raise ValueError('Info and data must have same number of ' 'channels.') if events is None: n_epochs = len(data) events = _gen_events(n_epochs) info = info.copy() # do not modify original info tmax = (data.shape[2] - 1) / info['sfreq'] + tmin super(EpochsArray, self).__init__( info, data, events, event_id, tmin, tmax, baseline, reject=reject, flat=flat, reject_tmin=reject_tmin, reject_tmax=reject_tmax, decim=1, metadata=metadata, selection=selection, proj=proj, on_missing=on_missing, verbose=verbose) if self.baseline is not None: self._do_baseline = True if len(events) != np.in1d(self.events[:, 2], list(self.event_id.values())).sum(): raise ValueError('The events must only contain event numbers from ' 'event_id') detrend_picks = self._detrend_picks for e in self._data: # This is safe without assignment b/c there is no decim self._detrend_offset_decim(e, detrend_picks) self.drop_bad() def combine_event_ids(epochs, old_event_ids, new_event_id, copy=True): """Collapse event_ids from an epochs instance into a new event_id. Parameters ---------- epochs : instance of Epochs The epochs to operate on. old_event_ids : str, or list Conditions to collapse together. new_event_id : dict, or int A one-element dict (or a single integer) for the new condition. Note that for safety, this cannot be any existing id (in epochs.event_id.values()). copy : bool Whether to return a new instance or modify in place. Returns ------- epochs : instance of Epochs The modified epochs. Notes ----- This For example (if epochs.event_id was ``{'Left': 1, 'Right': 2}``:: combine_event_ids(epochs, ['Left', 'Right'], {'Directional': 12}) would create a 'Directional' entry in epochs.event_id replacing 'Left' and 'Right' (combining their trials). """ epochs = epochs.copy() if copy else epochs old_event_ids = np.asanyarray(old_event_ids) if isinstance(new_event_id, int): new_event_id = {str(new_event_id): new_event_id} else: if not isinstance(new_event_id, dict): raise ValueError('new_event_id must be a dict or int') if not len(list(new_event_id.keys())) == 1: raise ValueError('new_event_id dict must have one entry') new_event_num = list(new_event_id.values())[0] new_event_num = operator.index(new_event_num) if new_event_num in epochs.event_id.values(): raise ValueError('new_event_id value must not already exist') # could use .pop() here, but if a latter one doesn't exist, we're # in trouble, so run them all here and pop() later old_event_nums = np.array([epochs.event_id[key] for key in old_event_ids]) # find the ones to replace inds = np.any(epochs.events[:, 2][:, np.newaxis] == old_event_nums[np.newaxis, :], axis=1) # replace the event numbers in the events list epochs.events[inds, 2] = new_event_num # delete old entries for key in old_event_ids: epochs.event_id.pop(key) # add the new entry epochs.event_id.update(new_event_id) return epochs def equalize_epoch_counts(epochs_list, method='mintime'): """Equalize the number of trials in multiple Epoch instances. Parameters ---------- epochs_list : list of Epochs instances The Epochs instances to equalize trial counts for. method : str If 'truncate', events will be truncated from the end of each event list. If 'mintime', timing differences between each event list will be minimized. Notes ----- This tries to make the remaining epochs occurring as close as possible in time. This method works based on the idea that if there happened to be some time-varying (like on the scale of minutes) noise characteristics during a recording, they could be compensated for (to some extent) in the equalization process. This method thus seeks to reduce any of those effects by minimizing the differences in the times of the events in the two sets of epochs. For example, if one had event times [1, 2, 3, 4, 120, 121] and the other one had [3.5, 4.5, 120.5, 121.5], it would remove events at times [1, 2] in the first epochs and not [120, 121]. Examples -------- >>> equalize_epoch_counts([epochs1, epochs2]) # doctest: +SKIP """ if not all(isinstance(e, BaseEpochs) for e in epochs_list): raise ValueError('All inputs must be Epochs instances') # make sure bad epochs are dropped for e in epochs_list: if not e._bad_dropped: e.drop_bad() event_times = [e.events[:, 0] for e in epochs_list] indices = _get_drop_indices(event_times, method) for e, inds in zip(epochs_list, indices): e.drop(inds, reason='EQUALIZED_COUNT') def _get_drop_indices(event_times, method): """Get indices to drop from multiple event timing lists.""" small_idx = np.argmin([e.shape[0] for e in event_times]) small_e_times = event_times[small_idx] _check_option('method', method, ['mintime', 'truncate']) indices = list() for e in event_times: if method == 'mintime': mask = _minimize_time_diff(small_e_times, e) else: mask = np.ones(e.shape[0], dtype=bool) mask[small_e_times.shape[0]:] = False indices.append(np.where(np.logical_not(mask))[0]) return indices def _minimize_time_diff(t_shorter, t_longer): """Find a boolean mask to minimize timing differences.""" from scipy.interpolate import interp1d keep = np.ones((len(t_longer)), dtype=bool) # special case: length zero or one if len(t_shorter) < 2: # interp1d won't work keep.fill(False) if len(t_shorter) == 1: idx = np.argmin(np.abs(t_longer - t_shorter)) keep[idx] = True return keep scores = np.ones((len(t_longer))) x1 = np.arange(len(t_shorter)) # The first set of keep masks to test kwargs = dict(copy=False, bounds_error=False, assume_sorted=True) shorter_interp = interp1d(x1, t_shorter, fill_value=t_shorter[-1], **kwargs) for ii in range(len(t_longer) - len(t_shorter)): scores.fill(np.inf) # set up the keep masks to test, eliminating any rows that are already # gone keep_mask = ~np.eye(len(t_longer), dtype=bool)[keep] keep_mask[:, ~keep] = False # Check every possible removal to see if it minimizes x2 = np.arange(len(t_longer) - ii - 1) t_keeps = np.array([t_longer[km] for km in keep_mask]) longer_interp = interp1d(x2, t_keeps, axis=1, fill_value=t_keeps[:, -1], **kwargs) d1 = longer_interp(x1) - t_shorter d2 = shorter_interp(x2) - t_keeps scores[keep] = np.abs(d1, d1).sum(axis=1) + np.abs(d2, d2).sum(axis=1) keep[np.argmin(scores)] = False return keep @verbose def _is_good(e, ch_names, channel_type_idx, reject, flat, full_report=False, ignore_chs=[], verbose=None): """Test if data segment e is good according to reject and flat. If full_report=True, it will give True/False as well as a list of all offending channels. """ bad_tuple = tuple() has_printed = False checkable = np.ones(len(ch_names), dtype=bool) checkable[np.array([c in ignore_chs for c in ch_names], dtype=bool)] = False for refl, f, t in zip([reject, flat], [np.greater, np.less], ['', 'flat']): if refl is not None: for key, thresh in refl.items(): idx = channel_type_idx[key] name = key.upper() if len(idx) > 0: e_idx = e[idx] deltas = np.max(e_idx, axis=1) - np.min(e_idx, axis=1) checkable_idx = checkable[idx] idx_deltas = np.where(np.logical_and(f(deltas, thresh), checkable_idx))[0] if len(idx_deltas) > 0: bad_names = [ch_names[idx[i]] for i in idx_deltas] if (not has_printed): logger.info(' Rejecting %s epoch based on %s : ' '%s' % (t, name, bad_names)) has_printed = True if not full_report: return False else: bad_tuple += tuple(bad_names) if not full_report: return True else: if bad_tuple == (): return True, None else: return False, bad_tuple def _read_one_epoch_file(f, tree, preload): """Read a single FIF file.""" with f as fid: # Read the measurement info info, meas = read_meas_info(fid, tree, clean_bads=True) # read in the Annotations if they exist annotations = _read_annotations_fif(fid, tree) events, mappings = _read_events_fif(fid, tree) # Metadata metadata = None metadata_tree = dir_tree_find(tree, FIFF.FIFFB_MNE_METADATA) if len(metadata_tree) > 0: for dd in metadata_tree[0]['directory']: kind = dd.kind pos = dd.pos if kind == FIFF.FIFF_DESCRIPTION: metadata = read_tag(fid, pos).data metadata = _prepare_read_metadata(metadata) break # Locate the data of interest processed = dir_tree_find(meas, FIFF.FIFFB_PROCESSED_DATA) del meas if len(processed) == 0: raise ValueError('Could not find processed data') epochs_node = dir_tree_find(tree, FIFF.FIFFB_MNE_EPOCHS) if len(epochs_node) == 0: # before version 0.11 we errantly saved with this tag instead of # an MNE tag epochs_node = dir_tree_find(tree, FIFF.FIFFB_MNE_EPOCHS) if len(epochs_node) == 0: epochs_node = dir_tree_find(tree, 122) # 122 used before v0.11 if len(epochs_node) == 0: raise ValueError('Could not find epochs data') my_epochs = epochs_node[0] # Now find the data in the block data = None data_tag = None bmin, bmax = None, None baseline = None selection = None drop_log = None raw_sfreq = None reject_params = {} for k in range(my_epochs['nent']): kind = my_epochs['directory'][k].kind pos = my_epochs['directory'][k].pos if kind == FIFF.FIFF_FIRST_SAMPLE: tag = read_tag(fid, pos) first = int(tag.data) elif kind == FIFF.FIFF_LAST_SAMPLE: tag = read_tag(fid, pos) last = int(tag.data) elif kind == FIFF.FIFF_EPOCH: # delay reading until later fid.seek(pos, 0) data_tag = read_tag_info(fid) data_tag.pos = pos data_tag.type = data_tag.type ^ (1 << 30) elif kind in [FIFF.FIFF_MNE_BASELINE_MIN, 304]: # Constant 304 was used before v0.11 tag = read_tag(fid, pos) bmin = float(tag.data) elif kind in [FIFF.FIFF_MNE_BASELINE_MAX, 305]: # Constant 305 was used before v0.11 tag = read_tag(fid, pos) bmax = float(tag.data) elif kind == FIFF.FIFF_MNE_EPOCHS_SELECTION: tag = read_tag(fid, pos) selection = np.array(tag.data) elif kind == FIFF.FIFF_MNE_EPOCHS_DROP_LOG: tag = read_tag(fid, pos) drop_log = tag.data drop_log = json.loads(drop_log) drop_log = tuple(tuple(x) for x in drop_log) elif kind == FIFF.FIFF_MNE_EPOCHS_REJECT_FLAT: tag = read_tag(fid, pos) reject_params = json.loads(tag.data) elif kind == FIFF.FIFF_MNE_EPOCHS_RAW_SFREQ: tag = read_tag(fid, pos) raw_sfreq = tag.data if bmin is not None or bmax is not None: baseline = (bmin, bmax) n_samp = last - first + 1 logger.info(' Found the data of interest:') logger.info(' t = %10.2f ... %10.2f ms' % (1000 * first / info['sfreq'], 1000 * last / info['sfreq'])) if info['comps'] is not None: logger.info(' %d CTF compensation matrices available' % len(info['comps'])) # Inspect the data if data_tag is None: raise ValueError('Epochs data not found') epoch_shape = (len(info['ch_names']), n_samp) size_expected = len(events) * np.prod(epoch_shape) # on read double-precision is always used if data_tag.type == FIFF.FIFFT_FLOAT: datatype = np.float64 fmt = '>f4' elif data_tag.type == FIFF.FIFFT_DOUBLE: datatype = np.float64 fmt = '>f8' elif data_tag.type == FIFF.FIFFT_COMPLEX_FLOAT: datatype = np.complex128 fmt = '>c8' elif data_tag.type == FIFF.FIFFT_COMPLEX_DOUBLE: datatype = np.complex128 fmt = '>c16' fmt_itemsize = np.dtype(fmt).itemsize assert fmt_itemsize in (4, 8, 16) size_actual = data_tag.size // fmt_itemsize - 16 // fmt_itemsize if not size_actual == size_expected: raise ValueError('Incorrect number of samples (%d instead of %d)' % (size_actual, size_expected)) # Calibration factors cals = np.array([[info['chs'][k]['cal'] * info['chs'][k].get('scale', 1.0)] for k in range(info['nchan'])], np.float64) # Read the data if preload: data = read_tag(fid, data_tag.pos).data.astype(datatype) data *= cals # Put it all together tmin = first / info['sfreq'] tmax = last / info['sfreq'] event_id = ({str(e): e for e in np.unique(events[:, 2])} if mappings is None else mappings) # In case epochs didn't have a FIFF.FIFF_MNE_EPOCHS_SELECTION tag # (version < 0.8): if selection is None: selection = np.arange(len(events)) if drop_log is None: drop_log = ((),) * len(events) return (info, data, data_tag, events, event_id, metadata, tmin, tmax, baseline, selection, drop_log, epoch_shape, cals, reject_params, fmt, annotations, raw_sfreq) @verbose def read_epochs(fname, proj=True, preload=True, verbose=None): """Read epochs from a fif file. Parameters ---------- %(epochs_fname)s %(proj_epochs)s preload : bool If True, read all epochs from disk immediately. If ``False``, epochs will be read on demand. %(verbose)s Returns ------- epochs : instance of Epochs The epochs. """ return EpochsFIF(fname, proj, preload, verbose) class _RawContainer(object): """Helper for a raw data container.""" def __init__(self, fid, data_tag, event_samps, epoch_shape, cals, fmt): # noqa: D102 self.fid = fid self.data_tag = data_tag self.event_samps = event_samps self.epoch_shape = epoch_shape self.cals = cals self.proj = False self.fmt = fmt def __del__(self): # noqa: D105 self.fid.close() @fill_doc class EpochsFIF(BaseEpochs): """Epochs read from disk. Parameters ---------- %(epochs_fname)s %(proj_epochs)s preload : bool If True, read all epochs from disk immediately. If False, epochs will be read on demand. %(verbose)s See Also -------- mne.Epochs mne.epochs.combine_event_ids mne.Epochs.equalize_event_counts """ @verbose def __init__(self, fname, proj=True, preload=True, verbose=None): # noqa: D102 if _path_like(fname): check_fname( fname=fname, filetype='epochs', endings=('-epo.fif', '-epo.fif.gz', '_epo.fif', '_epo.fif.gz') ) fname = _check_fname(fname=fname, must_exist=True, overwrite='read') elif not preload: raise ValueError('preload must be used with file-like objects') fnames = [fname] ep_list = list() raw = list() for fname in fnames: fname_rep = _get_fname_rep(fname) logger.info('Reading %s ...' % fname_rep) fid, tree, _ = fiff_open(fname, preload=preload) next_fname = _get_next_fname(fid, fname, tree) (info, data, data_tag, events, event_id, metadata, tmin, tmax, baseline, selection, drop_log, epoch_shape, cals, reject_params, fmt, annotations, raw_sfreq) = \ _read_one_epoch_file(fid, tree, preload) if (events[:, 0] < 0).any(): events = events.copy() warn('Incorrect events detected on disk, setting event ' 'numbers to consecutive increasing integers') events[:, 0] = np.arange(1, len(events) + 1) # here we ignore missing events, since users should already be # aware of missing events if they have saved data that way # we also retain original baseline without re-applying baseline # correction (data is being baseline-corrected when written to # disk) epoch = BaseEpochs( info, data, events, event_id, tmin, tmax, baseline=None, metadata=metadata, on_missing='ignore', selection=selection, drop_log=drop_log, proj=False, verbose=False, raw_sfreq=raw_sfreq) epoch.baseline = baseline epoch._do_baseline = False # might be superfluous but won't hurt ep_list.append(epoch) if not preload: # store everything we need to index back to the original data raw.append(_RawContainer(fiff_open(fname)[0], data_tag, events[:, 0].copy(), epoch_shape, cals, fmt)) if next_fname is not None: fnames.append(next_fname) unsafe_annot_add = raw_sfreq is None (info, data, raw_sfreq, events, event_id, tmin, tmax, metadata, baseline, selection, drop_log) = \ _concatenate_epochs(ep_list, with_data=preload, add_offset=False) # we need this uniqueness for non-preloaded data to work properly if len(np.unique(events[:, 0])) != len(events): raise RuntimeError('Event time samples were not unique') # correct the drop log assert len(drop_log) % len(fnames) == 0 step = len(drop_log) // len(fnames) offsets = np.arange(step, len(drop_log) + 1, step) drop_log = list(drop_log) for i1, i2 in zip(offsets[:-1], offsets[1:]): other_log = drop_log[i1:i2] for k, (a, b) in enumerate(zip(drop_log, other_log)): if a == ('IGNORED',) and b != ('IGNORED',): drop_log[k] = b drop_log = tuple(drop_log[:step]) # call BaseEpochs constructor # again, ensure we're retaining the baseline period originally loaded # from disk without trying to re-apply baseline correction super(EpochsFIF, self).__init__( info, data, events, event_id, tmin, tmax, baseline=None, raw=raw, proj=proj, preload_at_end=False, on_missing='ignore', selection=selection, drop_log=drop_log, filename=fname_rep, metadata=metadata, verbose=verbose, raw_sfreq=raw_sfreq, annotations=annotations, **reject_params) self.baseline = baseline self._do_baseline = False # use the private property instead of drop_bad so that epochs # are not all read from disk for preload=False self._bad_dropped = True # private property to suggest that people re-save epochs if they add # annotations self._unsafe_annot_add = unsafe_annot_add @verbose def _get_epoch_from_raw(self, idx, verbose=None): """Load one epoch from disk.""" # Find the right file and offset to use event_samp = self.events[idx, 0] for raw in self._raw: idx = np.where(raw.event_samps == event_samp)[0] if len(idx) == 1: fmt = raw.fmt idx = idx[0] size = np.prod(raw.epoch_shape) * np.dtype(fmt).itemsize offset = idx * size + 16 # 16 = Tag header break else: # read the correct subset of the data raise RuntimeError('Correct epoch could not be found, please ' 'contact mne-python developers') # the following is equivalent to this, but faster: # # >>> data = read_tag(raw.fid, raw.data_tag.pos).data.astype(float) # >>> data *= raw.cals[np.newaxis, :, :] # >>> data = data[idx] # # Eventually this could be refactored in io/tag.py if other functions # could make use of it raw.fid.seek(raw.data_tag.pos + offset, 0) if fmt == '>c8': read_fmt = '>f4' elif fmt == '>c16': read_fmt = '>f8' else: read_fmt = fmt data = np.frombuffer(raw.fid.read(size), read_fmt) if read_fmt != fmt: data = data.view(fmt) data = data.astype(np.complex128) else: data = data.astype(np.float64) data.shape = raw.epoch_shape data *= raw.cals return data @fill_doc def bootstrap(epochs, random_state=None): """Compute epochs selected by bootstrapping. Parameters ---------- epochs : Epochs instance epochs data to be bootstrapped %(random_state)s Returns ------- epochs : Epochs instance The bootstrap samples """ if not epochs.preload: raise RuntimeError('Modifying data of epochs is only supported ' 'when preloading is used. Use preload=True ' 'in the constructor.') rng = check_random_state(random_state) epochs_bootstrap = epochs.copy() n_events = len(epochs_bootstrap.events) idx = rng_uniform(rng)(0, n_events, n_events) epochs_bootstrap = epochs_bootstrap[idx] return epochs_bootstrap def _check_merge_epochs(epochs_list): """Aux function.""" if len({tuple(epochs.event_id.items()) for epochs in epochs_list}) != 1: raise NotImplementedError("Epochs with unequal values for event_id") if len({epochs.tmin for epochs in epochs_list}) != 1: raise NotImplementedError("Epochs with unequal values for tmin") if len({epochs.tmax for epochs in epochs_list}) != 1: raise NotImplementedError("Epochs with unequal values for tmax") if len({epochs.baseline for epochs in epochs_list}) != 1: raise NotImplementedError("Epochs with unequal values for baseline") @verbose def add_channels_epochs(epochs_list, verbose=None): """Concatenate channels, info and data from two Epochs objects. Parameters ---------- epochs_list : list of Epochs Epochs object to concatenate. %(verbose)s Defaults to True if any of the input epochs have verbose=True. Returns ------- epochs : instance of Epochs Concatenated epochs. """ if not all(e.preload for e in epochs_list): raise ValueError('All epochs must be preloaded.') info = _merge_info([epochs.info for epochs in epochs_list]) data = [epochs._data for epochs in epochs_list] _check_merge_epochs(epochs_list) for d in data: if len(d) != len(data[0]): raise ValueError('all epochs must be of the same length') data = np.concatenate(data, axis=1) if len(info['chs']) != data.shape[1]: err = "Data shape does not match channel number in measurement info" raise RuntimeError(err) events = epochs_list[0].events.copy() all_same = all(np.array_equal(events, epochs.events) for epochs in epochs_list[1:]) if not all_same: raise ValueError('Events must be the same.') proj = any(e.proj for e in epochs_list) epochs = epochs_list[0].copy() epochs.info = info epochs.picks = None epochs.events = events epochs.preload = True epochs._bad_dropped = True epochs._data = data epochs._projector, epochs.info = setup_proj(epochs.info, False, activate=proj) return epochs def _concatenate_epochs(epochs_list, with_data=True, add_offset=True, *, on_mismatch='raise'): """Auxiliary function for concatenating epochs.""" if not isinstance(epochs_list, (list, tuple)): raise TypeError('epochs_list must be a list or tuple, got %s' % (type(epochs_list),)) # to make warning messages only occur once during concatenation warned = False for ei, epochs in enumerate(epochs_list): if not isinstance(epochs, BaseEpochs): raise TypeError('epochs_list[%d] must be an instance of Epochs, ' 'got %s' % (ei, type(epochs))) if (getattr(epochs, 'annotations', None) is not None and len(epochs.annotations) > 0 and not warned): warned = True warn('Concatenation of Annotations within Epochs is not supported ' 'yet. All annotations will be dropped.') # create a copy, so that the Annotations are not modified in place # from the original object epochs = epochs.copy() epochs.set_annotations(None) out = epochs_list[0] offsets = [0] if with_data: out.drop_bad() offsets.append(len(out)) events = [out.events] metadata = [out.metadata] baseline, tmin, tmax = out.baseline, out.tmin, out.tmax raw_sfreq = out._raw_sfreq info = deepcopy(out.info) drop_log = out.drop_log event_id = deepcopy(out.event_id) selection = out.selection # offset is the last epoch + tmax + 10 second shift = int((10 + tmax) * out.info['sfreq']) events_offset = int(np.max(events[0][:, 0])) + shift events_overflow = False warned = False for ii, epochs in enumerate(epochs_list[1:], 1): _ensure_infos_match(epochs.info, info, f'epochs[{ii}]', on_mismatch=on_mismatch) if not np.allclose(epochs.times, epochs_list[0].times): raise ValueError('Epochs must have same times') if epochs.baseline != baseline: raise ValueError('Baseline must be same for all epochs') if epochs._raw_sfreq != raw_sfreq and not warned: warned = True warn('The original raw sampling rate of the Epochs does not ' 'match for all Epochs. Please proceed cautiously.') # compare event_id common_keys = list(set(event_id).intersection(set(epochs.event_id))) for key in common_keys: if not event_id[key] == epochs.event_id[key]: msg = ('event_id values must be the same for identical keys ' 'for all concatenated epochs. Key "{}" maps to {} in ' 'some epochs and to {} in others.') raise ValueError(msg.format(key, event_id[key], epochs.event_id[key])) if with_data: epochs.drop_bad() offsets.append(len(epochs)) evs = epochs.events.copy() if len(epochs.events) == 0: warn('One of the Epochs objects to concatenate was empty.') elif add_offset: # We need to cast to a native Python int here to detect an # overflow of a numpy int32 (which is the default on windows) max_timestamp = int(np.max(evs[:, 0])) evs[:, 0] += events_offset events_offset += max_timestamp + shift if events_offset > INT32_MAX: warn(f'Event number greater than {INT32_MAX} created, ' 'events[:, 0] will be assigned consecutive increasing ' 'integer values') events_overflow = True add_offset = False # we no longer need to add offset events.append(evs) selection = np.concatenate((selection, epochs.selection)) drop_log = drop_log + epochs.drop_log event_id.update(epochs.event_id) metadata.append(epochs.metadata) events = np.concatenate(events, axis=0) # check to see if we exceeded our maximum event offset if events_overflow: events[:, 0] = np.arange(1, len(events) + 1) # Create metadata object (or make it None) n_have = sum(this_meta is not None for this_meta in metadata) if n_have == 0: metadata = None elif n_have != len(metadata): raise ValueError('%d of %d epochs instances have metadata, either ' 'all or none must have metadata' % (n_have, len(metadata))) else: pd = _check_pandas_installed(strict=False) if pd is not False: metadata = pd.concat(metadata) else: # dict of dicts metadata = sum(metadata, list()) assert len(offsets) == (len(epochs_list) if with_data else 0) + 1 data = None if with_data: offsets = np.cumsum(offsets) for start, stop, epochs in zip(offsets[:-1], offsets[1:], epochs_list): this_data = epochs.get_data() if data is None: data = np.empty( (offsets[-1], len(out.ch_names), len(out.times)), dtype=this_data.dtype) data[start:stop] = this_data return (info, data, raw_sfreq, events, event_id, tmin, tmax, metadata, baseline, selection, drop_log) def _finish_concat(info, data, raw_sfreq, events, event_id, tmin, tmax, metadata, baseline, selection, drop_log): """Finish concatenation for epochs not read from disk.""" selection = np.where([len(d) == 0 for d in drop_log])[0] out = BaseEpochs( info, data, events, event_id, tmin, tmax, baseline=baseline, selection=selection, drop_log=drop_log, proj=False, on_missing='ignore', metadata=metadata, raw_sfreq=raw_sfreq) out.drop_bad() return out @verbose def concatenate_epochs(epochs_list, add_offset=True, *, on_mismatch='raise', verbose=None): """Concatenate a list of `~mne.Epochs` into one `~mne.Epochs` object. .. note:: Unlike `~mne.concatenate_raws`, this function does **not** modify any of the input data. Parameters ---------- epochs_list : list List of `~mne.Epochs` instances to concatenate (in that order). add_offset : bool If True, a fixed offset is added to the event times from different Epochs sets, such that they are easy to distinguish after the concatenation. If False, the event times are unaltered during the concatenation. %(on_info_mismatch)s %(verbose)s .. versionadded:: 0.24 Returns ------- epochs : instance of Epochs The result of the concatenation. Notes ----- .. versionadded:: 0.9.0 """ return _finish_concat(*_concatenate_epochs(epochs_list, add_offset=add_offset, on_mismatch=on_mismatch)) @verbose def average_movements(epochs, head_pos=None, orig_sfreq=None, picks=None, origin='auto', weight_all=True, int_order=8, ext_order=3, destination=None, ignore_ref=False, return_mapping=False, mag_scale=100., verbose=None): """Average data using Maxwell filtering, transforming using head positions. Parameters ---------- epochs : instance of Epochs The epochs to operate on. %(maxwell_pos)s orig_sfreq : float | None The original sample frequency of the data (that matches the event sample numbers in ``epochs.events``). Can be ``None`` if data have not been decimated or resampled. %(picks_all_data)s %(maxwell_origin)s weight_all : bool If True, all channels are weighted by the SSS basis weights. If False, only MEG channels are weighted, other channels receive uniform weight per epoch. %(maxwell_int)s %(maxwell_ext)s %(maxwell_dest)s %(maxwell_ref)s return_mapping : bool If True, return the mapping matrix. %(maxwell_mag)s .. versionadded:: 0.13 %(verbose)s Returns ------- evoked : instance of Evoked The averaged epochs. See Also -------- mne.preprocessing.maxwell_filter mne.chpi.read_head_pos Notes ----- The Maxwell filtering version of this algorithm is described in [1]_, in section V.B "Virtual signals and movement correction", equations 40-44. For additional validation, see [2]_. Regularization has not been added because in testing it appears to decrease dipole localization accuracy relative to using all components. Fine calibration and cross-talk cancellation, however, could be added to this algorithm based on user demand. .. versionadded:: 0.11 References ---------- .. [1] Taulu S. and Kajola M. "Presentation of electromagnetic multichannel data: The signal space separation method," Journal of Applied Physics, vol. 97, pp. 124905 1-10, 2005. .. [2] Wehner DT, Hämäläinen MS, Mody M, Ahlfors SP. "Head movements of children in MEG: Quantification, effects on source estimation, and compensation. NeuroImage 40:541–550, 2008. """ # noqa: E501 from .preprocessing.maxwell import (_trans_sss_basis, _reset_meg_bads, _check_usable, _col_norm_pinv, _get_n_moments, _get_mf_picks_fix_mags, _prep_mf_coils, _check_destination, _remove_meg_projs, _get_coil_scale) if head_pos is None: raise TypeError('head_pos must be provided and cannot be None') from .chpi import head_pos_to_trans_rot_t if not isinstance(epochs, BaseEpochs): raise TypeError('epochs must be an instance of Epochs, not %s' % (type(epochs),)) orig_sfreq = epochs.info['sfreq'] if orig_sfreq is None else orig_sfreq orig_sfreq = float(orig_sfreq) if isinstance(head_pos, np.ndarray): head_pos = head_pos_to_trans_rot_t(head_pos) trn, rot, t = head_pos del head_pos _check_usable(epochs) origin = _check_origin(origin, epochs.info, 'head') recon_trans = _check_destination(destination, epochs.info, True) logger.info('Aligning and averaging up to %s epochs' % (len(epochs.events))) if not np.array_equal(epochs.events[:, 0], np.unique(epochs.events[:, 0])): raise RuntimeError('Epochs must have monotonically increasing events') info_to = epochs.info.copy() meg_picks, mag_picks, grad_picks, good_mask, _ = \ _get_mf_picks_fix_mags(info_to, int_order, ext_order, ignore_ref) coil_scale, mag_scale = _get_coil_scale( meg_picks, mag_picks, grad_picks, mag_scale, info_to) n_channels, n_times = len(epochs.ch_names), len(epochs.times) other_picks = np.setdiff1d(np.arange(n_channels), meg_picks) data = np.zeros((n_channels, n_times)) count = 0 # keep only MEG w/bad channels marked in "info_from" info_from = pick_info(info_to, meg_picks[good_mask], copy=True) all_coils_recon = _prep_mf_coils(info_to, ignore_ref=ignore_ref) all_coils = _prep_mf_coils(info_from, ignore_ref=ignore_ref) # remove MEG bads in "to" info _reset_meg_bads(info_to) # set up variables w_sum = 0. n_in, n_out = _get_n_moments([int_order, ext_order]) S_decomp = 0. # this will end up being a weighted average last_trans = None decomp_coil_scale = coil_scale[good_mask] exp = dict(int_order=int_order, ext_order=ext_order, head_frame=True, origin=origin) n_in = _get_n_moments(int_order) for ei, epoch in enumerate(epochs): event_time = epochs.events[epochs._current - 1, 0] / orig_sfreq use_idx = np.where(t <= event_time)[0] if len(use_idx) == 0: trans = info_to['dev_head_t']['trans'] else: use_idx = use_idx[-1] trans = np.vstack([np.hstack([rot[use_idx], trn[[use_idx]].T]), [[0., 0., 0., 1.]]]) loc_str = ', '.join('%0.1f' % tr for tr in (trans[:3, 3] * 1000)) if last_trans is None or not np.allclose(last_trans, trans): logger.info(' Processing epoch %s (device location: %s mm)' % (ei + 1, loc_str)) reuse = False last_trans = trans else: logger.info(' Processing epoch %s (device location: same)' % (ei + 1,)) reuse = True epoch = epoch.copy() # because we operate inplace if not reuse: S = _trans_sss_basis(exp, all_coils, trans, coil_scale=decomp_coil_scale) # Get the weight from the un-regularized version (eq. 44) weight = np.linalg.norm(S[:, :n_in]) # XXX Eventually we could do cross-talk and fine-cal here S *= weight S_decomp += S # eq. 41 epoch[slice(None) if weight_all else meg_picks] *= weight data += epoch # eq. 42 w_sum += weight count += 1 del info_from mapping = None if count == 0: data.fill(np.nan) else: data[meg_picks] /= w_sum data[other_picks] /= w_sum if weight_all else count # Finalize weighted average decomp matrix S_decomp /= w_sum # Get recon matrix # (We would need to include external here for regularization to work) exp['ext_order'] = 0 S_recon = _trans_sss_basis(exp, all_coils_recon, recon_trans) exp['ext_order'] = ext_order # We could determine regularization on basis of destination basis # matrix, restricted to good channels, as regularizing individual # matrices within the loop above does not seem to work. But in # testing this seemed to decrease localization quality in most cases, # so we do not provide the option here. S_recon /= coil_scale # Invert pS_ave = _col_norm_pinv(S_decomp)[0][:n_in] pS_ave *= decomp_coil_scale.T # Get mapping matrix mapping = np.dot(S_recon, pS_ave) # Apply mapping data[meg_picks] = np.dot(mapping, data[meg_picks[good_mask]]) info_to['dev_head_t'] = recon_trans # set the reconstruction transform evoked = epochs._evoked_from_epoch_data(data, info_to, picks, n_events=count, kind='average', comment=epochs._name) _remove_meg_projs(evoked) # remove MEG projectors, they won't apply now logger.info('Created Evoked dataset from %s epochs' % (count,)) return (evoked, mapping) if return_mapping else evoked @verbose def make_fixed_length_epochs(raw, duration=1., preload=False, reject_by_annotation=True, proj=True, overlap=0., id=1, verbose=None): """Divide continuous raw data into equal-sized consecutive epochs. Parameters ---------- raw : instance of Raw Raw data to divide into segments. duration : float Duration of each epoch in seconds. Defaults to 1. %(preload)s %(reject_by_annotation_epochs)s .. versionadded:: 0.21.0 %(proj_epochs)s .. versionadded:: 0.22.0 overlap : float The overlap between epochs, in seconds. Must be ``0 <= overlap < duration``. Default is 0, i.e., no overlap. .. versionadded:: 0.23.0 id : int The id to use (default 1). .. versionadded:: 0.24.0 %(verbose)s Returns ------- epochs : instance of Epochs Segmented data. Notes ----- .. versionadded:: 0.20 """ events = make_fixed_length_events(raw, id=id, duration=duration, overlap=overlap) delta = 1. / raw.info['sfreq'] return Epochs(raw, events, event_id=[id], tmin=0, tmax=duration - delta, baseline=None, preload=preload, reject_by_annotation=reject_by_annotation, proj=proj, verbose=verbose)
# -*- coding: utf-8 -*- """Tools for working with epoched data.""" # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Matti Hämäläinen <msh@nmr.mgh.harvard.edu> # Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de> # Denis Engemann <denis.engemann@gmail.com> # Mainak Jas <mainak@neuro.hut.fi> # Stefan Appelhoff <stefan.appelhoff@mailbox.org> # # License: BSD-3-Clause from functools import partial from collections import Counter from copy import deepcopy import json import operator import os.path as op import numpy as np from .io.utils import _construct_bids_filename from .io.write import (start_and_end_file, start_block, end_block, write_int, write_float, write_float_matrix, write_double_matrix, write_complex_float_matrix, write_complex_double_matrix, write_id, write_string, _get_split_size, _NEXT_FILE_BUFFER, INT32_MAX) from .io.meas_info import (read_meas_info, write_meas_info, _merge_info, _ensure_infos_match) from .io.open import fiff_open, _get_next_fname from .io.tree import dir_tree_find from .io.tag import read_tag, read_tag_info from .io.constants import FIFF from .io.fiff.raw import _get_fname_rep from .io.pick import (channel_indices_by_type, channel_type, pick_channels, pick_info, _pick_data_channels, _DATA_CH_TYPES_SPLIT, _picks_to_idx) from .io.proj import setup_proj, ProjMixin from .io.base import BaseRaw, TimeMixin, _get_ch_factors from .bem import _check_origin from .evoked import EvokedArray, _check_decim from .baseline import rescale, _log_rescale, _check_baseline from .channels.channels import (ContainsMixin, UpdateChannelsMixin, SetChannelsMixin, InterpolationMixin) from .filter import detrend, FilterMixin, _check_fun from .parallel import parallel_func from .event import (_read_events_fif, make_fixed_length_events, match_event_names) from .fixes import rng_uniform from .viz import (plot_epochs, plot_epochs_psd, plot_epochs_psd_topomap, plot_epochs_image, plot_topo_image_epochs, plot_drop_log) from .utils import (_check_fname, check_fname, logger, verbose, _time_mask, check_random_state, warn, _pl, sizeof_fmt, SizeMixin, copy_function_doc_to_method_doc, _check_pandas_installed, _check_preload, GetEpochsMixin, _prepare_read_metadata, _prepare_write_metadata, _check_event_id, _gen_events, _check_option, _check_combine, ShiftTimeMixin, _build_data_frame, _check_pandas_index_arguments, _convert_times, _scale_dataframe_data, _check_time_format, object_size, _on_missing, _validate_type, _ensure_events, _path_like, _VerboseDep) from .utils.docs import fill_doc from .annotations import (_write_annotations, _read_annotations_fif, EpochAnnotationsMixin) def _pack_reject_params(epochs): reject_params = dict() for key in ('reject', 'flat', 'reject_tmin', 'reject_tmax'): val = getattr(epochs, key, None) if val is not None: reject_params[key] = val return reject_params def _save_split(epochs, fname, part_idx, n_parts, fmt, split_naming, overwrite): """Split epochs. Anything new added to this function also needs to be added to BaseEpochs.save to account for new file sizes. """ # insert index in filename base, ext = op.splitext(fname) if part_idx > 0: if split_naming == 'neuromag': fname = '%s-%d%s' % (base, part_idx, ext) else: assert split_naming == 'bids' fname = _construct_bids_filename(base, ext, part_idx, validate=False) _check_fname(fname, overwrite=overwrite) next_fname = None if part_idx < n_parts - 1: if split_naming == 'neuromag': next_fname = '%s-%d%s' % (base, part_idx + 1, ext) else: assert split_naming == 'bids' next_fname = _construct_bids_filename(base, ext, part_idx + 1, validate=False) next_idx = part_idx + 1 else: next_idx = None with start_and_end_file(fname) as fid: _save_part(fid, epochs, fmt, n_parts, next_fname, next_idx) def _save_part(fid, epochs, fmt, n_parts, next_fname, next_idx): info = epochs.info meas_id = info['meas_id'] start_block(fid, FIFF.FIFFB_MEAS) write_id(fid, FIFF.FIFF_BLOCK_ID) if info['meas_id'] is not None: write_id(fid, FIFF.FIFF_PARENT_BLOCK_ID, info['meas_id']) # Write measurement info write_meas_info(fid, info) # One or more evoked data sets start_block(fid, FIFF.FIFFB_PROCESSED_DATA) start_block(fid, FIFF.FIFFB_MNE_EPOCHS) # write events out after getting data to ensure bad events are dropped data = epochs.get_data() _check_option('fmt', fmt, ['single', 'double']) if np.iscomplexobj(data): if fmt == 'single': write_function = write_complex_float_matrix elif fmt == 'double': write_function = write_complex_double_matrix else: if fmt == 'single': write_function = write_float_matrix elif fmt == 'double': write_function = write_double_matrix # Epoch annotations are written if there are any annotations = getattr(epochs, 'annotations', []) if annotations is not None and len(annotations): _write_annotations(fid, annotations) # write Epoch event windows start_block(fid, FIFF.FIFFB_MNE_EVENTS) write_int(fid, FIFF.FIFF_MNE_EVENT_LIST, epochs.events.T) write_string(fid, FIFF.FIFF_DESCRIPTION, _event_id_string(epochs.event_id)) end_block(fid, FIFF.FIFFB_MNE_EVENTS) # Metadata if epochs.metadata is not None: start_block(fid, FIFF.FIFFB_MNE_METADATA) metadata = _prepare_write_metadata(epochs.metadata) write_string(fid, FIFF.FIFF_DESCRIPTION, metadata) end_block(fid, FIFF.FIFFB_MNE_METADATA) # First and last sample first = int(round(epochs.tmin * info['sfreq'])) # round just to be safe last = first + len(epochs.times) - 1 write_int(fid, FIFF.FIFF_FIRST_SAMPLE, first) write_int(fid, FIFF.FIFF_LAST_SAMPLE, last) # write raw original sampling rate write_float(fid, FIFF.FIFF_MNE_EPOCHS_RAW_SFREQ, epochs._raw_sfreq) # save baseline if epochs.baseline is not None: bmin, bmax = epochs.baseline write_float(fid, FIFF.FIFF_MNE_BASELINE_MIN, bmin) write_float(fid, FIFF.FIFF_MNE_BASELINE_MAX, bmax) # The epochs itself decal = np.empty(info['nchan']) for k in range(info['nchan']): decal[k] = 1.0 / (info['chs'][k]['cal'] * info['chs'][k].get('scale', 1.0)) data *= decal[np.newaxis, :, np.newaxis] write_function(fid, FIFF.FIFF_EPOCH, data) # undo modifications to data data /= decal[np.newaxis, :, np.newaxis] write_string(fid, FIFF.FIFF_MNE_EPOCHS_DROP_LOG, json.dumps(epochs.drop_log)) reject_params = _pack_reject_params(epochs) if reject_params: write_string(fid, FIFF.FIFF_MNE_EPOCHS_REJECT_FLAT, json.dumps(reject_params)) write_int(fid, FIFF.FIFF_MNE_EPOCHS_SELECTION, epochs.selection) # And now write the next file info in case epochs are split on disk if next_fname is not None and n_parts > 1: start_block(fid, FIFF.FIFFB_REF) write_int(fid, FIFF.FIFF_REF_ROLE, FIFF.FIFFV_ROLE_NEXT_FILE) write_string(fid, FIFF.FIFF_REF_FILE_NAME, op.basename(next_fname)) if meas_id is not None: write_id(fid, FIFF.FIFF_REF_FILE_ID, meas_id) write_int(fid, FIFF.FIFF_REF_FILE_NUM, next_idx) end_block(fid, FIFF.FIFFB_REF) end_block(fid, FIFF.FIFFB_MNE_EPOCHS) end_block(fid, FIFF.FIFFB_PROCESSED_DATA) end_block(fid, FIFF.FIFFB_MEAS) def _event_id_string(event_id): return ';'.join([k + ':' + str(v) for k, v in event_id.items()]) def _merge_events(events, event_id, selection): """Merge repeated events.""" event_id = event_id.copy() new_events = events.copy() event_idxs_to_delete = list() unique_events, counts = np.unique(events[:, 0], return_counts=True) for ev in unique_events[counts > 1]: # indices at which the non-unique events happened idxs = (events[:, 0] == ev).nonzero()[0] # Figure out new value for events[:, 1]. Set to 0, if mixed vals exist unique_priors = np.unique(events[idxs, 1]) new_prior = unique_priors[0] if len(unique_priors) == 1 else 0 # If duplicate time samples have same event val, "merge" == "drop" # and no new event_id key will be created ev_vals = np.unique(events[idxs, 2]) if len(ev_vals) <= 1: new_event_val = ev_vals[0] # Else, make a new event_id for the merged event else: # Find all event_id keys involved in duplicated events. These # keys will be merged to become a new entry in "event_id" event_id_keys = list(event_id.keys()) event_id_vals = list(event_id.values()) new_key_comps = [event_id_keys[event_id_vals.index(value)] for value in ev_vals] # Check if we already have an entry for merged keys of duplicate # events ... if yes, reuse it for key in event_id: if set(key.split('/')) == set(new_key_comps): new_event_val = event_id[key] break # Else, find an unused value for the new key and make an entry into # the event_id dict else: ev_vals = np.unique( np.concatenate((list(event_id.values()), events[:, 1:].flatten()), axis=0)) if ev_vals[0] > 1: new_event_val = 1 else: diffs = np.diff(ev_vals) idx = np.where(diffs > 1)[0] idx = -1 if len(idx) == 0 else idx[0] new_event_val = ev_vals[idx] + 1 new_event_id_key = '/'.join(sorted(new_key_comps)) event_id[new_event_id_key] = int(new_event_val) # Replace duplicate event times with merged event and remember which # duplicate indices to delete later new_events[idxs[0], 1] = new_prior new_events[idxs[0], 2] = new_event_val event_idxs_to_delete.extend(idxs[1:]) # Delete duplicate event idxs new_events = np.delete(new_events, event_idxs_to_delete, 0) new_selection = np.delete(selection, event_idxs_to_delete, 0) return new_events, event_id, new_selection def _handle_event_repeated(events, event_id, event_repeated, selection, drop_log): """Handle repeated events. Note that drop_log will be modified inplace """ assert len(events) == len(selection) selection = np.asarray(selection) unique_events, u_ev_idxs = np.unique(events[:, 0], return_index=True) # Return early if no duplicates if len(unique_events) == len(events): return events, event_id, selection, drop_log # Else, we have duplicates. Triage ... _check_option('event_repeated', event_repeated, ['error', 'drop', 'merge']) drop_log = list(drop_log) if event_repeated == 'error': raise RuntimeError('Event time samples were not unique. Consider ' 'setting the `event_repeated` parameter."') elif event_repeated == 'drop': logger.info('Multiple event values for single event times found. ' 'Keeping the first occurrence and dropping all others.') new_events = events[u_ev_idxs] new_selection = selection[u_ev_idxs] drop_ev_idxs = np.setdiff1d(selection, new_selection) for idx in drop_ev_idxs: drop_log[idx] = drop_log[idx] + ('DROP DUPLICATE',) selection = new_selection elif event_repeated == 'merge': logger.info('Multiple event values for single event times found. ' 'Creating new event value to reflect simultaneous events.') new_events, event_id, new_selection = \ _merge_events(events, event_id, selection) drop_ev_idxs = np.setdiff1d(selection, new_selection) for idx in drop_ev_idxs: drop_log[idx] = drop_log[idx] + ('MERGE DUPLICATE',) selection = new_selection drop_log = tuple(drop_log) # Remove obsolete kv-pairs from event_id after handling keys = new_events[:, 1:].flatten() event_id = {k: v for k, v in event_id.items() if v in keys} return new_events, event_id, selection, drop_log @fill_doc class BaseEpochs(ProjMixin, ContainsMixin, UpdateChannelsMixin, ShiftTimeMixin, SetChannelsMixin, InterpolationMixin, FilterMixin, TimeMixin, SizeMixin, GetEpochsMixin, EpochAnnotationsMixin, _VerboseDep): """Abstract base class for `~mne.Epochs`-type classes. .. warning:: This class provides basic functionality and should never be instantiated directly. Parameters ---------- %(info_not_none)s data : ndarray | None If ``None``, data will be read from the Raw object. If ndarray, must be of shape (n_epochs, n_channels, n_times). %(events_epochs)s %(event_id)s %(epochs_tmin_tmax)s %(baseline_epochs)s Defaults to ``(None, 0)``, i.e. beginning of the the data until time point zero. %(epochs_raw)s %(picks_all)s %(reject_epochs)s %(flat)s %(decim)s %(epochs_reject_tmin_tmax)s %(epochs_detrend)s %(proj_epochs)s %(epochs_on_missing)s preload_at_end : bool %(epochs_preload)s selection : iterable | None Iterable of indices of selected epochs. If ``None``, will be automatically generated, corresponding to all non-zero events. drop_log : tuple | None Tuple of tuple of strings indicating which epochs have been marked to be ignored. filename : str | None The filename (if the epochs are read from disk). %(epochs_metadata)s %(epochs_event_repeated)s %(verbose)s raw_sfreq : float The original Raw object sampling rate. If None, then it is set to ``info['sfreq']``. annotations : instance of mne.Annotations | None Annotations to set. Notes ----- The ``BaseEpochs`` class is public to allow for stable type-checking in user code (i.e., ``isinstance(my_epochs, BaseEpochs)``) but should not be used as a constructor for Epochs objects (use instead :class:`mne.Epochs`). """ @verbose def __init__(self, info, data, events, event_id=None, tmin=-0.2, tmax=0.5, baseline=(None, 0), raw=None, picks=None, reject=None, flat=None, decim=1, reject_tmin=None, reject_tmax=None, detrend=None, proj=True, on_missing='raise', preload_at_end=False, selection=None, drop_log=None, filename=None, metadata=None, event_repeated='error', *, verbose=None, raw_sfreq=None, annotations=None): # noqa: D102 if events is not None: # RtEpochs can have events=None events = _ensure_events(events) events_max = events.max() if events_max > INT32_MAX: raise ValueError( f'events array values must not exceed {INT32_MAX}, ' f'got {events_max}') event_id = _check_event_id(event_id, events) self.event_id = event_id del event_id if events is not None: # RtEpochs can have events=None for key, val in self.event_id.items(): if val not in events[:, 2]: msg = ('No matching events found for %s ' '(event id %i)' % (key, val)) _on_missing(on_missing, msg) # ensure metadata matches original events size self.selection = np.arange(len(events)) self.events = events # same as self.metadata = metadata, but suppress log in favor # of logging below (after setting self.selection) GetEpochsMixin.metadata.fset(self, metadata, verbose=False) del events values = list(self.event_id.values()) selected = np.where(np.in1d(self.events[:, 2], values))[0] if selection is None: selection = selected else: selection = np.array(selection, int) if selection.shape != (len(selected),): raise ValueError('selection must be shape %s got shape %s' % (selected.shape, selection.shape)) self.selection = selection if drop_log is None: self.drop_log = tuple( () if k in self.selection else ('IGNORED',) for k in range(max(len(self.events), max(self.selection) + 1))) else: self.drop_log = drop_log self.events = self.events[selected] self.events, self.event_id, self.selection, self.drop_log = \ _handle_event_repeated( self.events, self.event_id, event_repeated, self.selection, self.drop_log) # then subselect sub = np.where(np.in1d(selection, self.selection))[0] if isinstance(metadata, list): metadata = [metadata[s] for s in sub] elif metadata is not None: metadata = metadata.iloc[sub] # Remove temporarily set metadata from above, and set # again to get the correct log ("adding metadata", instead of # "replacing existing metadata") GetEpochsMixin.metadata.fset(self, None, verbose=False) self.metadata = metadata del metadata n_events = len(self.events) if n_events > 1: if np.diff(self.events.astype(np.int64)[:, 0]).min() <= 0: warn('The events passed to the Epochs constructor are not ' 'chronologically ordered.', RuntimeWarning) if n_events > 0: logger.info('%d matching events found' % n_events) else: raise ValueError('No desired events found.') else: self.drop_log = tuple() self.selection = np.array([], int) self.metadata = metadata # do not set self.events here, let subclass do it if (detrend not in [None, 0, 1]) or isinstance(detrend, bool): raise ValueError('detrend must be None, 0, or 1') self.detrend = detrend self._raw = raw info._check_consistency() self.picks = _picks_to_idx(info, picks, none='all', exclude=(), allow_empty=False) self.info = pick_info(info, self.picks) del info self._current = 0 if data is None: self.preload = False self._data = None self._do_baseline = True else: assert decim == 1 if data.ndim != 3 or data.shape[2] != \ round((tmax - tmin) * self.info['sfreq']) + 1: raise RuntimeError('bad data shape') if data.shape[0] != len(self.events): raise ValueError( 'The number of epochs and the number of events must match') self.preload = True self._data = data self._do_baseline = False self._offset = None if tmin > tmax: raise ValueError('tmin has to be less than or equal to tmax') # Handle times sfreq = float(self.info['sfreq']) start_idx = int(round(tmin * sfreq)) self._raw_times = np.arange(start_idx, int(round(tmax * sfreq)) + 1) / sfreq self._set_times(self._raw_times) # check reject_tmin and reject_tmax if reject_tmin is not None: if (np.isclose(reject_tmin, tmin)): # adjust for potential small deviations due to sampling freq reject_tmin = self.tmin elif reject_tmin < tmin: raise ValueError(f'reject_tmin needs to be None or >= tmin ' f'(got {reject_tmin})') if reject_tmax is not None: if (np.isclose(reject_tmax, tmax)): # adjust for potential small deviations due to sampling freq reject_tmax = self.tmax elif reject_tmax > tmax: raise ValueError(f'reject_tmax needs to be None or <= tmax ' f'(got {reject_tmax})') if (reject_tmin is not None) and (reject_tmax is not None): if reject_tmin >= reject_tmax: raise ValueError(f'reject_tmin ({reject_tmin}) needs to be ' f' < reject_tmax ({reject_tmax})') self.reject_tmin = reject_tmin self.reject_tmax = reject_tmax # decimation self._decim = 1 self.decimate(decim) # baseline correction: replace `None` tuple elements with actual times self.baseline = _check_baseline(baseline, times=self.times, sfreq=self.info['sfreq']) if self.baseline is not None and self.baseline != baseline: logger.info(f'Setting baseline interval to ' f'[{self.baseline[0]}, {self.baseline[1]}] sec') logger.info(_log_rescale(self.baseline)) # setup epoch rejection self.reject = None self.flat = None self._reject_setup(reject, flat) # do the rest valid_proj = [True, 'delayed', False] if proj not in valid_proj: raise ValueError('"proj" must be one of %s, not %s' % (valid_proj, proj)) if proj == 'delayed': self._do_delayed_proj = True logger.info('Entering delayed SSP mode.') else: self._do_delayed_proj = False activate = False if self._do_delayed_proj else proj self._projector, self.info = setup_proj(self.info, False, activate=activate) if preload_at_end: assert self._data is None assert self.preload is False self.load_data() # this will do the projection elif proj is True and self._projector is not None and data is not None: # let's make sure we project if data was provided and proj # requested # we could do this with np.einsum, but iteration should be # more memory safe in most instances for ii, epoch in enumerate(self._data): self._data[ii] = np.dot(self._projector, epoch) self._filename = str(filename) if filename is not None else filename if raw_sfreq is None: raw_sfreq = self.info['sfreq'] self._raw_sfreq = raw_sfreq self._check_consistency() self.set_annotations(annotations) def _check_consistency(self): """Check invariants of epochs object.""" if hasattr(self, 'events'): assert len(self.selection) == len(self.events) assert len(self.drop_log) >= len(self.events) assert len(self.selection) == sum( (len(dl) == 0 for dl in self.drop_log)) assert hasattr(self, '_times_readonly') assert not self.times.flags['WRITEABLE'] assert isinstance(self.drop_log, tuple) assert all(isinstance(log, tuple) for log in self.drop_log) assert all(isinstance(s, str) for log in self.drop_log for s in log) def reset_drop_log_selection(self): """Reset the drop_log and selection entries. This method will simplify ``self.drop_log`` and ``self.selection`` so that they are meaningless (tuple of empty tuples and increasing integers, respectively). This can be useful when concatenating many Epochs instances, as ``drop_log`` can accumulate many entries which can become problematic when saving. """ self.selection = np.arange(len(self.events)) self.drop_log = (tuple(),) * len(self.events) self._check_consistency() def load_data(self): """Load the data if not already preloaded. Returns ------- epochs : instance of Epochs The epochs object. Notes ----- This function operates in-place. .. versionadded:: 0.10.0 """ if self.preload: return self self._data = self._get_data() self.preload = True self._do_baseline = False self._decim_slice = slice(None, None, None) self._decim = 1 self._raw_times = self.times assert self._data.shape[-1] == len(self.times) self._raw = None # shouldn't need it anymore return self @verbose def decimate(self, decim, offset=0, verbose=None): """Decimate the epochs. Parameters ---------- %(decim)s %(decim_offset)s %(verbose)s Returns ------- epochs : instance of Epochs The decimated Epochs object. See Also -------- mne.Evoked.decimate mne.Epochs.resample mne.io.Raw.resample Notes ----- %(decim_notes)s If ``decim`` is 1, this method does not copy the underlying data. .. versionadded:: 0.10.0 References ---------- .. footbibliography:: """ decim, offset, new_sfreq = _check_decim(self.info, decim, offset) start_idx = int(round(-self._raw_times[0] * (self.info['sfreq'] * self._decim))) self._decim *= decim i_start = start_idx % self._decim + offset decim_slice = slice(i_start, None, self._decim) with self.info._unlock(): self.info['sfreq'] = new_sfreq if self.preload: if decim != 1: self._data = self._data[:, :, decim_slice].copy() self._raw_times = self._raw_times[decim_slice].copy() else: self._data = np.ascontiguousarray(self._data) self._decim_slice = slice(None) self._decim = 1 else: self._decim_slice = decim_slice self._set_times(self._raw_times[self._decim_slice]) return self @verbose def apply_baseline(self, baseline=(None, 0), *, verbose=None): """Baseline correct epochs. Parameters ---------- %(baseline_epochs)s Defaults to ``(None, 0)``, i.e. beginning of the the data until time point zero. %(verbose)s Returns ------- epochs : instance of Epochs The baseline-corrected Epochs object. Notes ----- Baseline correction can be done multiple times, but can never be reverted once the data has been loaded. .. versionadded:: 0.10.0 """ baseline = _check_baseline(baseline, times=self.times, sfreq=self.info['sfreq']) if self.preload: if self.baseline is not None and baseline is None: raise RuntimeError('You cannot remove baseline correction ' 'from preloaded data once it has been ' 'applied.') self._do_baseline = True picks = self._detrend_picks rescale(self._data, self.times, baseline, copy=False, picks=picks) self._do_baseline = False else: # logging happens in "rescale" in "if" branch logger.info(_log_rescale(baseline)) # For EpochsArray and Epochs, this is already True: # assert self._do_baseline is True # ... but for EpochsFIF it's not, so let's set it explicitly self._do_baseline = True self.baseline = baseline return self def _reject_setup(self, reject, flat): """Set self._reject_time and self._channel_type_idx.""" idx = channel_indices_by_type(self.info) reject = deepcopy(reject) if reject is not None else dict() flat = deepcopy(flat) if flat is not None else dict() for rej, kind in zip((reject, flat), ('reject', 'flat')): if not isinstance(rej, dict): raise TypeError('reject and flat must be dict or None, not %s' % type(rej)) bads = set(rej.keys()) - set(idx.keys()) if len(bads) > 0: raise KeyError('Unknown channel types found in %s: %s' % (kind, bads)) for key in idx.keys(): # don't throw an error if rejection/flat would do nothing if len(idx[key]) == 0 and (np.isfinite(reject.get(key, np.inf)) or flat.get(key, -1) >= 0): # This is where we could eventually add e.g. # self.allow_missing_reject_keys check to allow users to # provide keys that don't exist in data raise ValueError("No %s channel found. Cannot reject based on " "%s." % (key.upper(), key.upper())) # check for invalid values for rej, kind in zip((reject, flat), ('Rejection', 'Flat')): for key, val in rej.items(): if val is None or val < 0: raise ValueError('%s value must be a number >= 0, not "%s"' % (kind, val)) # now check to see if our rejection and flat are getting more # restrictive old_reject = self.reject if self.reject is not None else dict() old_flat = self.flat if self.flat is not None else dict() bad_msg = ('{kind}["{key}"] == {new} {op} {old} (old value), new ' '{kind} values must be at least as stringent as ' 'previous ones') # copy thresholds for channel types that were used previously, but not # passed this time for key in set(old_reject) - set(reject): reject[key] = old_reject[key] # make sure new thresholds are at least as stringent as the old ones for key in reject: if key in old_reject and reject[key] > old_reject[key]: raise ValueError( bad_msg.format(kind='reject', key=key, new=reject[key], old=old_reject[key], op='>')) # same for flat thresholds for key in set(old_flat) - set(flat): flat[key] = old_flat[key] for key in flat: if key in old_flat and flat[key] < old_flat[key]: raise ValueError( bad_msg.format(kind='flat', key=key, new=flat[key], old=old_flat[key], op='<')) # after validation, set parameters self._bad_dropped = False self._channel_type_idx = idx self.reject = reject if len(reject) > 0 else None self.flat = flat if len(flat) > 0 else None if (self.reject_tmin is None) and (self.reject_tmax is None): self._reject_time = None else: if self.reject_tmin is None: reject_imin = None else: idxs = np.nonzero(self.times >= self.reject_tmin)[0] reject_imin = idxs[0] if self.reject_tmax is None: reject_imax = None else: idxs = np.nonzero(self.times <= self.reject_tmax)[0] reject_imax = idxs[-1] self._reject_time = slice(reject_imin, reject_imax) @verbose # verbose is used by mne-realtime def _is_good_epoch(self, data, verbose=None): """Determine if epoch is good.""" if isinstance(data, str): return False, (data,) if data is None: return False, ('NO_DATA',) n_times = len(self.times) if data.shape[1] < n_times: # epoch is too short ie at the end of the data return False, ('TOO_SHORT',) if self.reject is None and self.flat is None: return True, None else: if self._reject_time is not None: data = data[:, self._reject_time] return _is_good(data, self.ch_names, self._channel_type_idx, self.reject, self.flat, full_report=True, ignore_chs=self.info['bads']) @verbose def _detrend_offset_decim(self, epoch, picks, verbose=None): """Aux Function: detrend, baseline correct, offset, decim. Note: operates inplace """ if (epoch is None) or isinstance(epoch, str): return epoch # Detrend if self.detrend is not None: # We explicitly detrend just data channels (not EMG, ECG, EOG which # are processed by baseline correction) use_picks = _pick_data_channels(self.info, exclude=()) epoch[use_picks] = detrend(epoch[use_picks], self.detrend, axis=1) # Baseline correct if self._do_baseline: rescale( epoch, self._raw_times, self.baseline, picks=picks, copy=False, verbose=False) # Decimate if necessary (i.e., epoch not preloaded) epoch = epoch[:, self._decim_slice] # handle offset if self._offset is not None: epoch += self._offset return epoch def iter_evoked(self, copy=False): """Iterate over epochs as a sequence of Evoked objects. The Evoked objects yielded will each contain a single epoch (i.e., no averaging is performed). This method resets the object iteration state to the first epoch. Parameters ---------- copy : bool If False copies of data and measurement info will be omitted to save time. """ self.__iter__() while True: try: out = self.__next__(True) except StopIteration: break data, event_id = out tmin = self.times[0] info = self.info if copy: info = deepcopy(self.info) data = data.copy() yield EvokedArray(data, info, tmin, comment=str(event_id)) def subtract_evoked(self, evoked=None): """Subtract an evoked response from each epoch. Can be used to exclude the evoked response when analyzing induced activity, see e.g. [1]_. Parameters ---------- evoked : instance of Evoked | None The evoked response to subtract. If None, the evoked response is computed from Epochs itself. Returns ------- self : instance of Epochs The modified instance (instance is also modified inplace). References ---------- .. [1] David et al. "Mechanisms of evoked and induced responses in MEG/EEG", NeuroImage, vol. 31, no. 4, pp. 1580-1591, July 2006. """ logger.info('Subtracting Evoked from Epochs') if evoked is None: picks = _pick_data_channels(self.info, exclude=[]) evoked = self.average(picks) # find the indices of the channels to use picks = pick_channels(evoked.ch_names, include=self.ch_names) # make sure the omitted channels are not data channels if len(picks) < len(self.ch_names): sel_ch = [evoked.ch_names[ii] for ii in picks] diff_ch = list(set(self.ch_names).difference(sel_ch)) diff_idx = [self.ch_names.index(ch) for ch in diff_ch] diff_types = [channel_type(self.info, idx) for idx in diff_idx] bad_idx = [diff_types.index(t) for t in diff_types if t in _DATA_CH_TYPES_SPLIT] if len(bad_idx) > 0: bad_str = ', '.join([diff_ch[ii] for ii in bad_idx]) raise ValueError('The following data channels are missing ' 'in the evoked response: %s' % bad_str) logger.info(' The following channels are not included in the ' 'subtraction: %s' % ', '.join(diff_ch)) # make sure the times match if (len(self.times) != len(evoked.times) or np.max(np.abs(self.times - evoked.times)) >= 1e-7): raise ValueError('Epochs and Evoked object do not contain ' 'the same time points.') # handle SSPs if not self.proj and evoked.proj: warn('Evoked has SSP applied while Epochs has not.') if self.proj and not evoked.proj: evoked = evoked.copy().apply_proj() # find the indices of the channels to use in Epochs ep_picks = [self.ch_names.index(evoked.ch_names[ii]) for ii in picks] # do the subtraction if self.preload: self._data[:, ep_picks, :] -= evoked.data[picks][None, :, :] else: if self._offset is None: self._offset = np.zeros((len(self.ch_names), len(self.times)), dtype=np.float64) self._offset[ep_picks] -= evoked.data[picks] logger.info('[done]') return self @fill_doc def average(self, picks=None, method="mean", by_event_type=False): """Compute an average over epochs. Parameters ---------- %(picks_all_data)s method : str | callable How to combine the data. If "mean"/"median", the mean/median are returned. Otherwise, must be a callable which, when passed an array of shape (n_epochs, n_channels, n_time) returns an array of shape (n_channels, n_time). Note that due to file type limitations, the kind for all these will be "average". %(by_event_type)s Returns ------- %(by_event_type_returns_average)s Notes ----- Computes an average of all epochs in the instance, even if they correspond to different conditions. To average by condition, do ``epochs[condition].average()`` for each condition separately. When picks is None and epochs contain only ICA channels, no channels are selected, resulting in an error. This is because ICA channels are not considered data channels (they are of misc type) and only data channels are selected when picks is None. The ``method`` parameter allows e.g. robust averaging. For example, one could do: >>> from scipy.stats import trim_mean # doctest:+SKIP >>> trim = lambda x: trim_mean(x, 0.1, axis=0) # doctest:+SKIP >>> epochs.average(method=trim) # doctest:+SKIP This would compute the trimmed mean. """ if by_event_type: evokeds = list() for event_type in self.event_id.keys(): ev = self[event_type]._compute_aggregate(picks=picks, mode=method) ev.comment = event_type evokeds.append(ev) else: evokeds = self._compute_aggregate(picks=picks, mode=method) return evokeds @fill_doc def standard_error(self, picks=None, by_event_type=False): """Compute standard error over epochs. Parameters ---------- %(picks_all_data)s %(by_event_type)s Returns ------- %(by_event_type_returns_stderr)s """ return self.average(picks=picks, method="std", by_event_type=by_event_type) def _compute_aggregate(self, picks, mode='mean'): """Compute the mean, median, or std over epochs and return Evoked.""" # if instance contains ICA channels they won't be included unless picks # is specified if picks is None: check_ICA = [x.startswith('ICA') for x in self.ch_names] if np.all(check_ICA): raise TypeError('picks must be specified (i.e. not None) for ' 'ICA channel data') elif np.any(check_ICA): warn('ICA channels will not be included unless explicitly ' 'selected in picks') n_channels = len(self.ch_names) n_times = len(self.times) if self.preload: n_events = len(self.events) fun = _check_combine(mode, valid=('mean', 'median', 'std')) data = fun(self._data) assert len(self.events) == len(self._data) if data.shape != self._data.shape[1:]: raise RuntimeError( 'You passed a function that resulted n data of shape {}, ' 'but it should be {}.'.format( data.shape, self._data.shape[1:])) else: if mode not in {"mean", "std"}: raise ValueError("If data are not preloaded, can only compute " "mean or standard deviation.") data = np.zeros((n_channels, n_times)) n_events = 0 for e in self: if np.iscomplexobj(e): data = data.astype(np.complex128) data += e n_events += 1 if n_events > 0: data /= n_events else: data.fill(np.nan) # convert to stderr if requested, could do in one pass but do in # two (slower) in case there are large numbers if mode == "std": data_mean = data.copy() data.fill(0.) for e in self: data += (e - data_mean) ** 2 data = np.sqrt(data / n_events) if mode == "std": kind = 'standard_error' data /= np.sqrt(n_events) else: kind = "average" return self._evoked_from_epoch_data(data, self.info, picks, n_events, kind, self._name) @property def _name(self): """Give a nice string representation based on event ids.""" if len(self.event_id) == 1: comment = next(iter(self.event_id.keys())) else: count = Counter(self.events[:, 2]) comments = list() for key, value in self.event_id.items(): comments.append('%.2f × %s' % ( float(count[value]) / len(self.events), key)) comment = ' + '.join(comments) return comment def _evoked_from_epoch_data(self, data, info, picks, n_events, kind, comment): """Create an evoked object from epoch data.""" info = deepcopy(info) # don't apply baseline correction; we'll set evoked.baseline manually evoked = EvokedArray(data, info, tmin=self.times[0], comment=comment, nave=n_events, kind=kind, baseline=None) evoked.baseline = self.baseline # the above constructor doesn't recreate the times object precisely # due to numerical precision issues evoked.times = self.times.copy() # pick channels picks = _picks_to_idx(self.info, picks, 'data_or_ica', ()) ch_names = [evoked.ch_names[p] for p in picks] evoked.pick_channels(ch_names) if len(evoked.info['ch_names']) == 0: raise ValueError('No data channel found when averaging.') if evoked.nave < 1: warn('evoked object is empty (based on less than 1 epoch)') return evoked @property def ch_names(self): """Channel names.""" return self.info['ch_names'] @copy_function_doc_to_method_doc(plot_epochs) def plot(self, picks=None, scalings=None, n_epochs=20, n_channels=20, title=None, events=None, event_color=None, order=None, show=True, block=False, decim='auto', noise_cov=None, butterfly=False, show_scrollbars=True, show_scalebars=True, epoch_colors=None, event_id=None, group_by='type'): return plot_epochs(self, picks=picks, scalings=scalings, n_epochs=n_epochs, n_channels=n_channels, title=title, events=events, event_color=event_color, order=order, show=show, block=block, decim=decim, noise_cov=noise_cov, butterfly=butterfly, show_scrollbars=show_scrollbars, show_scalebars=show_scalebars, epoch_colors=epoch_colors, event_id=event_id, group_by=group_by) @copy_function_doc_to_method_doc(plot_epochs_psd) def plot_psd(self, fmin=0, fmax=np.inf, tmin=None, tmax=None, proj=False, bandwidth=None, adaptive=False, low_bias=True, normalization='length', picks=None, ax=None, color='black', xscale='linear', area_mode='std', area_alpha=0.33, dB=True, estimate='auto', show=True, n_jobs=1, average=False, line_alpha=None, spatial_colors=True, sphere=None, exclude='bads', verbose=None): return plot_epochs_psd(self, fmin=fmin, fmax=fmax, tmin=tmin, tmax=tmax, proj=proj, bandwidth=bandwidth, adaptive=adaptive, low_bias=low_bias, normalization=normalization, picks=picks, ax=ax, color=color, xscale=xscale, area_mode=area_mode, area_alpha=area_alpha, dB=dB, estimate=estimate, show=show, n_jobs=n_jobs, average=average, line_alpha=line_alpha, spatial_colors=spatial_colors, sphere=sphere, exclude=exclude, verbose=verbose) @copy_function_doc_to_method_doc(plot_epochs_psd_topomap) def plot_psd_topomap(self, bands=None, tmin=None, tmax=None, proj=False, bandwidth=None, adaptive=False, low_bias=True, normalization='length', ch_type=None, cmap=None, agg_fun=None, dB=True, n_jobs=1, normalize=False, cbar_fmt='auto', outlines='head', axes=None, show=True, sphere=None, vlim=(None, None), verbose=None): return plot_epochs_psd_topomap( self, bands=bands, tmin=tmin, tmax=tmax, proj=proj, bandwidth=bandwidth, adaptive=adaptive, low_bias=low_bias, normalization=normalization, ch_type=ch_type, cmap=cmap, agg_fun=agg_fun, dB=dB, n_jobs=n_jobs, normalize=normalize, cbar_fmt=cbar_fmt, outlines=outlines, axes=axes, show=show, sphere=sphere, vlim=vlim, verbose=verbose) @copy_function_doc_to_method_doc(plot_topo_image_epochs) def plot_topo_image(self, layout=None, sigma=0., vmin=None, vmax=None, colorbar=None, order=None, cmap='RdBu_r', layout_scale=.95, title=None, scalings=None, border='none', fig_facecolor='k', fig_background=None, font_color='w', show=True): return plot_topo_image_epochs( self, layout=layout, sigma=sigma, vmin=vmin, vmax=vmax, colorbar=colorbar, order=order, cmap=cmap, layout_scale=layout_scale, title=title, scalings=scalings, border=border, fig_facecolor=fig_facecolor, fig_background=fig_background, font_color=font_color, show=show) @verbose def drop_bad(self, reject='existing', flat='existing', verbose=None): """Drop bad epochs without retaining the epochs data. Should be used before slicing operations. .. warning:: This operation is slow since all epochs have to be read from disk. To avoid reading epochs from disk multiple times, use :meth:`mne.Epochs.load_data()`. .. note:: To constrain the time period used for estimation of signal quality, set ``epochs.reject_tmin`` and ``epochs.reject_tmax``, respectively. Parameters ---------- %(reject_drop_bad)s %(flat_drop_bad)s %(verbose)s Returns ------- epochs : instance of Epochs The epochs with bad epochs dropped. Operates in-place. Notes ----- Dropping bad epochs can be done multiple times with different ``reject`` and ``flat`` parameters. However, once an epoch is dropped, it is dropped forever, so if more lenient thresholds may subsequently be applied, `epochs.copy <mne.Epochs.copy>` should be used. """ if reject == 'existing': if flat == 'existing' and self._bad_dropped: return reject = self.reject if flat == 'existing': flat = self.flat if any(isinstance(rej, str) and rej != 'existing' for rej in (reject, flat)): raise ValueError('reject and flat, if strings, must be "existing"') self._reject_setup(reject, flat) self._get_data(out=False, verbose=verbose) return self def drop_log_stats(self, ignore=('IGNORED',)): """Compute the channel stats based on a drop_log from Epochs. Parameters ---------- ignore : list The drop reasons to ignore. Returns ------- perc : float Total percentage of epochs dropped. See Also -------- plot_drop_log """ return _drop_log_stats(self.drop_log, ignore) @copy_function_doc_to_method_doc(plot_drop_log) def plot_drop_log(self, threshold=0, n_max_plot=20, subject=None, color=(0.9, 0.9, 0.9), width=0.8, ignore=('IGNORED',), show=True): if not self._bad_dropped: raise ValueError("You cannot use plot_drop_log since bad " "epochs have not yet been dropped. " "Use epochs.drop_bad().") return plot_drop_log(self.drop_log, threshold, n_max_plot, subject, color=color, width=width, ignore=ignore, show=show) @copy_function_doc_to_method_doc(plot_epochs_image) def plot_image(self, picks=None, sigma=0., vmin=None, vmax=None, colorbar=True, order=None, show=True, units=None, scalings=None, cmap=None, fig=None, axes=None, overlay_times=None, combine=None, group_by=None, evoked=True, ts_args=None, title=None, clear=False): return plot_epochs_image(self, picks=picks, sigma=sigma, vmin=vmin, vmax=vmax, colorbar=colorbar, order=order, show=show, units=units, scalings=scalings, cmap=cmap, fig=fig, axes=axes, overlay_times=overlay_times, combine=combine, group_by=group_by, evoked=evoked, ts_args=ts_args, title=title, clear=clear) @verbose def drop(self, indices, reason='USER', verbose=None): """Drop epochs based on indices or boolean mask. .. note:: The indices refer to the current set of undropped epochs rather than the complete set of dropped and undropped epochs. They are therefore not necessarily consistent with any external indices (e.g., behavioral logs). To drop epochs based on external criteria, do not use the ``preload=True`` flag when constructing an Epochs object, and call this method before calling the :meth:`mne.Epochs.drop_bad` or :meth:`mne.Epochs.load_data` methods. Parameters ---------- indices : array of int or bool Set epochs to remove by specifying indices to remove or a boolean mask to apply (where True values get removed). Events are correspondingly modified. reason : str Reason for dropping the epochs ('ECG', 'timeout', 'blink' etc). Default: 'USER'. %(verbose)s Returns ------- epochs : instance of Epochs The epochs with indices dropped. Operates in-place. """ indices = np.atleast_1d(indices) if indices.ndim > 1: raise ValueError("indices must be a scalar or a 1-d array") if indices.dtype == bool: indices = np.where(indices)[0] try_idx = np.where(indices < 0, indices + len(self.events), indices) out_of_bounds = (try_idx < 0) | (try_idx >= len(self.events)) if out_of_bounds.any(): first = indices[out_of_bounds][0] raise IndexError("Epoch index %d is out of bounds" % first) keep = np.setdiff1d(np.arange(len(self.events)), try_idx) self._getitem(keep, reason, copy=False, drop_event_id=False) count = len(try_idx) logger.info('Dropped %d epoch%s: %s' % (count, _pl(count), ', '.join(map(str, np.sort(try_idx))))) return self def _get_epoch_from_raw(self, idx, verbose=None): """Get a given epoch from disk.""" raise NotImplementedError def _project_epoch(self, epoch): """Process a raw epoch based on the delayed param.""" # whenever requested, the first epoch is being projected. if (epoch is None) or isinstance(epoch, str): # can happen if t < 0 or reject based on annotations return epoch proj = self._do_delayed_proj or self.proj if self._projector is not None and proj is True: epoch = np.dot(self._projector, epoch) return epoch @verbose def _get_data(self, out=True, picks=None, item=None, *, units=None, tmin=None, tmax=None, verbose=None): """Load all data, dropping bad epochs along the way. Parameters ---------- out : bool Return the data. Setting this to False is used to reject bad epochs without caching all the data, which saves memory. %(picks_all)s item : slice | array-like | str | list | None See docstring of get_data method. %(units)s tmin : int | float | None Start time of data to get in seconds. tmax : int | float | None End time of data to get in seconds. %(verbose)s """ start, stop = self._handle_tmin_tmax(tmin, tmax) if item is None: item = slice(None) elif not self._bad_dropped: raise ValueError( 'item must be None in epochs.get_data() unless bads have been ' 'dropped. Consider using epochs.drop_bad().') select = self._item_to_select(item) # indices or slice use_idx = np.arange(len(self.events))[select] n_events = len(use_idx) # in case there are no good events if self.preload: # we will store our result in our existing array data = self._data else: # we start out with an empty array, allocate only if necessary data = np.empty((0, len(self.info['ch_names']), len(self.times))) msg = (f'for {n_events} events and {len(self._raw_times)} ' 'original time points') if self._decim > 1: msg += ' (prior to decimation)' if getattr(self._raw, "preload", False): logger.info(f'Using data from preloaded Raw {msg} ...') else: logger.info(f'Loading data {msg} ...') orig_picks = picks if orig_picks is None: picks = _picks_to_idx(self.info, picks, "all", exclude=()) else: picks = _picks_to_idx(self.info, picks) # handle units param only if we are going to return data (out==True) if (units is not None) and out: ch_factors = _get_ch_factors(self, units, picks) if self._bad_dropped: if not out: return if self.preload: data = data[select] if orig_picks is not None: data = data[:, picks] if units is not None: data *= ch_factors[:, np.newaxis] if start != 0 or stop != self.times.size: data = data[..., start:stop] return data # we need to load from disk, drop, and return data detrend_picks = self._detrend_picks for ii, idx in enumerate(use_idx): # faster to pre-allocate memory here epoch_noproj = self._get_epoch_from_raw(idx) epoch_noproj = self._detrend_offset_decim( epoch_noproj, detrend_picks) if self._do_delayed_proj: epoch_out = epoch_noproj else: epoch_out = self._project_epoch(epoch_noproj) if ii == 0: data = np.empty((n_events, len(self.ch_names), len(self.times)), dtype=epoch_out.dtype) data[ii] = epoch_out else: # bads need to be dropped, this might occur after a preload # e.g., when calling drop_bad w/new params good_idx = [] n_out = 0 drop_log = list(self.drop_log) assert n_events == len(self.selection) if not self.preload: detrend_picks = self._detrend_picks for idx, sel in enumerate(self.selection): if self.preload: # from memory if self._do_delayed_proj: epoch_noproj = self._data[idx] epoch = self._project_epoch(epoch_noproj) else: epoch_noproj = None epoch = self._data[idx] else: # from disk epoch_noproj = self._get_epoch_from_raw(idx) epoch_noproj = self._detrend_offset_decim( epoch_noproj, detrend_picks) epoch = self._project_epoch(epoch_noproj) epoch_out = epoch_noproj if self._do_delayed_proj else epoch is_good, bad_tuple = self._is_good_epoch( epoch, verbose=verbose) if not is_good: assert isinstance(bad_tuple, tuple) assert all(isinstance(x, str) for x in bad_tuple) drop_log[sel] = drop_log[sel] + bad_tuple continue good_idx.append(idx) # store the epoch if there is a reason to (output or update) if out or self.preload: # faster to pre-allocate, then trim as necessary if n_out == 0 and not self.preload: data = np.empty((n_events, epoch_out.shape[0], epoch_out.shape[1]), dtype=epoch_out.dtype, order='C') data[n_out] = epoch_out n_out += 1 self.drop_log = tuple(drop_log) del drop_log self._bad_dropped = True logger.info("%d bad epochs dropped" % (n_events - len(good_idx))) # adjust the data size if there is a reason to (output or update) if out or self.preload: if data.flags['OWNDATA'] and data.flags['C_CONTIGUOUS']: data.resize((n_out,) + data.shape[1:], refcheck=False) else: data = data[:n_out] if self.preload: self._data = data # Now update our properties (excepd data, which is already fixed) self._getitem(good_idx, None, copy=False, drop_event_id=False, select_data=False) if out: if orig_picks is not None: data = data[:, picks] if units is not None: data *= ch_factors[:, np.newaxis] if start != 0 or stop != self.times.size: data = data[..., start:stop] return data else: return None @property def _detrend_picks(self): if self._do_baseline: return _pick_data_channels( self.info, with_ref_meg=True, with_aux=True, exclude=()) else: return [] @fill_doc def get_data(self, picks=None, item=None, units=None, tmin=None, tmax=None): """Get all epochs as a 3D array. Parameters ---------- %(picks_all)s item : slice | array-like | str | list | None The items to get. See :meth:`mne.Epochs.__getitem__` for a description of valid options. This can be substantially faster for obtaining an ndarray than :meth:`~mne.Epochs.__getitem__` for repeated access on large Epochs objects. None (default) is an alias for ``slice(None)``. .. versionadded:: 0.20 %(units)s .. versionadded:: 0.24 tmin : int | float | None Start time of data to get in seconds. .. versionadded:: 0.24.0 tmax : int | float | None End time of data to get in seconds. .. versionadded:: 0.24.0 Returns ------- data : array of shape (n_epochs, n_channels, n_times) A view on epochs data. """ return self._get_data(picks=picks, item=item, units=units, tmin=tmin, tmax=tmax) @verbose def apply_function(self, fun, picks=None, dtype=None, n_jobs=1, channel_wise=True, verbose=None, **kwargs): """Apply a function to a subset of channels. %(applyfun_summary_epochs)s Parameters ---------- %(applyfun_fun)s %(picks_all_data_noref)s %(applyfun_dtype)s %(n_jobs)s %(applyfun_chwise_epo)s %(verbose)s %(kwarg_fun)s Returns ------- self : instance of Epochs The epochs object with transformed data. """ _check_preload(self, 'epochs.apply_function') picks = _picks_to_idx(self.info, picks, exclude=(), with_ref_meg=False) if not callable(fun): raise ValueError('fun needs to be a function') data_in = self._data if dtype is not None and dtype != self._data.dtype: self._data = self._data.astype(dtype) if channel_wise: if n_jobs == 1: _fun = partial(_check_fun, fun, **kwargs) # modify data inplace to save memory for idx in picks: self._data[:, idx, :] = np.apply_along_axis( _fun, -1, data_in[:, idx, :]) else: # use parallel function parallel, p_fun, _ = parallel_func(_check_fun, n_jobs) data_picks_new = parallel(p_fun( fun, data_in[:, p, :], **kwargs) for p in picks) for pp, p in enumerate(picks): self._data[:, p, :] = data_picks_new[pp] else: self._data = _check_fun(fun, data_in, **kwargs) return self @property def times(self): """Time vector in seconds.""" return self._times_readonly def _set_times(self, times): """Set self._times_readonly (and make it read only).""" # naming used to indicate that it shouldn't be # changed directly, but rather via this method self._times_readonly = times.copy() self._times_readonly.flags['WRITEABLE'] = False @property def tmin(self): """First time point.""" return self.times[0] @property def filename(self): """The filename.""" return self._filename @property def tmax(self): """Last time point.""" return self.times[-1] def __repr__(self): """Build string representation.""" s = ' %s events ' % len(self.events) s += '(all good)' if self._bad_dropped else '(good & bad)' s += ', %g - %g sec' % (self.tmin, self.tmax) s += ', baseline ' if self.baseline is None: s += 'off' else: s += f'{self.baseline[0]:g} – {self.baseline[1]:g} sec' if self.baseline != _check_baseline( self.baseline, times=self.times, sfreq=self.info['sfreq'], on_baseline_outside_data='adjust'): s += ' (baseline period was cropped after baseline correction)' s += ', ~%s' % (sizeof_fmt(self._size),) s += ', data%s loaded' % ('' if self.preload else ' not') s += ', with metadata' if self.metadata is not None else '' max_events = 10 counts = ['%r: %i' % (k, sum(self.events[:, 2] == v)) for k, v in list(self.event_id.items())[:max_events]] if len(self.event_id) > 0: s += ',' + '\n '.join([''] + counts) if len(self.event_id) > max_events: not_shown_events = len(self.event_id) - max_events s += f"\n and {not_shown_events} more events ..." class_name = self.__class__.__name__ class_name = 'Epochs' if class_name == 'BaseEpochs' else class_name return '<%s | %s>' % (class_name, s) def _repr_html_(self): from .html_templates import repr_templates_env if self.baseline is None: baseline = 'off' else: baseline = tuple([f'{b:.3f}' for b in self.baseline]) baseline = f'{baseline[0]} – {baseline[1]} sec' if isinstance(self.event_id, dict): event_strings = [] for k, v in sorted(self.event_id.items()): n_events = sum(self.events[:, 2] == v) event_strings.append(f'{k}: {n_events}') elif isinstance(self.event_id, list): event_strings = [] for k in self.event_id: n_events = sum(self.events[:, 2] == k) event_strings.append(f'{k}: {n_events}') elif isinstance(self.event_id, int): n_events = len(self.events[:, 2]) event_strings = [f'{self.event_id}: {n_events}'] else: event_strings = None t = repr_templates_env.get_template('epochs.html.jinja') t = t.render(epochs=self, baseline=baseline, events=event_strings) return t @verbose def crop(self, tmin=None, tmax=None, include_tmax=True, verbose=None): """Crop a time interval from the epochs. Parameters ---------- tmin : float | None Start time of selection in seconds. tmax : float | None End time of selection in seconds. %(include_tmax)s %(verbose)s Returns ------- epochs : instance of Epochs The cropped epochs object, modified in-place. Notes ----- %(notes_tmax_included_by_default)s """ # XXX this could be made to work on non-preloaded data... _check_preload(self, 'Modifying data of epochs') if tmin is None: tmin = self.tmin elif tmin < self.tmin: warn('tmin is not in epochs time interval. tmin is set to ' 'epochs.tmin') tmin = self.tmin if tmax is None: tmax = self.tmax elif tmax > self.tmax: warn('tmax is not in epochs time interval. tmax is set to ' 'epochs.tmax') tmax = self.tmax include_tmax = True tmask = _time_mask(self.times, tmin, tmax, sfreq=self.info['sfreq'], include_tmax=include_tmax) self._set_times(self.times[tmask]) self._raw_times = self._raw_times[tmask] self._data = self._data[:, :, tmask] # Adjust rejection period if self.reject_tmin is not None and self.reject_tmin < self.tmin: logger.info( f'reject_tmin is not in epochs time interval. ' f'Setting reject_tmin to epochs.tmin ({self.tmin} sec)') self.reject_tmin = self.tmin if self.reject_tmax is not None and self.reject_tmax > self.tmax: logger.info( f'reject_tmax is not in epochs time interval. ' f'Setting reject_tmax to epochs.tmax ({self.tmax} sec)') self.reject_tmax = self.tmax return self def copy(self): """Return copy of Epochs instance. Returns ------- epochs : instance of Epochs A copy of the object. """ return deepcopy(self) def __deepcopy__(self, memodict): """Make a deepcopy.""" cls = self.__class__ result = cls.__new__(cls) for k, v in self.__dict__.items(): # drop_log is immutable and _raw is private (and problematic to # deepcopy) if k in ('drop_log', '_raw', '_times_readonly'): memodict[id(v)] = v else: v = deepcopy(v, memodict) result.__dict__[k] = v return result @verbose def save(self, fname, split_size='2GB', fmt='single', overwrite=False, split_naming='neuromag', verbose=True): """Save epochs in a fif file. Parameters ---------- fname : str The name of the file, which should end with ``-epo.fif`` or ``-epo.fif.gz``. split_size : str | int Large raw files are automatically split into multiple pieces. This parameter specifies the maximum size of each piece. If the parameter is an integer, it specifies the size in Bytes. It is also possible to pass a human-readable string, e.g., 100MB. Note: Due to FIFF file limitations, the maximum split size is 2GB. .. versionadded:: 0.10.0 fmt : str Format to save data. Valid options are 'double' or 'single' for 64- or 32-bit float, or for 128- or 64-bit complex numbers respectively. Note: Data are processed with double precision. Choosing single-precision, the saved data will slightly differ due to the reduction in precision. .. versionadded:: 0.17 %(overwrite)s To overwrite original file (the same one that was loaded), data must be preloaded upon reading. This defaults to True in 0.18 but will change to False in 0.19. .. versionadded:: 0.18 %(split_naming)s .. versionadded:: 0.24 %(verbose)s Notes ----- Bad epochs will be dropped before saving the epochs to disk. """ check_fname(fname, 'epochs', ('-epo.fif', '-epo.fif.gz', '_epo.fif', '_epo.fif.gz')) # check for file existence and expand `~` if present fname = _check_fname(fname=fname, overwrite=overwrite) split_size_bytes = _get_split_size(split_size) _check_option('fmt', fmt, ['single', 'double']) # to know the length accurately. The get_data() call would drop # bad epochs anyway self.drop_bad() # total_size tracks sizes that get split # over_size tracks overhead (tags, things that get written to each) if len(self) == 0: warn('Saving epochs with no data') total_size = 0 else: d = self[0].get_data() # this should be guaranteed by subclasses assert d.dtype in ('>f8', '<f8', '>c16', '<c16') total_size = d.nbytes * len(self) self._check_consistency() over_size = 0 if fmt == "single": total_size //= 2 # 64bit data converted to 32bit before writing. over_size += 32 # FIF tags # Account for all the other things we write, too # 1. meas_id block plus main epochs block over_size += 132 # 2. measurement info (likely slight overestimate, but okay) over_size += object_size(self.info) + 16 * len(self.info) # 3. events and event_id in its own block total_size += self.events.size * 4 over_size += len(_event_id_string(self.event_id)) + 72 # 4. Metadata in a block of its own if self.metadata is not None: total_size += len(_prepare_write_metadata(self.metadata)) over_size += 56 # 5. first sample, last sample, baseline over_size += 40 * (self.baseline is not None) + 40 # 6. drop log: gets written to each, with IGNORE for ones that are # not part of it. So make a fake one with all having entries. drop_size = len(json.dumps(self.drop_log)) + 16 drop_size += 8 * (len(self.selection) - 1) # worst case: all but one over_size += drop_size # 7. reject params reject_params = _pack_reject_params(self) if reject_params: over_size += len(json.dumps(reject_params)) + 16 # 8. selection total_size += self.selection.size * 4 over_size += 16 # 9. end of file tags over_size += _NEXT_FILE_BUFFER logger.debug(f' Overhead size: {str(over_size).rjust(15)}') logger.debug(f' Splittable size: {str(total_size).rjust(15)}') logger.debug(f' Split size: {str(split_size_bytes).rjust(15)}') # need at least one per n_epochs = len(self) n_per = total_size // n_epochs if n_epochs else 0 min_size = n_per + over_size if split_size_bytes < min_size: raise ValueError( f'The split size {split_size} is too small to safely write ' 'the epochs contents, minimum split size is ' f'{sizeof_fmt(min_size)} ({min_size} bytes)') # This is like max(int(ceil(total_size / split_size)), 1) but cleaner n_parts = max( (total_size - 1) // (split_size_bytes - over_size) + 1, 1) assert n_parts >= 1, n_parts if n_parts > 1: logger.info(f'Splitting into {n_parts} parts') if n_parts > 100: # This must be an error raise ValueError( f'Split size {split_size} would result in writing ' f'{n_parts} files') if len(self.drop_log) > 100000: warn(f'epochs.drop_log contains {len(self.drop_log)} entries ' f'which will incur up to a {sizeof_fmt(drop_size)} writing ' f'overhead (per split file), consider using ' f'epochs.reset_drop_log_selection() prior to writing') epoch_idxs = np.array_split(np.arange(n_epochs), n_parts) for part_idx, epoch_idx in enumerate(epoch_idxs): this_epochs = self[epoch_idx] if n_parts > 1 else self # avoid missing event_ids in splits this_epochs.event_id = self.event_id _save_split(this_epochs, fname, part_idx, n_parts, fmt, split_naming, overwrite) @verbose def export(self, fname, fmt='auto', *, overwrite=False, verbose=None): """Export Epochs to external formats. Supported formats: EEGLAB (set, uses :mod:`eeglabio`) %(export_warning)s Parameters ---------- %(export_params_fname)s %(export_params_fmt)s %(overwrite)s .. versionadded:: 0.24.1 %(verbose)s Notes ----- .. versionadded:: 0.24 %(export_warning_note_epochs)s %(export_eeglab_note)s """ from .export import export_epochs export_epochs(fname, self, fmt, overwrite=overwrite, verbose=verbose) def equalize_event_counts(self, event_ids=None, method='mintime'): """Equalize the number of trials in each condition. It tries to make the remaining epochs occurring as close as possible in time. This method works based on the idea that if there happened to be some time-varying (like on the scale of minutes) noise characteristics during a recording, they could be compensated for (to some extent) in the equalization process. This method thus seeks to reduce any of those effects by minimizing the differences in the times of the events within a `~mne.Epochs` instance. For example, if one event type occurred at time points ``[1, 2, 3, 4, 120, 121]`` and the another one at ``[3.5, 4.5, 120.5, 121.5]``, this method would remove the events at times ``[1, 2]`` for the first event type – and not the events at times ``[120, 121]``. Parameters ---------- event_ids : None | list | dict The event types to equalize. If ``None`` (default), equalize the counts of **all** event types present in the `~mne.Epochs` instance. If a list, each element can either be a string (event name) or a list of strings. In the case where one of the entries is a list of strings, event types in that list will be grouped together before equalizing trial counts across conditions. If a dictionary, the keys are considered as the event names whose counts to equalize, i.e., passing ``dict(A=1, B=2)`` will have the same effect as passing ``['A', 'B']``. This is useful if you intend to pass an ``event_id`` dictionary that was used when creating `~mne.Epochs`. In the case where partial matching is used (using ``/`` in the event names), the event types will be matched according to the provided tags, that is, processing works as if the ``event_ids`` matched by the provided tags had been supplied instead. The ``event_ids`` must identify non-overlapping subsets of the epochs. method : str If ``'truncate'``, events will be truncated from the end of each type of events. If ``'mintime'``, timing differences between each event type will be minimized. Returns ------- epochs : instance of Epochs The modified instance. It is modified in-place. indices : array of int Indices from the original events list that were dropped. Notes ----- For example (if ``epochs.event_id`` was ``{'Left': 1, 'Right': 2, 'Nonspatial':3}``: epochs.equalize_event_counts([['Left', 'Right'], 'Nonspatial']) would equalize the number of trials in the ``'Nonspatial'`` condition with the total number of trials in the ``'Left'`` and ``'Right'`` conditions combined. If multiple indices are provided (e.g. ``'Left'`` and ``'Right'`` in the example above), it is not guaranteed that after equalization the conditions will contribute equally. E.g., it is possible to end up with 70 ``'Nonspatial'`` epochs, 69 ``'Left'`` and 1 ``'Right'``. .. versionchanged:: 0.23 Default to equalizing all events in the passed instance if no event names were specified explicitly. """ from collections.abc import Iterable _validate_type(event_ids, types=(Iterable, None), item_name='event_ids', type_name='list-like or None') if isinstance(event_ids, str): raise TypeError(f'event_ids must be list-like or None, but ' f'received a string: {event_ids}') if event_ids is None: event_ids = list(self.event_id) elif not event_ids: raise ValueError('event_ids must have at least one element') if not self._bad_dropped: self.drop_bad() # figure out how to equalize eq_inds = list() # deal with hierarchical tags ids = self.event_id orig_ids = list(event_ids) tagging = False if "/" in "".join(ids): # make string inputs a list of length 1 event_ids = [[x] if isinstance(x, str) else x for x in event_ids] for ids_ in event_ids: # check if tagging is attempted if any([id_ not in ids for id_ in ids_]): tagging = True # 1. treat everything that's not in event_id as a tag # 2a. for tags, find all the event_ids matched by the tags # 2b. for non-tag ids, just pass them directly # 3. do this for every input event_ids = [[k for k in ids if all((tag in k.split("/") for tag in id_))] # ids matching all tags if all(id__ not in ids for id__ in id_) else id_ # straight pass for non-tag inputs for id_ in event_ids] for ii, id_ in enumerate(event_ids): if len(id_) == 0: raise KeyError(f"{orig_ids[ii]} not found in the epoch " "object's event_id.") elif len({sub_id in ids for sub_id in id_}) != 1: err = ("Don't mix hierarchical and regular event_ids" " like in \'%s\'." % ", ".join(id_)) raise ValueError(err) # raise for non-orthogonal tags if tagging is True: events_ = [set(self[x].events[:, 0]) for x in event_ids] doubles = events_[0].intersection(events_[1]) if len(doubles): raise ValueError("The two sets of epochs are " "overlapping. Provide an " "orthogonal selection.") for eq in event_ids: eq_inds.append(self._keys_to_idx(eq)) event_times = [self.events[e, 0] for e in eq_inds] indices = _get_drop_indices(event_times, method) # need to re-index indices indices = np.concatenate([e[idx] for e, idx in zip(eq_inds, indices)]) self.drop(indices, reason='EQUALIZED_COUNT') # actually remove the indices return self, indices @verbose def to_data_frame(self, picks=None, index=None, scalings=None, copy=True, long_format=False, time_format='ms', *, verbose=None): """Export data in tabular structure as a pandas DataFrame. Channels are converted to columns in the DataFrame. By default, additional columns "time", "epoch" (epoch number), and "condition" (epoch event description) are added, unless ``index`` is not ``None`` (in which case the columns specified in ``index`` will be used to form the DataFrame's index instead). Parameters ---------- %(picks_all)s %(df_index_epo)s Valid string values are 'time', 'epoch', and 'condition'. Defaults to ``None``. %(df_scalings)s %(df_copy)s %(df_longform_epo)s %(df_time_format)s .. versionadded:: 0.20 %(verbose)s Returns ------- %(df_return)s """ # check pandas once here, instead of in each private utils function pd = _check_pandas_installed() # noqa # arg checking valid_index_args = ['time', 'epoch', 'condition'] valid_time_formats = ['ms', 'timedelta'] index = _check_pandas_index_arguments(index, valid_index_args) time_format = _check_time_format(time_format, valid_time_formats) # get data picks = _picks_to_idx(self.info, picks, 'all', exclude=()) data = self.get_data()[:, picks, :] times = self.times n_epochs, n_picks, n_times = data.shape data = np.hstack(data).T # (time*epochs) x signals if copy: data = data.copy() data = _scale_dataframe_data(self, data, picks, scalings) # prepare extra columns / multiindex mindex = list() times = np.tile(times, n_epochs) times = _convert_times(self, times, time_format) mindex.append(('time', times)) rev_event_id = {v: k for k, v in self.event_id.items()} conditions = [rev_event_id[k] for k in self.events[:, 2]] mindex.append(('condition', np.repeat(conditions, n_times))) mindex.append(('epoch', np.repeat(self.selection, n_times))) assert all(len(mdx) == len(mindex[0]) for mdx in mindex) # build DataFrame df = _build_data_frame(self, data, picks, long_format, mindex, index, default_index=['condition', 'epoch', 'time']) return df def as_type(self, ch_type='grad', mode='fast'): """Compute virtual epochs using interpolated fields. .. Warning:: Using virtual epochs to compute inverse can yield unexpected results. The virtual channels have ``'_v'`` appended at the end of the names to emphasize that the data contained in them are interpolated. Parameters ---------- ch_type : str The destination channel type. It can be 'mag' or 'grad'. mode : str Either ``'accurate'`` or ``'fast'``, determines the quality of the Legendre polynomial expansion used. ``'fast'`` should be sufficient for most applications. Returns ------- epochs : instance of mne.EpochsArray The transformed epochs object containing only virtual channels. Notes ----- This method returns a copy and does not modify the data it operates on. It also returns an EpochsArray instance. .. versionadded:: 0.20.0 """ from .forward import _as_meg_type_inst return _as_meg_type_inst(self, ch_type=ch_type, mode=mode) def _drop_log_stats(drop_log, ignore=('IGNORED',)): """Compute drop log stats. Parameters ---------- drop_log : list of list Epoch drop log from Epochs.drop_log. ignore : list The drop reasons to ignore. Returns ------- perc : float Total percentage of epochs dropped. """ if not isinstance(drop_log, tuple) or \ not all(isinstance(d, tuple) for d in drop_log) or \ not all(isinstance(s, str) for d in drop_log for s in d): raise TypeError('drop_log must be a tuple of tuple of str') perc = 100 * np.mean([len(d) > 0 for d in drop_log if not any(r in ignore for r in d)]) return perc def make_metadata(events, event_id, tmin, tmax, sfreq, row_events=None, keep_first=None, keep_last=None): """Generate metadata from events for use with `mne.Epochs`. This function mimics the epoching process (it constructs time windows around time-locked "events of interest") and collates information about any other events that occurred within those time windows. The information is returned as a :class:`pandas.DataFrame` suitable for use as `~mne.Epochs` metadata: one row per time-locked event, and columns indicating presence/absence and latency of each ancillary event type. The function will also return a new ``events`` array and ``event_id`` dictionary that correspond to the generated metadata. Parameters ---------- events : array, shape (m, 3) The :term:`events array <events>`. By default, the returned metadata :class:`~pandas.DataFrame` will have as many rows as the events array. To create rows for only a subset of events, pass the ``row_events`` parameter. event_id : dict A mapping from event names (keys) to event IDs (values). The event names will be incorporated as columns of the returned metadata :class:`~pandas.DataFrame`. tmin, tmax : float Start and end of the time interval for metadata generation in seconds, relative to the time-locked event of the respective time window. .. note:: If you are planning to attach the generated metadata to `~mne.Epochs` and intend to include only events that fall inside your epochs time interval, pass the same ``tmin`` and ``tmax`` values here as you use for your epochs. sfreq : float The sampling frequency of the data from which the events array was extracted. row_events : list of str | str | None Event types around which to create the time windows / for which to create **rows** in the returned metadata :class:`pandas.DataFrame`. If provided, the string(s) must be keys of ``event_id``. If ``None`` (default), rows are created for **all** event types present in ``event_id``. keep_first : str | list of str | None Specify subsets of :term:`hierarchical event descriptors` (HEDs, inspired by :footcite:`BigdelyShamloEtAl2013`) matching events of which the **first occurrence** within each time window shall be stored in addition to the original events. .. note:: There is currently no way to retain **all** occurrences of a repeated event. The ``keep_first`` parameter can be used to specify subsets of HEDs, effectively creating a new event type that is the union of all events types described by the matching HED pattern. Only the very first event of this set will be kept. For example, you might have two response events types, ``response/left`` and ``response/right``; and in trials with both responses occurring, you want to keep only the first response. In this case, you can pass ``keep_first='response'``. This will add two new columns to the metadata: ``response``, indicating at what **time** the event occurred, relative to the time-locked event; and ``first_response``, stating which **type** (``'left'`` or ``'right'``) of event occurred. To match specific subsets of HEDs describing different sets of events, pass a list of these subsets, e.g. ``keep_first=['response', 'stimulus']``. If ``None`` (default), no event aggregation will take place and no new columns will be created. .. note:: By default, this function will always retain the first instance of any event in each time window. For example, if a time window contains two ``'response'`` events, the generated ``response`` column will automatically refer to the first of the two events. In this specific case, it is therefore **not** necessary to make use of the ``keep_first`` parameter – unless you need to differentiate between two types of responses, like in the example above. keep_last : list of str | None Same as ``keep_first``, but for keeping only the **last** occurrence of matching events. The column indicating the **type** of an event ``myevent`` will be named ``last_myevent``. Returns ------- metadata : pandas.DataFrame Metadata for each row event, with the following columns: - ``event_name``, with strings indicating the name of the time-locked event ("row event") for that specific time window - one column per event type in ``event_id``, with the same name; floats indicating the latency of the event in seconds, relative to the time-locked event - if applicable, additional columns named after the ``keep_first`` and ``keep_last`` event types; floats indicating the latency of the event in seconds, relative to the time-locked event - if applicable, additional columns ``first_{event_type}`` and ``last_{event_type}`` for ``keep_first`` and ``keep_last`` event types, respetively; the values will be strings indicating which event types were matched by the provided HED patterns events : array, shape (n, 3) The events corresponding to the generated metadata, i.e. one time-locked event per row. event_id : dict The event dictionary corresponding to the new events array. This will be identical to the input dictionary unless ``row_events`` is supplied, in which case it will only contain the events provided there. Notes ----- The time window used for metadata generation need not correspond to the time window used to create the `~mne.Epochs`, to which the metadata will be attached; it may well be much shorter or longer, or not overlap at all, if desired. The can be useful, for example, to include events that occurred before or after an epoch, e.g. during the inter-trial interval. .. versionadded:: 0.23 References ---------- .. footbibliography:: """ pd = _check_pandas_installed() _validate_type(event_id, types=(dict,), item_name='event_id') _validate_type(row_events, types=(None, str, list, tuple), item_name='row_events') _validate_type(keep_first, types=(None, str, list, tuple), item_name='keep_first') _validate_type(keep_last, types=(None, str, list, tuple), item_name='keep_last') if not event_id: raise ValueError('event_id dictionary must contain at least one entry') def _ensure_list(x): if x is None: return [] elif isinstance(x, str): return [x] else: return list(x) row_events = _ensure_list(row_events) keep_first = _ensure_list(keep_first) keep_last = _ensure_list(keep_last) keep_first_and_last = set(keep_first) & set(keep_last) if keep_first_and_last: raise ValueError(f'The event names in keep_first and keep_last must ' f'be mutually exclusive. Specified in both: ' f'{", ".join(sorted(keep_first_and_last))}') del keep_first_and_last for param_name, values in dict(keep_first=keep_first, keep_last=keep_last).items(): for first_last_event_name in values: try: match_event_names(event_id, [first_last_event_name]) except KeyError: raise ValueError( f'Event "{first_last_event_name}", specified in ' f'{param_name}, cannot be found in event_id dictionary') event_name_diff = sorted(set(row_events) - set(event_id.keys())) if event_name_diff: raise ValueError( f'Present in row_events, but missing from event_id: ' f'{", ".join(event_name_diff)}') del event_name_diff # First and last sample of each epoch, relative to the time-locked event # This follows the approach taken in mne.Epochs start_sample = int(round(tmin * sfreq)) stop_sample = int(round(tmax * sfreq)) + 1 # Make indexing easier # We create the DataFrame before subsetting the events so we end up with # indices corresponding to the original event indices. Not used for now, # but might come in handy sometime later events_df = pd.DataFrame(events, columns=('sample', 'prev_id', 'id')) id_to_name_map = {v: k for k, v in event_id.items()} # Only keep events that are of interest events = events[np.in1d(events[:, 2], list(event_id.values()))] events_df = events_df.loc[events_df['id'].isin(event_id.values()), :] # Prepare & condition the metadata DataFrame # Avoid column name duplications if the exact same event name appears in # event_id.keys() and keep_first / keep_last simultaneously keep_first_cols = [col for col in keep_first if col not in event_id] keep_last_cols = [col for col in keep_last if col not in event_id] first_cols = [f'first_{col}' for col in keep_first_cols] last_cols = [f'last_{col}' for col in keep_last_cols] columns = ['event_name', *event_id.keys(), *keep_first_cols, *keep_last_cols, *first_cols, *last_cols] data = np.empty((len(events_df), len(columns))) metadata = pd.DataFrame(data=data, columns=columns, index=events_df.index) # Event names metadata.iloc[:, 0] = '' # Event times start_idx = 1 stop_idx = (start_idx + len(event_id.keys()) + len(keep_first_cols + keep_last_cols)) metadata.iloc[:, start_idx:stop_idx] = np.nan # keep_first and keep_last names start_idx = stop_idx metadata.iloc[:, start_idx:] = None # We're all set, let's iterate over all eventns and fill in in the # respective cells in the metadata. We will subset this to include only # `row_events` later for row_event in events_df.itertuples(name='RowEvent'): row_idx = row_event.Index metadata.loc[row_idx, 'event_name'] = \ id_to_name_map[row_event.id] # Determine which events fall into the current epoch window_start_sample = row_event.sample + start_sample window_stop_sample = row_event.sample + stop_sample events_in_window = events_df.loc[ (events_df['sample'] >= window_start_sample) & (events_df['sample'] <= window_stop_sample), :] assert not events_in_window.empty # Store the metadata for event in events_in_window.itertuples(name='Event'): event_sample = event.sample - row_event.sample event_time = event_sample / sfreq event_time = 0 if np.isclose(event_time, 0) else event_time event_name = id_to_name_map[event.id] if not np.isnan(metadata.loc[row_idx, event_name]): # Event already exists in current time window! assert metadata.loc[row_idx, event_name] <= event_time if event_name not in keep_last: continue metadata.loc[row_idx, event_name] = event_time # Handle keep_first and keep_last event aggregation for event_group_name in keep_first + keep_last: if event_name not in match_event_names( event_id, [event_group_name] ): continue if event_group_name in keep_first: first_last_col = f'first_{event_group_name}' else: first_last_col = f'last_{event_group_name}' old_time = metadata.loc[row_idx, event_group_name] if not np.isnan(old_time): if ((event_group_name in keep_first and old_time <= event_time) or (event_group_name in keep_last and old_time >= event_time)): continue if event_group_name not in event_id: # This is an HED. Strip redundant information from the # event name name = (event_name .replace(event_group_name, '') .replace('//', '/') .strip('/')) metadata.loc[row_idx, first_last_col] = name del name metadata.loc[row_idx, event_group_name] = event_time # Only keep rows of interest if row_events: event_id_timelocked = {name: val for name, val in event_id.items() if name in row_events} events = events[np.in1d(events[:, 2], list(event_id_timelocked.values()))] metadata = metadata.loc[ metadata['event_name'].isin(event_id_timelocked)] assert len(events) == len(metadata) event_id = event_id_timelocked return metadata, events, event_id @fill_doc class Epochs(BaseEpochs): """Epochs extracted from a Raw instance. Parameters ---------- %(epochs_raw)s %(events_epochs)s %(event_id)s %(epochs_tmin_tmax)s %(baseline_epochs)s Defaults to ``(None, 0)``, i.e. beginning of the the data until time point zero. %(picks_all)s preload : bool %(epochs_preload)s %(reject_epochs)s %(flat)s %(proj_epochs)s %(decim)s %(epochs_reject_tmin_tmax)s %(epochs_detrend)s %(epochs_on_missing)s %(reject_by_annotation_epochs)s %(epochs_metadata)s %(epochs_event_repeated)s %(verbose)s Attributes ---------- %(info_not_none)s event_id : dict Names of conditions corresponding to event_ids. ch_names : list of string List of channel names. selection : array List of indices of selected events (not dropped or ignored etc.). For example, if the original event array had 4 events and the second event has been dropped, this attribute would be np.array([0, 2, 3]). preload : bool Indicates whether epochs are in memory. drop_log : tuple of tuple A tuple of the same length as the event array used to initialize the Epochs object. If the i-th original event is still part of the selection, drop_log[i] will be an empty tuple; otherwise it will be a tuple of the reasons the event is not longer in the selection, e.g.: - 'IGNORED' If it isn't part of the current subset defined by the user - 'NO_DATA' or 'TOO_SHORT' If epoch didn't contain enough data names of channels that exceeded the amplitude threshold - 'EQUALIZED_COUNTS' See :meth:`~mne.Epochs.equalize_event_counts` - 'USER' For user-defined reasons (see :meth:`~mne.Epochs.drop`). filename : str The filename of the object. times : ndarray Time vector in seconds. Goes from ``tmin`` to ``tmax``. Time interval between consecutive time samples is equal to the inverse of the sampling frequency. See Also -------- mne.epochs.combine_event_ids mne.Epochs.equalize_event_counts Notes ----- When accessing data, Epochs are detrended, baseline-corrected, and decimated, then projectors are (optionally) applied. For indexing and slicing using ``epochs[...]``, see :meth:`mne.Epochs.__getitem__`. All methods for iteration over objects (using :meth:`mne.Epochs.__iter__`, :meth:`mne.Epochs.iter_evoked` or :meth:`mne.Epochs.next`) use the same internal state. If ``event_repeated`` is set to ``'merge'``, the coinciding events (duplicates) will be merged into a single event_id and assigned a new id_number as:: event_id['{event_id_1}/{event_id_2}/...'] = new_id_number For example with the event_id ``{'aud': 1, 'vis': 2}`` and the events ``[[0, 0, 1], [0, 0, 2]]``, the "merge" behavior will update both event_id and events to be: ``{'aud/vis': 3}`` and ``[[0, 0, 3]]`` respectively. There is limited support for :class:`~mne.Annotations` in the :class:`~mne.Epochs` class. Currently annotations that are present in the :class:`~mne.io.Raw` object will be preserved in the resulting :class:`~mne.Epochs` object, but: 1. It is not yet possible to add annotations to the Epochs object programmatically (via code) or interactively (through the plot window) 2. Concatenating :class:`~mne.Epochs` objects that contain annotations is not supported, and any annotations will be dropped when concatenating. 3. Annotations will be lost on save. """ @verbose def __init__(self, raw, events, event_id=None, tmin=-0.2, tmax=0.5, baseline=(None, 0), picks=None, preload=False, reject=None, flat=None, proj=True, decim=1, reject_tmin=None, reject_tmax=None, detrend=None, on_missing='raise', reject_by_annotation=True, metadata=None, event_repeated='error', verbose=None): # noqa: D102 if not isinstance(raw, BaseRaw): raise ValueError('The first argument to `Epochs` must be an ' 'instance of mne.io.BaseRaw') info = deepcopy(raw.info) # proj is on when applied in Raw proj = proj or raw.proj self.reject_by_annotation = reject_by_annotation # keep track of original sfreq (needed for annotations) raw_sfreq = raw.info['sfreq'] # call BaseEpochs constructor super(Epochs, self).__init__( info, None, events, event_id, tmin, tmax, metadata=metadata, baseline=baseline, raw=raw, picks=picks, reject=reject, flat=flat, decim=decim, reject_tmin=reject_tmin, reject_tmax=reject_tmax, detrend=detrend, proj=proj, on_missing=on_missing, preload_at_end=preload, event_repeated=event_repeated, verbose=verbose, raw_sfreq=raw_sfreq, annotations=raw.annotations) @verbose def _get_epoch_from_raw(self, idx, verbose=None): """Load one epoch from disk. Returns ------- data : array | str | None If string, it's details on rejection reason. If array, it's the data in the desired range (good segment) If None, it means no data is available. """ if self._raw is None: # This should never happen, as raw=None only if preload=True raise ValueError('An error has occurred, no valid raw file found. ' 'Please report this to the mne-python ' 'developers.') sfreq = self._raw.info['sfreq'] event_samp = self.events[idx, 0] # Read a data segment from "start" to "stop" in samples first_samp = self._raw.first_samp start = int(round(event_samp + self._raw_times[0] * sfreq)) start -= first_samp stop = start + len(self._raw_times) # reject_tmin, and reject_tmax need to be converted to samples to # check the reject_by_annotation boundaries: reject_start, reject_stop reject_tmin = self.reject_tmin if reject_tmin is None: reject_tmin = self._raw_times[0] reject_start = int(round(event_samp + reject_tmin * sfreq)) reject_start -= first_samp reject_tmax = self.reject_tmax if reject_tmax is None: reject_tmax = self._raw_times[-1] diff = int(round((self._raw_times[-1] - reject_tmax) * sfreq)) reject_stop = stop - diff logger.debug(' Getting epoch for %d-%d' % (start, stop)) data = self._raw._check_bad_segment(start, stop, self.picks, reject_start, reject_stop, self.reject_by_annotation) return data @fill_doc class EpochsArray(BaseEpochs): """Epochs object from numpy array. Parameters ---------- data : array, shape (n_epochs, n_channels, n_times) The channels' time series for each epoch. See notes for proper units of measure. %(info_not_none)s Consider using :func:`mne.create_info` to populate this structure. events : None | array of int, shape (n_events, 3) The events typically returned by the read_events function. If some events don't match the events of interest as specified by event_id, they will be marked as 'IGNORED' in the drop log. If None (default), all event values are set to 1 and event time-samples are set to range(n_epochs). tmin : float Start time before event. If nothing provided, defaults to 0. event_id : int | list of int | dict | None The id of the event to consider. If dict, the keys can later be used to access associated events. Example: dict(auditory=1, visual=3). If int, a dict will be created with the id as string. If a list, all events with the IDs specified in the list are used. If None, all events will be used with and a dict is created with string integer names corresponding to the event id integers. %(reject_epochs)s %(flat)s reject_tmin : scalar | None Start of the time window used to reject epochs (with the default None, the window will start with tmin). reject_tmax : scalar | None End of the time window used to reject epochs (with the default None, the window will end with tmax). %(baseline_epochs)s Defaults to ``None``, i.e. no baseline correction. proj : bool | 'delayed' Apply SSP projection vectors. See :class:`mne.Epochs` for details. on_missing : str See :class:`mne.Epochs` docstring for details. metadata : instance of pandas.DataFrame | None See :class:`mne.Epochs` docstring for details. .. versionadded:: 0.16 selection : ndarray | None The selection compared to the original set of epochs. Can be None to use ``np.arange(len(events))``. .. versionadded:: 0.16 %(verbose)s See Also -------- create_info EvokedArray io.RawArray Notes ----- Proper units of measure: * V: eeg, eog, seeg, dbs, emg, ecg, bio, ecog * T: mag * T/m: grad * M: hbo, hbr * Am: dipole * AU: misc EpochsArray does not set `Annotations`. If you would like to create simulated data with Annotations that are then preserved in the Epochs object, you would use `mne.io.RawArray` first and then create an `mne.Epochs` object. """ @verbose def __init__(self, data, info, events=None, tmin=0, event_id=None, reject=None, flat=None, reject_tmin=None, reject_tmax=None, baseline=None, proj=True, on_missing='raise', metadata=None, selection=None, verbose=None): # noqa: D102 dtype = np.complex128 if np.any(np.iscomplex(data)) else np.float64 data = np.asanyarray(data, dtype=dtype) if data.ndim != 3: raise ValueError('Data must be a 3D array of shape (n_epochs, ' 'n_channels, n_samples)') if len(info['ch_names']) != data.shape[1]: raise ValueError('Info and data must have same number of ' 'channels.') if events is None: n_epochs = len(data) events = _gen_events(n_epochs) info = info.copy() # do not modify original info tmax = (data.shape[2] - 1) / info['sfreq'] + tmin super(EpochsArray, self).__init__( info, data, events, event_id, tmin, tmax, baseline, reject=reject, flat=flat, reject_tmin=reject_tmin, reject_tmax=reject_tmax, decim=1, metadata=metadata, selection=selection, proj=proj, on_missing=on_missing, verbose=verbose) if self.baseline is not None: self._do_baseline = True if len(events) != np.in1d(self.events[:, 2], list(self.event_id.values())).sum(): raise ValueError('The events must only contain event numbers from ' 'event_id') detrend_picks = self._detrend_picks for e in self._data: # This is safe without assignment b/c there is no decim self._detrend_offset_decim(e, detrend_picks) self.drop_bad() def combine_event_ids(epochs, old_event_ids, new_event_id, copy=True): """Collapse event_ids from an epochs instance into a new event_id. Parameters ---------- epochs : instance of Epochs The epochs to operate on. old_event_ids : str, or list Conditions to collapse together. new_event_id : dict, or int A one-element dict (or a single integer) for the new condition. Note that for safety, this cannot be any existing id (in epochs.event_id.values()). copy : bool Whether to return a new instance or modify in place. Returns ------- epochs : instance of Epochs The modified epochs. Notes ----- This For example (if epochs.event_id was ``{'Left': 1, 'Right': 2}``:: combine_event_ids(epochs, ['Left', 'Right'], {'Directional': 12}) would create a 'Directional' entry in epochs.event_id replacing 'Left' and 'Right' (combining their trials). """ epochs = epochs.copy() if copy else epochs old_event_ids = np.asanyarray(old_event_ids) if isinstance(new_event_id, int): new_event_id = {str(new_event_id): new_event_id} else: if not isinstance(new_event_id, dict): raise ValueError('new_event_id must be a dict or int') if not len(list(new_event_id.keys())) == 1: raise ValueError('new_event_id dict must have one entry') new_event_num = list(new_event_id.values())[0] new_event_num = operator.index(new_event_num) if new_event_num in epochs.event_id.values(): raise ValueError('new_event_id value must not already exist') # could use .pop() here, but if a latter one doesn't exist, we're # in trouble, so run them all here and pop() later old_event_nums = np.array([epochs.event_id[key] for key in old_event_ids]) # find the ones to replace inds = np.any(epochs.events[:, 2][:, np.newaxis] == old_event_nums[np.newaxis, :], axis=1) # replace the event numbers in the events list epochs.events[inds, 2] = new_event_num # delete old entries for key in old_event_ids: epochs.event_id.pop(key) # add the new entry epochs.event_id.update(new_event_id) return epochs def equalize_epoch_counts(epochs_list, method='mintime'): """Equalize the number of trials in multiple Epoch instances. Parameters ---------- epochs_list : list of Epochs instances The Epochs instances to equalize trial counts for. method : str If 'truncate', events will be truncated from the end of each event list. If 'mintime', timing differences between each event list will be minimized. Notes ----- This tries to make the remaining epochs occurring as close as possible in time. This method works based on the idea that if there happened to be some time-varying (like on the scale of minutes) noise characteristics during a recording, they could be compensated for (to some extent) in the equalization process. This method thus seeks to reduce any of those effects by minimizing the differences in the times of the events in the two sets of epochs. For example, if one had event times [1, 2, 3, 4, 120, 121] and the other one had [3.5, 4.5, 120.5, 121.5], it would remove events at times [1, 2] in the first epochs and not [120, 121]. Examples -------- >>> equalize_epoch_counts([epochs1, epochs2]) # doctest: +SKIP """ if not all(isinstance(e, BaseEpochs) for e in epochs_list): raise ValueError('All inputs must be Epochs instances') # make sure bad epochs are dropped for e in epochs_list: if not e._bad_dropped: e.drop_bad() event_times = [e.events[:, 0] for e in epochs_list] indices = _get_drop_indices(event_times, method) for e, inds in zip(epochs_list, indices): e.drop(inds, reason='EQUALIZED_COUNT') def _get_drop_indices(event_times, method): """Get indices to drop from multiple event timing lists.""" small_idx = np.argmin([e.shape[0] for e in event_times]) small_e_times = event_times[small_idx] _check_option('method', method, ['mintime', 'truncate']) indices = list() for e in event_times: if method == 'mintime': mask = _minimize_time_diff(small_e_times, e) else: mask = np.ones(e.shape[0], dtype=bool) mask[small_e_times.shape[0]:] = False indices.append(np.where(np.logical_not(mask))[0]) return indices def _minimize_time_diff(t_shorter, t_longer): """Find a boolean mask to minimize timing differences.""" from scipy.interpolate import interp1d keep = np.ones((len(t_longer)), dtype=bool) # special case: length zero or one if len(t_shorter) < 2: # interp1d won't work keep.fill(False) if len(t_shorter) == 1: idx = np.argmin(np.abs(t_longer - t_shorter)) keep[idx] = True return keep scores = np.ones((len(t_longer))) x1 = np.arange(len(t_shorter)) # The first set of keep masks to test kwargs = dict(copy=False, bounds_error=False, assume_sorted=True) shorter_interp = interp1d(x1, t_shorter, fill_value=t_shorter[-1], **kwargs) for ii in range(len(t_longer) - len(t_shorter)): scores.fill(np.inf) # set up the keep masks to test, eliminating any rows that are already # gone keep_mask = ~np.eye(len(t_longer), dtype=bool)[keep] keep_mask[:, ~keep] = False # Check every possible removal to see if it minimizes x2 = np.arange(len(t_longer) - ii - 1) t_keeps = np.array([t_longer[km] for km in keep_mask]) longer_interp = interp1d(x2, t_keeps, axis=1, fill_value=t_keeps[:, -1], **kwargs) d1 = longer_interp(x1) - t_shorter d2 = shorter_interp(x2) - t_keeps scores[keep] = np.abs(d1, d1).sum(axis=1) + np.abs(d2, d2).sum(axis=1) keep[np.argmin(scores)] = False return keep @verbose def _is_good(e, ch_names, channel_type_idx, reject, flat, full_report=False, ignore_chs=[], verbose=None): """Test if data segment e is good according to reject and flat. If full_report=True, it will give True/False as well as a list of all offending channels. """ bad_tuple = tuple() has_printed = False checkable = np.ones(len(ch_names), dtype=bool) checkable[np.array([c in ignore_chs for c in ch_names], dtype=bool)] = False for refl, f, t in zip([reject, flat], [np.greater, np.less], ['', 'flat']): if refl is not None: for key, thresh in refl.items(): idx = channel_type_idx[key] name = key.upper() if len(idx) > 0: e_idx = e[idx] deltas = np.max(e_idx, axis=1) - np.min(e_idx, axis=1) checkable_idx = checkable[idx] idx_deltas = np.where(np.logical_and(f(deltas, thresh), checkable_idx))[0] if len(idx_deltas) > 0: bad_names = [ch_names[idx[i]] for i in idx_deltas] if (not has_printed): logger.info(' Rejecting %s epoch based on %s : ' '%s' % (t, name, bad_names)) has_printed = True if not full_report: return False else: bad_tuple += tuple(bad_names) if not full_report: return True else: if bad_tuple == (): return True, None else: return False, bad_tuple def _read_one_epoch_file(f, tree, preload): """Read a single FIF file.""" with f as fid: # Read the measurement info info, meas = read_meas_info(fid, tree, clean_bads=True) # read in the Annotations if they exist annotations = _read_annotations_fif(fid, tree) events, mappings = _read_events_fif(fid, tree) # Metadata metadata = None metadata_tree = dir_tree_find(tree, FIFF.FIFFB_MNE_METADATA) if len(metadata_tree) > 0: for dd in metadata_tree[0]['directory']: kind = dd.kind pos = dd.pos if kind == FIFF.FIFF_DESCRIPTION: metadata = read_tag(fid, pos).data metadata = _prepare_read_metadata(metadata) break # Locate the data of interest processed = dir_tree_find(meas, FIFF.FIFFB_PROCESSED_DATA) del meas if len(processed) == 0: raise ValueError('Could not find processed data') epochs_node = dir_tree_find(tree, FIFF.FIFFB_MNE_EPOCHS) if len(epochs_node) == 0: # before version 0.11 we errantly saved with this tag instead of # an MNE tag epochs_node = dir_tree_find(tree, FIFF.FIFFB_MNE_EPOCHS) if len(epochs_node) == 0: epochs_node = dir_tree_find(tree, 122) # 122 used before v0.11 if len(epochs_node) == 0: raise ValueError('Could not find epochs data') my_epochs = epochs_node[0] # Now find the data in the block data = None data_tag = None bmin, bmax = None, None baseline = None selection = None drop_log = None raw_sfreq = None reject_params = {} for k in range(my_epochs['nent']): kind = my_epochs['directory'][k].kind pos = my_epochs['directory'][k].pos if kind == FIFF.FIFF_FIRST_SAMPLE: tag = read_tag(fid, pos) first = int(tag.data) elif kind == FIFF.FIFF_LAST_SAMPLE: tag = read_tag(fid, pos) last = int(tag.data) elif kind == FIFF.FIFF_EPOCH: # delay reading until later fid.seek(pos, 0) data_tag = read_tag_info(fid) data_tag.pos = pos data_tag.type = data_tag.type ^ (1 << 30) elif kind in [FIFF.FIFF_MNE_BASELINE_MIN, 304]: # Constant 304 was used before v0.11 tag = read_tag(fid, pos) bmin = float(tag.data) elif kind in [FIFF.FIFF_MNE_BASELINE_MAX, 305]: # Constant 305 was used before v0.11 tag = read_tag(fid, pos) bmax = float(tag.data) elif kind == FIFF.FIFF_MNE_EPOCHS_SELECTION: tag = read_tag(fid, pos) selection = np.array(tag.data) elif kind == FIFF.FIFF_MNE_EPOCHS_DROP_LOG: tag = read_tag(fid, pos) drop_log = tag.data drop_log = json.loads(drop_log) drop_log = tuple(tuple(x) for x in drop_log) elif kind == FIFF.FIFF_MNE_EPOCHS_REJECT_FLAT: tag = read_tag(fid, pos) reject_params = json.loads(tag.data) elif kind == FIFF.FIFF_MNE_EPOCHS_RAW_SFREQ: tag = read_tag(fid, pos) raw_sfreq = tag.data if bmin is not None or bmax is not None: baseline = (bmin, bmax) n_samp = last - first + 1 logger.info(' Found the data of interest:') logger.info(' t = %10.2f ... %10.2f ms' % (1000 * first / info['sfreq'], 1000 * last / info['sfreq'])) if info['comps'] is not None: logger.info(' %d CTF compensation matrices available' % len(info['comps'])) # Inspect the data if data_tag is None: raise ValueError('Epochs data not found') epoch_shape = (len(info['ch_names']), n_samp) size_expected = len(events) * np.prod(epoch_shape) # on read double-precision is always used if data_tag.type == FIFF.FIFFT_FLOAT: datatype = np.float64 fmt = '>f4' elif data_tag.type == FIFF.FIFFT_DOUBLE: datatype = np.float64 fmt = '>f8' elif data_tag.type == FIFF.FIFFT_COMPLEX_FLOAT: datatype = np.complex128 fmt = '>c8' elif data_tag.type == FIFF.FIFFT_COMPLEX_DOUBLE: datatype = np.complex128 fmt = '>c16' fmt_itemsize = np.dtype(fmt).itemsize assert fmt_itemsize in (4, 8, 16) size_actual = data_tag.size // fmt_itemsize - 16 // fmt_itemsize if not size_actual == size_expected: raise ValueError('Incorrect number of samples (%d instead of %d)' % (size_actual, size_expected)) # Calibration factors cals = np.array([[info['chs'][k]['cal'] * info['chs'][k].get('scale', 1.0)] for k in range(info['nchan'])], np.float64) # Read the data if preload: data = read_tag(fid, data_tag.pos).data.astype(datatype) data *= cals # Put it all together tmin = first / info['sfreq'] tmax = last / info['sfreq'] event_id = ({str(e): e for e in np.unique(events[:, 2])} if mappings is None else mappings) # In case epochs didn't have a FIFF.FIFF_MNE_EPOCHS_SELECTION tag # (version < 0.8): if selection is None: selection = np.arange(len(events)) if drop_log is None: drop_log = ((),) * len(events) return (info, data, data_tag, events, event_id, metadata, tmin, tmax, baseline, selection, drop_log, epoch_shape, cals, reject_params, fmt, annotations, raw_sfreq) @verbose def read_epochs(fname, proj=True, preload=True, verbose=None): """Read epochs from a fif file. Parameters ---------- %(epochs_fname)s %(proj_epochs)s preload : bool If True, read all epochs from disk immediately. If ``False``, epochs will be read on demand. %(verbose)s Returns ------- epochs : instance of Epochs The epochs. """ return EpochsFIF(fname, proj, preload, verbose) class _RawContainer(object): """Helper for a raw data container.""" def __init__(self, fid, data_tag, event_samps, epoch_shape, cals, fmt): # noqa: D102 self.fid = fid self.data_tag = data_tag self.event_samps = event_samps self.epoch_shape = epoch_shape self.cals = cals self.proj = False self.fmt = fmt def __del__(self): # noqa: D105 self.fid.close() @fill_doc class EpochsFIF(BaseEpochs): """Epochs read from disk. Parameters ---------- %(epochs_fname)s %(proj_epochs)s preload : bool If True, read all epochs from disk immediately. If False, epochs will be read on demand. %(verbose)s See Also -------- mne.Epochs mne.epochs.combine_event_ids mne.Epochs.equalize_event_counts """ @verbose def __init__(self, fname, proj=True, preload=True, verbose=None): # noqa: D102 if _path_like(fname): check_fname( fname=fname, filetype='epochs', endings=('-epo.fif', '-epo.fif.gz', '_epo.fif', '_epo.fif.gz') ) fname = _check_fname(fname=fname, must_exist=True, overwrite='read') elif not preload: raise ValueError('preload must be used with file-like objects') fnames = [fname] ep_list = list() raw = list() for fname in fnames: fname_rep = _get_fname_rep(fname) logger.info('Reading %s ...' % fname_rep) fid, tree, _ = fiff_open(fname, preload=preload) next_fname = _get_next_fname(fid, fname, tree) (info, data, data_tag, events, event_id, metadata, tmin, tmax, baseline, selection, drop_log, epoch_shape, cals, reject_params, fmt, annotations, raw_sfreq) = \ _read_one_epoch_file(fid, tree, preload) if (events[:, 0] < 0).any(): events = events.copy() warn('Incorrect events detected on disk, setting event ' 'numbers to consecutive increasing integers') events[:, 0] = np.arange(1, len(events) + 1) # here we ignore missing events, since users should already be # aware of missing events if they have saved data that way # we also retain original baseline without re-applying baseline # correction (data is being baseline-corrected when written to # disk) epoch = BaseEpochs( info, data, events, event_id, tmin, tmax, baseline=None, metadata=metadata, on_missing='ignore', selection=selection, drop_log=drop_log, proj=False, verbose=False, raw_sfreq=raw_sfreq) epoch.baseline = baseline epoch._do_baseline = False # might be superfluous but won't hurt ep_list.append(epoch) if not preload: # store everything we need to index back to the original data raw.append(_RawContainer(fiff_open(fname)[0], data_tag, events[:, 0].copy(), epoch_shape, cals, fmt)) if next_fname is not None: fnames.append(next_fname) unsafe_annot_add = raw_sfreq is None (info, data, raw_sfreq, events, event_id, tmin, tmax, metadata, baseline, selection, drop_log) = \ _concatenate_epochs(ep_list, with_data=preload, add_offset=False) # we need this uniqueness for non-preloaded data to work properly if len(np.unique(events[:, 0])) != len(events): raise RuntimeError('Event time samples were not unique') # correct the drop log assert len(drop_log) % len(fnames) == 0 step = len(drop_log) // len(fnames) offsets = np.arange(step, len(drop_log) + 1, step) drop_log = list(drop_log) for i1, i2 in zip(offsets[:-1], offsets[1:]): other_log = drop_log[i1:i2] for k, (a, b) in enumerate(zip(drop_log, other_log)): if a == ('IGNORED',) and b != ('IGNORED',): drop_log[k] = b drop_log = tuple(drop_log[:step]) # call BaseEpochs constructor # again, ensure we're retaining the baseline period originally loaded # from disk without trying to re-apply baseline correction super(EpochsFIF, self).__init__( info, data, events, event_id, tmin, tmax, baseline=None, raw=raw, proj=proj, preload_at_end=False, on_missing='ignore', selection=selection, drop_log=drop_log, filename=fname_rep, metadata=metadata, verbose=verbose, raw_sfreq=raw_sfreq, annotations=annotations, **reject_params) self.baseline = baseline self._do_baseline = False # use the private property instead of drop_bad so that epochs # are not all read from disk for preload=False self._bad_dropped = True # private property to suggest that people re-save epochs if they add # annotations self._unsafe_annot_add = unsafe_annot_add @verbose def _get_epoch_from_raw(self, idx, verbose=None): """Load one epoch from disk.""" # Find the right file and offset to use event_samp = self.events[idx, 0] for raw in self._raw: idx = np.where(raw.event_samps == event_samp)[0] if len(idx) == 1: fmt = raw.fmt idx = idx[0] size = np.prod(raw.epoch_shape) * np.dtype(fmt).itemsize offset = idx * size + 16 # 16 = Tag header break else: # read the correct subset of the data raise RuntimeError('Correct epoch could not be found, please ' 'contact mne-python developers') # the following is equivalent to this, but faster: # # >>> data = read_tag(raw.fid, raw.data_tag.pos).data.astype(float) # >>> data *= raw.cals[np.newaxis, :, :] # >>> data = data[idx] # # Eventually this could be refactored in io/tag.py if other functions # could make use of it raw.fid.seek(raw.data_tag.pos + offset, 0) if fmt == '>c8': read_fmt = '>f4' elif fmt == '>c16': read_fmt = '>f8' else: read_fmt = fmt data = np.frombuffer(raw.fid.read(size), read_fmt) if read_fmt != fmt: data = data.view(fmt) data = data.astype(np.complex128) else: data = data.astype(np.float64) data.shape = raw.epoch_shape data *= raw.cals return data @fill_doc def bootstrap(epochs, random_state=None): """Compute epochs selected by bootstrapping. Parameters ---------- epochs : Epochs instance epochs data to be bootstrapped %(random_state)s Returns ------- epochs : Epochs instance The bootstrap samples """ if not epochs.preload: raise RuntimeError('Modifying data of epochs is only supported ' 'when preloading is used. Use preload=True ' 'in the constructor.') rng = check_random_state(random_state) epochs_bootstrap = epochs.copy() n_events = len(epochs_bootstrap.events) idx = rng_uniform(rng)(0, n_events, n_events) epochs_bootstrap = epochs_bootstrap[idx] return epochs_bootstrap def _check_merge_epochs(epochs_list): """Aux function.""" if len({tuple(epochs.event_id.items()) for epochs in epochs_list}) != 1: raise NotImplementedError("Epochs with unequal values for event_id") if len({epochs.tmin for epochs in epochs_list}) != 1: raise NotImplementedError("Epochs with unequal values for tmin") if len({epochs.tmax for epochs in epochs_list}) != 1: raise NotImplementedError("Epochs with unequal values for tmax") if len({epochs.baseline for epochs in epochs_list}) != 1: raise NotImplementedError("Epochs with unequal values for baseline") @verbose def add_channels_epochs(epochs_list, verbose=None): """Concatenate channels, info and data from two Epochs objects. Parameters ---------- epochs_list : list of Epochs Epochs object to concatenate. %(verbose)s Defaults to True if any of the input epochs have verbose=True. Returns ------- epochs : instance of Epochs Concatenated epochs. """ if not all(e.preload for e in epochs_list): raise ValueError('All epochs must be preloaded.') info = _merge_info([epochs.info for epochs in epochs_list]) data = [epochs._data for epochs in epochs_list] _check_merge_epochs(epochs_list) for d in data: if len(d) != len(data[0]): raise ValueError('all epochs must be of the same length') data = np.concatenate(data, axis=1) if len(info['chs']) != data.shape[1]: err = "Data shape does not match channel number in measurement info" raise RuntimeError(err) events = epochs_list[0].events.copy() all_same = all(np.array_equal(events, epochs.events) for epochs in epochs_list[1:]) if not all_same: raise ValueError('Events must be the same.') proj = any(e.proj for e in epochs_list) epochs = epochs_list[0].copy() epochs.info = info epochs.picks = None epochs.events = events epochs.preload = True epochs._bad_dropped = True epochs._data = data epochs._projector, epochs.info = setup_proj(epochs.info, False, activate=proj) return epochs def _concatenate_epochs(epochs_list, with_data=True, add_offset=True, *, on_mismatch='raise'): """Auxiliary function for concatenating epochs.""" if not isinstance(epochs_list, (list, tuple)): raise TypeError('epochs_list must be a list or tuple, got %s' % (type(epochs_list),)) # to make warning messages only occur once during concatenation warned = False for ei, epochs in enumerate(epochs_list): if not isinstance(epochs, BaseEpochs): raise TypeError('epochs_list[%d] must be an instance of Epochs, ' 'got %s' % (ei, type(epochs))) if (getattr(epochs, 'annotations', None) is not None and len(epochs.annotations) > 0 and not warned): warned = True warn('Concatenation of Annotations within Epochs is not supported ' 'yet. All annotations will be dropped.') # create a copy, so that the Annotations are not modified in place # from the original object epochs = epochs.copy() epochs.set_annotations(None) out = epochs_list[0] offsets = [0] if with_data: out.drop_bad() offsets.append(len(out)) events = [out.events] metadata = [out.metadata] baseline, tmin, tmax = out.baseline, out.tmin, out.tmax raw_sfreq = out._raw_sfreq info = deepcopy(out.info) drop_log = out.drop_log event_id = deepcopy(out.event_id) selection = out.selection # offset is the last epoch + tmax + 10 second shift = int((10 + tmax) * out.info['sfreq']) events_offset = int(np.max(events[0][:, 0])) + shift events_overflow = False warned = False for ii, epochs in enumerate(epochs_list[1:], 1): _ensure_infos_match(epochs.info, info, f'epochs[{ii}]', on_mismatch=on_mismatch) if not np.allclose(epochs.times, epochs_list[0].times): raise ValueError('Epochs must have same times') if epochs.baseline != baseline: raise ValueError('Baseline must be same for all epochs') if epochs._raw_sfreq != raw_sfreq and not warned: warned = True warn('The original raw sampling rate of the Epochs does not ' 'match for all Epochs. Please proceed cautiously.') # compare event_id common_keys = list(set(event_id).intersection(set(epochs.event_id))) for key in common_keys: if not event_id[key] == epochs.event_id[key]: msg = ('event_id values must be the same for identical keys ' 'for all concatenated epochs. Key "{}" maps to {} in ' 'some epochs and to {} in others.') raise ValueError(msg.format(key, event_id[key], epochs.event_id[key])) if with_data: epochs.drop_bad() offsets.append(len(epochs)) evs = epochs.events.copy() if len(epochs.events) == 0: warn('One of the Epochs objects to concatenate was empty.') elif add_offset: # We need to cast to a native Python int here to detect an # overflow of a numpy int32 (which is the default on windows) max_timestamp = int(np.max(evs[:, 0])) evs[:, 0] += events_offset events_offset += max_timestamp + shift if events_offset > INT32_MAX: warn(f'Event number greater than {INT32_MAX} created, ' 'events[:, 0] will be assigned consecutive increasing ' 'integer values') events_overflow = True add_offset = False # we no longer need to add offset events.append(evs) selection = np.concatenate((selection, epochs.selection)) drop_log = drop_log + epochs.drop_log event_id.update(epochs.event_id) metadata.append(epochs.metadata) events = np.concatenate(events, axis=0) # check to see if we exceeded our maximum event offset if events_overflow: events[:, 0] = np.arange(1, len(events) + 1) # Create metadata object (or make it None) n_have = sum(this_meta is not None for this_meta in metadata) if n_have == 0: metadata = None elif n_have != len(metadata): raise ValueError('%d of %d epochs instances have metadata, either ' 'all or none must have metadata' % (n_have, len(metadata))) else: pd = _check_pandas_installed(strict=False) if pd is not False: metadata = pd.concat(metadata) else: # dict of dicts metadata = sum(metadata, list()) assert len(offsets) == (len(epochs_list) if with_data else 0) + 1 data = None if with_data: offsets = np.cumsum(offsets) for start, stop, epochs in zip(offsets[:-1], offsets[1:], epochs_list): this_data = epochs.get_data() if data is None: data = np.empty( (offsets[-1], len(out.ch_names), len(out.times)), dtype=this_data.dtype) data[start:stop] = this_data return (info, data, raw_sfreq, events, event_id, tmin, tmax, metadata, baseline, selection, drop_log) def _finish_concat(info, data, raw_sfreq, events, event_id, tmin, tmax, metadata, baseline, selection, drop_log): """Finish concatenation for epochs not read from disk.""" selection = np.where([len(d) == 0 for d in drop_log])[0] out = BaseEpochs( info, data, events, event_id, tmin, tmax, baseline=baseline, selection=selection, drop_log=drop_log, proj=False, on_missing='ignore', metadata=metadata, raw_sfreq=raw_sfreq) out.drop_bad() return out @verbose def concatenate_epochs(epochs_list, add_offset=True, *, on_mismatch='raise', verbose=None): """Concatenate a list of `~mne.Epochs` into one `~mne.Epochs` object. .. note:: Unlike `~mne.concatenate_raws`, this function does **not** modify any of the input data. Parameters ---------- epochs_list : list List of `~mne.Epochs` instances to concatenate (in that order). add_offset : bool If True, a fixed offset is added to the event times from different Epochs sets, such that they are easy to distinguish after the concatenation. If False, the event times are unaltered during the concatenation. %(on_info_mismatch)s %(verbose)s .. versionadded:: 0.24 Returns ------- epochs : instance of Epochs The result of the concatenation. Notes ----- .. versionadded:: 0.9.0 """ return _finish_concat(*_concatenate_epochs(epochs_list, add_offset=add_offset, on_mismatch=on_mismatch)) @verbose def average_movements(epochs, head_pos=None, orig_sfreq=None, picks=None, origin='auto', weight_all=True, int_order=8, ext_order=3, destination=None, ignore_ref=False, return_mapping=False, mag_scale=100., verbose=None): """Average data using Maxwell filtering, transforming using head positions. Parameters ---------- epochs : instance of Epochs The epochs to operate on. %(maxwell_pos)s orig_sfreq : float | None The original sample frequency of the data (that matches the event sample numbers in ``epochs.events``). Can be ``None`` if data have not been decimated or resampled. %(picks_all_data)s %(maxwell_origin)s weight_all : bool If True, all channels are weighted by the SSS basis weights. If False, only MEG channels are weighted, other channels receive uniform weight per epoch. %(maxwell_int)s %(maxwell_ext)s %(maxwell_dest)s %(maxwell_ref)s return_mapping : bool If True, return the mapping matrix. %(maxwell_mag)s .. versionadded:: 0.13 %(verbose)s Returns ------- evoked : instance of Evoked The averaged epochs. See Also -------- mne.preprocessing.maxwell_filter mne.chpi.read_head_pos Notes ----- The Maxwell filtering version of this algorithm is described in [1]_, in section V.B "Virtual signals and movement correction", equations 40-44. For additional validation, see [2]_. Regularization has not been added because in testing it appears to decrease dipole localization accuracy relative to using all components. Fine calibration and cross-talk cancellation, however, could be added to this algorithm based on user demand. .. versionadded:: 0.11 References ---------- .. [1] Taulu S. and Kajola M. "Presentation of electromagnetic multichannel data: The signal space separation method," Journal of Applied Physics, vol. 97, pp. 124905 1-10, 2005. .. [2] Wehner DT, Hämäläinen MS, Mody M, Ahlfors SP. "Head movements of children in MEG: Quantification, effects on source estimation, and compensation. NeuroImage 40:541–550, 2008. """ # noqa: E501 from .preprocessing.maxwell import (_trans_sss_basis, _reset_meg_bads, _check_usable, _col_norm_pinv, _get_n_moments, _get_mf_picks_fix_mags, _prep_mf_coils, _check_destination, _remove_meg_projs, _get_coil_scale) if head_pos is None: raise TypeError('head_pos must be provided and cannot be None') from .chpi import head_pos_to_trans_rot_t if not isinstance(epochs, BaseEpochs): raise TypeError('epochs must be an instance of Epochs, not %s' % (type(epochs),)) orig_sfreq = epochs.info['sfreq'] if orig_sfreq is None else orig_sfreq orig_sfreq = float(orig_sfreq) if isinstance(head_pos, np.ndarray): head_pos = head_pos_to_trans_rot_t(head_pos) trn, rot, t = head_pos del head_pos _check_usable(epochs) origin = _check_origin(origin, epochs.info, 'head') recon_trans = _check_destination(destination, epochs.info, True) logger.info('Aligning and averaging up to %s epochs' % (len(epochs.events))) if not np.array_equal(epochs.events[:, 0], np.unique(epochs.events[:, 0])): raise RuntimeError('Epochs must have monotonically increasing events') info_to = epochs.info.copy() meg_picks, mag_picks, grad_picks, good_mask, _ = \ _get_mf_picks_fix_mags(info_to, int_order, ext_order, ignore_ref) coil_scale, mag_scale = _get_coil_scale( meg_picks, mag_picks, grad_picks, mag_scale, info_to) n_channels, n_times = len(epochs.ch_names), len(epochs.times) other_picks = np.setdiff1d(np.arange(n_channels), meg_picks) data = np.zeros((n_channels, n_times)) count = 0 # keep only MEG w/bad channels marked in "info_from" info_from = pick_info(info_to, meg_picks[good_mask], copy=True) all_coils_recon = _prep_mf_coils(info_to, ignore_ref=ignore_ref) all_coils = _prep_mf_coils(info_from, ignore_ref=ignore_ref) # remove MEG bads in "to" info _reset_meg_bads(info_to) # set up variables w_sum = 0. n_in, n_out = _get_n_moments([int_order, ext_order]) S_decomp = 0. # this will end up being a weighted average last_trans = None decomp_coil_scale = coil_scale[good_mask] exp = dict(int_order=int_order, ext_order=ext_order, head_frame=True, origin=origin) n_in = _get_n_moments(int_order) for ei, epoch in enumerate(epochs): event_time = epochs.events[epochs._current - 1, 0] / orig_sfreq use_idx = np.where(t <= event_time)[0] if len(use_idx) == 0: trans = info_to['dev_head_t']['trans'] else: use_idx = use_idx[-1] trans = np.vstack([np.hstack([rot[use_idx], trn[[use_idx]].T]), [[0., 0., 0., 1.]]]) loc_str = ', '.join('%0.1f' % tr for tr in (trans[:3, 3] * 1000)) if last_trans is None or not np.allclose(last_trans, trans): logger.info(' Processing epoch %s (device location: %s mm)' % (ei + 1, loc_str)) reuse = False last_trans = trans else: logger.info(' Processing epoch %s (device location: same)' % (ei + 1,)) reuse = True epoch = epoch.copy() # because we operate inplace if not reuse: S = _trans_sss_basis(exp, all_coils, trans, coil_scale=decomp_coil_scale) # Get the weight from the un-regularized version (eq. 44) weight = np.linalg.norm(S[:, :n_in]) # XXX Eventually we could do cross-talk and fine-cal here S *= weight S_decomp += S # eq. 41 epoch[slice(None) if weight_all else meg_picks] *= weight data += epoch # eq. 42 w_sum += weight count += 1 del info_from mapping = None if count == 0: data.fill(np.nan) else: data[meg_picks] /= w_sum data[other_picks] /= w_sum if weight_all else count # Finalize weighted average decomp matrix S_decomp /= w_sum # Get recon matrix # (We would need to include external here for regularization to work) exp['ext_order'] = 0 S_recon = _trans_sss_basis(exp, all_coils_recon, recon_trans) exp['ext_order'] = ext_order # We could determine regularization on basis of destination basis # matrix, restricted to good channels, as regularizing individual # matrices within the loop above does not seem to work. But in # testing this seemed to decrease localization quality in most cases, # so we do not provide the option here. S_recon /= coil_scale # Invert pS_ave = _col_norm_pinv(S_decomp)[0][:n_in] pS_ave *= decomp_coil_scale.T # Get mapping matrix mapping = np.dot(S_recon, pS_ave) # Apply mapping data[meg_picks] = np.dot(mapping, data[meg_picks[good_mask]]) info_to['dev_head_t'] = recon_trans # set the reconstruction transform evoked = epochs._evoked_from_epoch_data(data, info_to, picks, n_events=count, kind='average', comment=epochs._name) _remove_meg_projs(evoked) # remove MEG projectors, they won't apply now logger.info('Created Evoked dataset from %s epochs' % (count,)) return (evoked, mapping) if return_mapping else evoked @verbose def make_fixed_length_epochs(raw, duration=1., preload=False, reject_by_annotation=True, proj=True, overlap=0., id=1, verbose=None): """Divide continuous raw data into equal-sized consecutive epochs. Parameters ---------- raw : instance of Raw Raw data to divide into segments. duration : float Duration of each epoch in seconds. Defaults to 1. %(preload)s %(reject_by_annotation_epochs)s .. versionadded:: 0.21.0 %(proj_epochs)s .. versionadded:: 0.22.0 overlap : float The overlap between epochs, in seconds. Must be ``0 <= overlap < duration``. Default is 0, i.e., no overlap. .. versionadded:: 0.23.0 id : int The id to use (default 1). .. versionadded:: 0.24.0 %(verbose)s Returns ------- epochs : instance of Epochs Segmented data. Notes ----- .. versionadded:: 0.20 """ events = make_fixed_length_events(raw, id=id, duration=duration, overlap=overlap) delta = 1. / raw.info['sfreq'] return Epochs(raw, events, event_id=[id], tmin=0, tmax=duration - delta, baseline=None, preload=preload, reject_by_annotation=reject_by_annotation, proj=proj, verbose=verbose)
import collections.abc import warnings from abc import abstractmethod from collections import defaultdict from datetime import datetime from enum import Enum, EnumMeta from textwrap import dedent from typing import Any, Callable, Dict, Mapping, Optional, Set, Tuple, Union from urllib.parse import urlencode import ciso8601 from ruamel.yaml.timestamp import TimeStamp as RuamelTimeStamp from eodatasets3.utils import default_utc class FileFormat(Enum): GeoTIFF = 1 NetCDF = 2 Zarr = 3 JPEG2000 = 4 def nest_properties(d: Mapping[str, Any], separator=":") -> Dict[str, Any]: """ Split keys with embedded colons into sub dictionaries. Intended for stac-like properties >>> nest_properties({'landsat:path':1, 'landsat:row':2, 'clouds':3}) {'landsat': {'path': 1, 'row': 2}, 'clouds': 3} """ out = defaultdict(dict) for key, val in d.items(): section, *remainder = key.split(separator, 1) if remainder: [sub_key] = remainder out[section][sub_key] = val else: out[section] = val for key, val in out.items(): if isinstance(val, dict): out[key] = nest_properties(val, separator=separator) return dict(out) def datetime_type(value): # Ruamel's TimeZone class can become invalid from the .replace(utc) call. # (I think it no longer matches the internal ._yaml fields.) # Convert to a regular datetime. if isinstance(value, RuamelTimeStamp): value = value.isoformat() if isinstance(value, str): value = ciso8601.parse_datetime(value) # Store all dates with a timezone. # yaml standard says all dates default to UTC. # (and ruamel normalises timezones to UTC itself) return default_utc(value) def of_enum_type( vals: Union[EnumMeta, Tuple[str, ...]] = None, lower=False, upper=False, strict=True ) -> Callable[[str], str]: if isinstance(vals, EnumMeta): vals = tuple(vals.__members__.keys()) def normalise(v: str): if isinstance(v, Enum): v = v.name if upper: v = v.upper() if lower: v = v.lower() if v not in vals: msg = f"Unexpected value {v!r}. Expected one of: {", ".join(vals)}," if strict: raise ValueError(msg) else: warnings.warn(msg) return v return normalise def percent_type(value): value = float(value) if not (0.0 <= value <= 100.0): raise ValueError("Expected percent between 0,100") return value def normalise_platforms(value: Union[str, list, set]): """ >>> normalise_platforms('LANDSAT_8') 'landsat-8' >>> # Multiple can be comma-separated. They're normalised independently and sorted. >>> normalise_platforms('LANDSAT_8,Landsat-5,landsat-7') 'landsat-5,landsat-7,landsat-8' >>> # Can be given as a list. >>> normalise_platforms(['sentinel-2b','SENTINEL-2a']) 'sentinel-2a,sentinel-2b' >>> # Deduplicated too >>> normalise_platforms('landsat-5,landsat-5,LANDSAT-5') 'landsat-5' """ if not isinstance(value, (list, set, tuple)): value = value.split(",") platforms = sorted({s.strip().lower().replace("_", "-") for s in value if s}) if not platforms: return None return ",".join(platforms) def degrees_type(value): value = float(value) if not (-360.0 <= value <= 360.0): raise ValueError("Expected degrees between -360,+360") return value def identifier_type(v: str): v = v.replace("-", "_") if not v.isidentifier() or not v.islower(): warnings.warn( f"{v!r} is expected to be an identifier " "(alphanumeric with underscores, typically lowercase)" ) return v def producer_check(value): if "." not in value: warnings.warn( "Property 'odc:producer' is expected to be a domain name, " "eg 'usgs.gov' or 'ga.gov.au'" ) return value def parsed_sentinel_tile_id(tile_id) -> Tuple[str, Dict]: """Extract useful extra fields from a sentinel tile id >>> val, props = parsed_sentinel_tile_id("S2B_OPER_MSI_L1C_TL_EPAE_20201011T011446_A018789_T55HFA_N02.09") >>> val 'S2B_OPER_MSI_L1C_TL_EPAE_20201011T011446_A018789_T55HFA_N02.09' >>> props {'sentinel:datatake_start_datetime': datetime.datetime(2020, 10, 11, 1, 14, 46, tzinfo=datetime.timezone.utc)} """ extras = {} split_tile_id = tile_id.split("_") try: datatake_sensing_time = datetime_type(split_tile_id[-4]) extras["sentinel:datatake_start_datetime"] = datatake_sensing_time except IndexError: pass # TODO: we could extract other useful fields? return tile_id, extras def parsed_sentinel_datastrip_id(tile_id) -> Tuple[str, Dict]: """Extract useful extra fields from a sentinel datastrip id >>> val, props = parsed_sentinel_datastrip_id("S2B_OPER_MSI_L1C_DS_EPAE_20201011T011446_S20201011T000244_N02.09") >>> val 'S2B_OPER_MSI_L1C_DS_EPAE_20201011T011446_S20201011T000244_N02.09' >>> props {'sentinel:datatake_start_datetime': datetime.datetime(2020, 10, 11, 1, 14, 46, tzinfo=datetime.timezone.utc)} """ extras = {} split_tile_id = tile_id.split("_") try: datatake_sensing_time = datetime_type(split_tile_id[-3]) extras["sentinel:datatake_start_datetime"] = datatake_sensing_time except IndexError: pass # TODO: we could extract other useful fields? return tile_id, extras # The primitive types allowed as stac values. PrimitiveType = Union[str, int, float, datetime] ExtraProperties = Dict # A function to normalise a value. # (eg. convert to int, or make string lowercase). # They throw a ValueError if not valid. NormaliseValueFn = Callable[ [Any], # It returns the normalised value, but can optionally also return extra property values extracted from it. Union[PrimitiveType, Tuple[PrimitiveType, ExtraProperties]], ] # Extras typically on the ARD product. _GQA_FMASK_PROPS = { "fmask:clear": float, "fmask:cloud": float, "fmask:cloud_shadow": float, "fmask:snow": float, "fmask:water": float, "gqa:abs_iterative_mean_x": float, "gqa:abs_iterative_mean_xy": float, "gqa:abs_iterative_mean_y": float, "gqa:abs_x": float, "gqa:abs_xy": float, "gqa:abs_y": float, "gqa:cep90": float, "gqa:error_message": None, "gqa:final_gcp_count": int, "gqa:iterative_mean_x": float, "gqa:iterative_mean_xy": float, "gqa:iterative_mean_y": float, "gqa:iterative_stddev_x": float, "gqa:iterative_stddev_xy": float, "gqa:iterative_stddev_y": float, "gqa:mean_x": float, "gqa:mean_xy": float, "gqa:mean_y": float, "gqa:ref_source": None, "gqa:stddev_x": float, "gqa:stddev_xy": float, "gqa:stddev_y": float, } # Typically only from LPGS (ie. Level 1 products) _LANDSAT_EXTENDED_PROPS = { "landsat:algorithm_source_surface_reflectance": None, "landsat:collection_category": None, "landsat:collection_number": int, "landsat:data_type": None, "landsat:earth_sun_distance": None, "landsat:ephemeris_type": None, "landsat:geometric_rmse_model": None, "landsat:geometric_rmse_model_x": None, "landsat:geometric_rmse_model_y": None, "landsat:geometric_rmse_verify": None, "landsat:ground_control_points_model": None, "landsat:ground_control_points_verify": None, "landsat:ground_control_points_version": None, "landsat:image_quality_oli": None, "landsat:image_quality_tirs": None, "landsat:processing_software_version": None, "landsat:scan_gap_interpolation": float, "landsat:station_id": None, # Landsat USGS Properties "landsat:rmse": None, "landsat:rmse_x": None, "landsat:rmse_y": None, "landsat:wrs_type": None, "landsat:correction": None, "landsat:cloud_cover_land": None, } _SENTINEL_EXTENDED_PROPS = { "sentinel:sentinel_tile_id": parsed_sentinel_tile_id, "sentinel:datatake_start_datetime": datetime_type, "sentinel:datastrip_id": parsed_sentinel_datastrip_id, "sentinel:datatake_type": None, "sentinel:processing_baseline": None, "sentinel:processing_center": None, "sentinel:product_name": None, "sentinel:reception_station": None, "sentinel:utm_zone": int, "sentinel:latitude_band": None, "sentinel:grid_square": None, "sinergise_product_id": None, } _STAC_MISC_PROPS = { "providers": None, # https://github.com/radiantearth/stac-spec/blob/master/item-spec/common-metadata.md#provider, # Projection extension "proj:epsg": int, "proj:shape": None, "proj:transform": None, } class Eo3Dict(collections.abc.MutableMapping): """ This acts like a dictionary, but will normalise known properties (consistent case, types etc) and warn about common mistakes. It wraps an inner dictionary. By default it will normalise the fields in the input dictionary on creation, but you can disable this with `normalise_input=False`. """ # Every property we've seen or dealt with so far. Feel free to expand with abandon... # This is to minimise minor typos, case differences, etc, which plagued previous systems. # Keep sorted. KNOWN_PROPERTIES: Mapping[str, Optional[NormaliseValueFn]] = { "datetime": datetime_type, "dea:dataset_maturity": of_enum_type(("final", "interim", "nrt"), lower=True), "dea:product_maturity": of_enum_type(("stable", "provisional"), lower=True), "dtr:end_datetime": datetime_type, "dtr:start_datetime": datetime_type, "eo:azimuth": float, "eo:cloud_cover": percent_type, "eo:epsg": None, "eo:gsd": None, "eo:instrument": None, "eo:off_nadir": float, "eo:platform": normalise_platforms, "eo:constellation": None, "eo:sun_azimuth": degrees_type, "eo:sun_elevation": degrees_type, "sat:orbit_state": None, "sat:relative_orbit": int, "sat:absolute_orbit": int, "landsat:landsat_product_id": None, "landsat:scene_id": None, "landsat:landsat_scene_id": None, "landsat:wrs_path": int, "landsat:wrs_row": int, "odc:dataset_version": None, "odc:collection_number": int, "odc:naming_conventions": None, # Not strict as there may be more added in ODC... "odc:file_format": of_enum_type(FileFormat, strict=False), "odc:processing_datetime": datetime_type, "odc:producer": producer_check, "odc:product": None, "odc:product_family": identifier_type, "odc:region_code": None, **_LANDSAT_EXTENDED_PROPS, **_GQA_FMASK_PROPS, **_SENTINEL_EXTENDED_PROPS, **_STAC_MISC_PROPS, } # For backwards compatibility, in case users are extending at runtime. KNOWN_STAC_PROPERTIES = KNOWN_PROPERTIES def __init__(self, properties: Mapping = None, normalise_input=True) -> None: if properties is None: properties = {} self._props = properties # We normalise the properties they gave us. for key in list(self._props): # We always want to normalise dates as datetime objects rather than strings # for consistency. if normalise_input or ("datetime" in key): self.normalise_and_set(key, self._props[key], expect_override=True) self._finished_init_ = True def __setattr__(self, name: str, value: Any) -> None: """ Prevent against users accidentally setting new properties (it has happened multiple times). """ if hasattr(self, "_finished_init_") and not hasattr(self, name): raise TypeError( f"Cannot set new field '{name}' on a dict. " f"(Perhaps you meant to set it as a dictionary field??)" ) super().__setattr__(name, value) def __getitem__(self, item): return self._props[item] def __iter__(self): return iter(self._props) def __len__(self): return len(self._props) def __delitem__(self, name: str) -> None: del self._props[name] def __repr__(self) -> str: return f"{self.__class__.__name__}({self._props!r})" def __setitem__(self, key, value): self.normalise_and_set( key, value, # They can override properties but will receive a warning. allow_override=True, ) def normalise_and_set(self, key, value, allow_override=True, expect_override=False): """ Set a property with the usual normalisation. This has some options that are not available on normal dictionary item setting (``self[key] = val``) The default behaviour of this class is very conservative in order to catch common errors of users. You can loosen the settings here. :argument allow_override: Is it okay to overwrite an existing value? (if not, error will be thrown) :argument expect_override: We expect to overwrite a property, so don't produce a warning or error. """ if key not in self.KNOWN_PROPERTIES: warnings.warn( f"Unknown Stac property {key!r}. " f"If this is valid property, please tell us on Github here so we can add it: " f"\n\t{_github_suggest_new_property_url(key, value)}" ) if value is not None: normalise = self.KNOWN_PROPERTIES.get(key) if normalise: value = normalise(value) # If the normaliser has extracted extra properties, we'll get two return values. if isinstance(value, Tuple): value, extra_properties = value for k, v in extra_properties.items(): if k == key: raise RuntimeError( f"Infinite loop: writing key {k!r} from itself" ) self.normalise_and_set(k, v, allow_override=allow_override) if key in self._props and value != self[key] and (not expect_override): message = ( f"Overriding property {key!r} " f"(from {self[key]!r} to {value!r})" ) if allow_override: warnings.warn(message, category=PropertyOverrideWarning) else: raise KeyError(message) self._props[key] = value def nested(self): return nest_properties(self._props) class StacPropertyView(Eo3Dict): """ Backwards compatibility class name. Deprecated. Use the identical 'Eo3Dict' instead. These were called "StacProperties" in Stac 0.6, but many of them have changed in newer versions and we're sticking to the old names for consistency and backwards-compatibility. So they're now EO3 Properties. (The eo3-to-stac tool to convert EO3 properties to real Stac properties.) """ def __init__(self, properties=None) -> None: super().__init__(properties) warnings.warn( "The class name 'StacPropertyView' is deprecated as it's misleading. " "Please change your import to the (identical) 'Eo3Dict'.", category=DeprecationWarning, ) class PropertyOverrideWarning(UserWarning): """A warning that a property was set twice with different values.""" ... class Eo3Interface: """ These are convenience properties for common metadata fields. They are available on DatasetAssemblers and within other naming APIs. (This is abstract. If you want one of these of your own, you probably want to create an :class:`eodatasets3.DatasetDoc`) """ @property @abstractmethod def properties(self) -> Eo3Dict: raise NotImplementedError @property def platform(self) -> Optional[str]: """ Unique name of the specific platform the instrument is attached to. For satellites this would be the name of the satellite (e.g., ``landsat-8``, ``sentinel-2a``), whereas for drones this would be a unique name for the drone. In derivative products, multiple platforms can be specified with a comma: ``landsat-5,landsat-7``. Shorthand for ``eo:platform`` property """ return self.properties.get("eo:platform") @platform.setter def platform(self, value: str): self.properties["eo:platform"] = value @property def platforms(self) -> Set[str]: """ Get platform as a set (containing zero or more items). In EO3, multiple platforms are specified by comma-separating them. """ if not self.platform: return set() return set(self.properties.get("eo:platform", "").split(",")) @platforms.setter def platforms(self, value: Set[str]): # The normaliser supports sets/lists self.properties["eo:platform"] = value @property def instrument(self) -> str: """ Name of instrument or sensor used (e.g., MODIS, ASTER, OLI, Canon F-1). Shorthand for ``eo:instrument`` property """ return self.properties.get("eo:instrument") @instrument.setter def instrument(self, value: str): self.properties["eo:instrument"] = value @property def constellation(self) -> str: """ Constellation. Eg ``sentinel-2``. """ return self.properties.get("eo:constellation") @constellation.setter def constellation(self, value: str): self.properties["eo:constellation"] = value @property def product_name(self) -> Optional[str]: """ The ODC product name """ return self.properties.get("odc:product") @product_name.setter def product_name(self, value: str): self.properties["odc:product"] = value @property def producer(self) -> str: """ Organisation that produced the data. eg. ``usgs.gov`` or ``ga.gov.au`` Shorthand for ``odc:producer`` property """ return self.properties.get("odc:producer") @producer.setter def producer(self, domain: str): self.properties["odc:producer"] = domain @property def datetime_range(self) -> Tuple[datetime, datetime]: """ An optional date range for the dataset. The ``datetime`` is still mandatory when this is set. This field is a shorthand for reading/setting the datetime-range stac 0.6 extension properties: ``dtr:start_datetime`` and ``dtr:end_datetime`` """ return ( self.properties.get("dtr:start_datetime"), self.properties.get("dtr:end_datetime"), ) @datetime_range.setter def datetime_range(self, val: Tuple[datetime, datetime]): # TODO: string type conversion, better validation/errors start, end = val self.properties["dtr:start_datetime"] = start self.properties["dtr:end_datetime"] = end @property def processed(self) -> datetime: """When the dataset was created (Defaults to UTC if not specified) Shorthand for the ``odc:processing_datetime`` field """ return self.properties.get("odc:processing_datetime") @processed.setter def processed(self, value: Union[str, datetime]): self.properties["odc:processing_datetime"] = value def processed_now(self): """ Shorthand for when the dataset was processed right now on the current system. """ self.properties["odc:processing_datetime"] = datetime.utcnow() @property def dataset_version(self) -> str: """ The version of the dataset. Typically digits separated by a dot. Eg. `1.0.0` The first digit is usually the collection number for this 'producer' organisation, such as USGS Collection 1 or GA Collection 3. """ return self.properties.get("odc:dataset_version") @property def collection_number(self) -> int: """ The version of the collection. Eg.:: metadata: product_family: wofs dataset_version: 1.6.0 collection_number: 3 """ return self.properties.get("odc:collection_number") @dataset_version.setter def dataset_version(self, value): self.properties["odc:dataset_version"] = value @collection_number.setter def collection_number(self, value): self.properties["odc:collection_number"] = value @property def naming_conventions(self) -> str: return self.properties.get("odc:naming_conventions") @naming_conventions.setter def naming_conventions(self, value): self.properties["odc:naming_conventions"] = value @property def product_family(self) -> str: """ The identifier for this "family" of products, such as ``ard``, ``level1`` or ``fc``. It's used for grouping similar products together. They products in a family are usually produced the same way but have small variations: they come from different sensors, or are written in different projections, etc. ``ard`` family of products: ``ls7_ard``, ``ls5_ard`` .... On older versions of Open Data Cube this was called ``product_type``. Shorthand for ``odc:product_family`` property. """ return self.properties.get("odc:product_family") @product_family.setter def product_family(self, value): self.properties["odc:product_family"] = value @product_family.deleter def product_family(self): del self.properties["odc:product_family"] @property def region_code(self) -> Optional[str]: """ The "region" of acquisition. This is a platform-agnostic representation of things like the Landsat Path+Row. Datasets with the same Region Code will *roughly* (but usually not *exactly*) cover the same spatial footprint. It's generally treated as an opaque string to group datasets and process as stacks. For Landsat products it's the concatenated ``{path}{row}`` (both numbers formatted to three digits). For Sentinel 2, it's the MGRS grid (TODO presumably?). Shorthand for ``odc:region_code`` property. """ return self.properties.get("odc:region_code") @region_code.setter def region_code(self, value: str): self.properties["odc:region_code"] = value @property def maturity(self) -> str: """ The dataset maturity. The same data may be processed multiple times -- becoming more mature -- as new ancillary data becomes available. Typical values (from least to most mature): ``nrt`` (near real time), ``interim``, ``final`` """ return self.properties.get("dea:dataset_maturity") @maturity.setter def maturity(self, value): self.properties["dea:dataset_maturity"] = value @property def product_maturity(self) -> str: """ Classification: is this a 'provisional' or 'stable' release of the product? """ return self.properties.get("dea:product_maturity") @product_maturity.setter def product_maturity(self, value): self.properties["dea:product_maturity"] = value # Note that giving a method the name 'datetime' will override the 'datetime' type # for class-level declarations (ie, for any types on functions!) # So we make an alias: from datetime import datetime as datetime_ @property def datetime(self) -> datetime_: """ The searchable date and time of the assets. (Default to UTC if not specified) """ return self.properties.get("datetime") @datetime.setter def datetime(self, val: datetime_): self.properties["datetime"] = val def _github_suggest_new_property_url(key: str, value: object) -> str: """Get a URL to create a Github issue suggesting new properties to be added.""" issue_parameters = urlencode( dict( title=f"Include property {key!r}", labels="known-properties", body=dedent( f"""\ Hello! The property {key!r} does not appear to be in the KNOWN_STAC_PROPERTIES list, but I believe it to be valid. An example value of this property is: {value!r} Thank you! """ ), ) ) return f"https://github.com/GeoscienceAustralia/eo-datasets/issues/new?{issue_parameters}"
import collections.abc import warnings from abc import abstractmethod from collections import defaultdict from datetime import datetime from enum import Enum, EnumMeta from textwrap import dedent from typing import Any, Callable, Dict, Mapping, Optional, Set, Tuple, Union from urllib.parse import urlencode import ciso8601 from ruamel.yaml.timestamp import TimeStamp as RuamelTimeStamp from eodatasets3.utils import default_utc class FileFormat(Enum): GeoTIFF = 1 NetCDF = 2 Zarr = 3 JPEG2000 = 4 def nest_properties(d: Mapping[str, Any], separator=":") -> Dict[str, Any]: """ Split keys with embedded colons into sub dictionaries. Intended for stac-like properties >>> nest_properties({'landsat:path':1, 'landsat:row':2, 'clouds':3}) {'landsat': {'path': 1, 'row': 2}, 'clouds': 3} """ out = defaultdict(dict) for key, val in d.items(): section, *remainder = key.split(separator, 1) if remainder: [sub_key] = remainder out[section][sub_key] = val else: out[section] = val for key, val in out.items(): if isinstance(val, dict): out[key] = nest_properties(val, separator=separator) return dict(out) def datetime_type(value): # Ruamel's TimeZone class can become invalid from the .replace(utc) call. # (I think it no longer matches the internal ._yaml fields.) # Convert to a regular datetime. if isinstance(value, RuamelTimeStamp): value = value.isoformat() if isinstance(value, str): value = ciso8601.parse_datetime(value) # Store all dates with a timezone. # yaml standard says all dates default to UTC. # (and ruamel normalises timezones to UTC itself) return default_utc(value) def of_enum_type( vals: Union[EnumMeta, Tuple[str, ...]] = None, lower=False, upper=False, strict=True ) -> Callable[[str], str]: if isinstance(vals, EnumMeta): vals = tuple(vals.__members__.keys()) def normalise(v: str): if isinstance(v, Enum): v = v.name if upper: v = v.upper() if lower: v = v.lower() if v not in vals: msg = f"Unexpected value {v!r}. Expected one of: {', '.join(vals)}," if strict: raise ValueError(msg) else: warnings.warn(msg) return v return normalise def percent_type(value): value = float(value) if not (0.0 <= value <= 100.0): raise ValueError("Expected percent between 0,100") return value def normalise_platforms(value: Union[str, list, set]): """ >>> normalise_platforms('LANDSAT_8') 'landsat-8' >>> # Multiple can be comma-separated. They're normalised independently and sorted. >>> normalise_platforms('LANDSAT_8,Landsat-5,landsat-7') 'landsat-5,landsat-7,landsat-8' >>> # Can be given as a list. >>> normalise_platforms(['sentinel-2b','SENTINEL-2a']) 'sentinel-2a,sentinel-2b' >>> # Deduplicated too >>> normalise_platforms('landsat-5,landsat-5,LANDSAT-5') 'landsat-5' """ if not isinstance(value, (list, set, tuple)): value = value.split(",") platforms = sorted({s.strip().lower().replace("_", "-") for s in value if s}) if not platforms: return None return ",".join(platforms) def degrees_type(value): value = float(value) if not (-360.0 <= value <= 360.0): raise ValueError("Expected degrees between -360,+360") return value def identifier_type(v: str): v = v.replace("-", "_") if not v.isidentifier() or not v.islower(): warnings.warn( f"{v!r} is expected to be an identifier " "(alphanumeric with underscores, typically lowercase)" ) return v def producer_check(value): if "." not in value: warnings.warn( "Property 'odc:producer' is expected to be a domain name, " "eg 'usgs.gov' or 'ga.gov.au'" ) return value def parsed_sentinel_tile_id(tile_id) -> Tuple[str, Dict]: """Extract useful extra fields from a sentinel tile id >>> val, props = parsed_sentinel_tile_id("S2B_OPER_MSI_L1C_TL_EPAE_20201011T011446_A018789_T55HFA_N02.09") >>> val 'S2B_OPER_MSI_L1C_TL_EPAE_20201011T011446_A018789_T55HFA_N02.09' >>> props {'sentinel:datatake_start_datetime': datetime.datetime(2020, 10, 11, 1, 14, 46, tzinfo=datetime.timezone.utc)} """ extras = {} split_tile_id = tile_id.split("_") try: datatake_sensing_time = datetime_type(split_tile_id[-4]) extras["sentinel:datatake_start_datetime"] = datatake_sensing_time except IndexError: pass # TODO: we could extract other useful fields? return tile_id, extras def parsed_sentinel_datastrip_id(tile_id) -> Tuple[str, Dict]: """Extract useful extra fields from a sentinel datastrip id >>> val, props = parsed_sentinel_datastrip_id("S2B_OPER_MSI_L1C_DS_EPAE_20201011T011446_S20201011T000244_N02.09") >>> val 'S2B_OPER_MSI_L1C_DS_EPAE_20201011T011446_S20201011T000244_N02.09' >>> props {'sentinel:datatake_start_datetime': datetime.datetime(2020, 10, 11, 1, 14, 46, tzinfo=datetime.timezone.utc)} """ extras = {} split_tile_id = tile_id.split("_") try: datatake_sensing_time = datetime_type(split_tile_id[-3]) extras["sentinel:datatake_start_datetime"] = datatake_sensing_time except IndexError: pass # TODO: we could extract other useful fields? return tile_id, extras # The primitive types allowed as stac values. PrimitiveType = Union[str, int, float, datetime] ExtraProperties = Dict # A function to normalise a value. # (eg. convert to int, or make string lowercase). # They throw a ValueError if not valid. NormaliseValueFn = Callable[ [Any], # It returns the normalised value, but can optionally also return extra property values extracted from it. Union[PrimitiveType, Tuple[PrimitiveType, ExtraProperties]], ] # Extras typically on the ARD product. _GQA_FMASK_PROPS = { "fmask:clear": float, "fmask:cloud": float, "fmask:cloud_shadow": float, "fmask:snow": float, "fmask:water": float, "gqa:abs_iterative_mean_x": float, "gqa:abs_iterative_mean_xy": float, "gqa:abs_iterative_mean_y": float, "gqa:abs_x": float, "gqa:abs_xy": float, "gqa:abs_y": float, "gqa:cep90": float, "gqa:error_message": None, "gqa:final_gcp_count": int, "gqa:iterative_mean_x": float, "gqa:iterative_mean_xy": float, "gqa:iterative_mean_y": float, "gqa:iterative_stddev_x": float, "gqa:iterative_stddev_xy": float, "gqa:iterative_stddev_y": float, "gqa:mean_x": float, "gqa:mean_xy": float, "gqa:mean_y": float, "gqa:ref_source": None, "gqa:stddev_x": float, "gqa:stddev_xy": float, "gqa:stddev_y": float, } # Typically only from LPGS (ie. Level 1 products) _LANDSAT_EXTENDED_PROPS = { "landsat:algorithm_source_surface_reflectance": None, "landsat:collection_category": None, "landsat:collection_number": int, "landsat:data_type": None, "landsat:earth_sun_distance": None, "landsat:ephemeris_type": None, "landsat:geometric_rmse_model": None, "landsat:geometric_rmse_model_x": None, "landsat:geometric_rmse_model_y": None, "landsat:geometric_rmse_verify": None, "landsat:ground_control_points_model": None, "landsat:ground_control_points_verify": None, "landsat:ground_control_points_version": None, "landsat:image_quality_oli": None, "landsat:image_quality_tirs": None, "landsat:processing_software_version": None, "landsat:scan_gap_interpolation": float, "landsat:station_id": None, # Landsat USGS Properties "landsat:rmse": None, "landsat:rmse_x": None, "landsat:rmse_y": None, "landsat:wrs_type": None, "landsat:correction": None, "landsat:cloud_cover_land": None, } _SENTINEL_EXTENDED_PROPS = { "sentinel:sentinel_tile_id": parsed_sentinel_tile_id, "sentinel:datatake_start_datetime": datetime_type, "sentinel:datastrip_id": parsed_sentinel_datastrip_id, "sentinel:datatake_type": None, "sentinel:processing_baseline": None, "sentinel:processing_center": None, "sentinel:product_name": None, "sentinel:reception_station": None, "sentinel:utm_zone": int, "sentinel:latitude_band": None, "sentinel:grid_square": None, "sinergise_product_id": None, } _STAC_MISC_PROPS = { "providers": None, # https://github.com/radiantearth/stac-spec/blob/master/item-spec/common-metadata.md#provider, # Projection extension "proj:epsg": int, "proj:shape": None, "proj:transform": None, } class Eo3Dict(collections.abc.MutableMapping): """ This acts like a dictionary, but will normalise known properties (consistent case, types etc) and warn about common mistakes. It wraps an inner dictionary. By default it will normalise the fields in the input dictionary on creation, but you can disable this with `normalise_input=False`. """ # Every property we've seen or dealt with so far. Feel free to expand with abandon... # This is to minimise minor typos, case differences, etc, which plagued previous systems. # Keep sorted. KNOWN_PROPERTIES: Mapping[str, Optional[NormaliseValueFn]] = { "datetime": datetime_type, "dea:dataset_maturity": of_enum_type(("final", "interim", "nrt"), lower=True), "dea:product_maturity": of_enum_type(("stable", "provisional"), lower=True), "dtr:end_datetime": datetime_type, "dtr:start_datetime": datetime_type, "eo:azimuth": float, "eo:cloud_cover": percent_type, "eo:epsg": None, "eo:gsd": None, "eo:instrument": None, "eo:off_nadir": float, "eo:platform": normalise_platforms, "eo:constellation": None, "eo:sun_azimuth": degrees_type, "eo:sun_elevation": degrees_type, "sat:orbit_state": None, "sat:relative_orbit": int, "sat:absolute_orbit": int, "landsat:landsat_product_id": None, "landsat:scene_id": None, "landsat:landsat_scene_id": None, "landsat:wrs_path": int, "landsat:wrs_row": int, "odc:dataset_version": None, "odc:collection_number": int, "odc:naming_conventions": None, # Not strict as there may be more added in ODC... "odc:file_format": of_enum_type(FileFormat, strict=False), "odc:processing_datetime": datetime_type, "odc:producer": producer_check, "odc:product": None, "odc:product_family": identifier_type, "odc:region_code": None, **_LANDSAT_EXTENDED_PROPS, **_GQA_FMASK_PROPS, **_SENTINEL_EXTENDED_PROPS, **_STAC_MISC_PROPS, } # For backwards compatibility, in case users are extending at runtime. KNOWN_STAC_PROPERTIES = KNOWN_PROPERTIES def __init__(self, properties: Mapping = None, normalise_input=True) -> None: if properties is None: properties = {} self._props = properties # We normalise the properties they gave us. for key in list(self._props): # We always want to normalise dates as datetime objects rather than strings # for consistency. if normalise_input or ("datetime" in key): self.normalise_and_set(key, self._props[key], expect_override=True) self._finished_init_ = True def __setattr__(self, name: str, value: Any) -> None: """ Prevent against users accidentally setting new properties (it has happened multiple times). """ if hasattr(self, "_finished_init_") and not hasattr(self, name): raise TypeError( f"Cannot set new field '{name}' on a dict. " f"(Perhaps you meant to set it as a dictionary field??)" ) super().__setattr__(name, value) def __getitem__(self, item): return self._props[item] def __iter__(self): return iter(self._props) def __len__(self): return len(self._props) def __delitem__(self, name: str) -> None: del self._props[name] def __repr__(self) -> str: return f"{self.__class__.__name__}({self._props!r})" def __setitem__(self, key, value): self.normalise_and_set( key, value, # They can override properties but will receive a warning. allow_override=True, ) def normalise_and_set(self, key, value, allow_override=True, expect_override=False): """ Set a property with the usual normalisation. This has some options that are not available on normal dictionary item setting (``self[key] = val``) The default behaviour of this class is very conservative in order to catch common errors of users. You can loosen the settings here. :argument allow_override: Is it okay to overwrite an existing value? (if not, error will be thrown) :argument expect_override: We expect to overwrite a property, so don't produce a warning or error. """ if key not in self.KNOWN_PROPERTIES: warnings.warn( f"Unknown Stac property {key!r}. " f"If this is valid property, please tell us on Github here so we can add it: " f"\n\t{_github_suggest_new_property_url(key, value)}" ) if value is not None: normalise = self.KNOWN_PROPERTIES.get(key) if normalise: value = normalise(value) # If the normaliser has extracted extra properties, we'll get two return values. if isinstance(value, Tuple): value, extra_properties = value for k, v in extra_properties.items(): if k == key: raise RuntimeError( f"Infinite loop: writing key {k!r} from itself" ) self.normalise_and_set(k, v, allow_override=allow_override) if key in self._props and value != self[key] and (not expect_override): message = ( f"Overriding property {key!r} " f"(from {self[key]!r} to {value!r})" ) if allow_override: warnings.warn(message, category=PropertyOverrideWarning) else: raise KeyError(message) self._props[key] = value def nested(self): return nest_properties(self._props) class StacPropertyView(Eo3Dict): """ Backwards compatibility class name. Deprecated. Use the identical 'Eo3Dict' instead. These were called "StacProperties" in Stac 0.6, but many of them have changed in newer versions and we're sticking to the old names for consistency and backwards-compatibility. So they're now EO3 Properties. (The eo3-to-stac tool to convert EO3 properties to real Stac properties.) """ def __init__(self, properties=None) -> None: super().__init__(properties) warnings.warn( "The class name 'StacPropertyView' is deprecated as it's misleading. " "Please change your import to the (identical) 'Eo3Dict'.", category=DeprecationWarning, ) class PropertyOverrideWarning(UserWarning): """A warning that a property was set twice with different values.""" ... class Eo3Interface: """ These are convenience properties for common metadata fields. They are available on DatasetAssemblers and within other naming APIs. (This is abstract. If you want one of these of your own, you probably want to create an :class:`eodatasets3.DatasetDoc`) """ @property @abstractmethod def properties(self) -> Eo3Dict: raise NotImplementedError @property def platform(self) -> Optional[str]: """ Unique name of the specific platform the instrument is attached to. For satellites this would be the name of the satellite (e.g., ``landsat-8``, ``sentinel-2a``), whereas for drones this would be a unique name for the drone. In derivative products, multiple platforms can be specified with a comma: ``landsat-5,landsat-7``. Shorthand for ``eo:platform`` property """ return self.properties.get("eo:platform") @platform.setter def platform(self, value: str): self.properties["eo:platform"] = value @property def platforms(self) -> Set[str]: """ Get platform as a set (containing zero or more items). In EO3, multiple platforms are specified by comma-separating them. """ if not self.platform: return set() return set(self.properties.get("eo:platform", "").split(",")) @platforms.setter def platforms(self, value: Set[str]): # The normaliser supports sets/lists self.properties["eo:platform"] = value @property def instrument(self) -> str: """ Name of instrument or sensor used (e.g., MODIS, ASTER, OLI, Canon F-1). Shorthand for ``eo:instrument`` property """ return self.properties.get("eo:instrument") @instrument.setter def instrument(self, value: str): self.properties["eo:instrument"] = value @property def constellation(self) -> str: """ Constellation. Eg ``sentinel-2``. """ return self.properties.get("eo:constellation") @constellation.setter def constellation(self, value: str): self.properties["eo:constellation"] = value @property def product_name(self) -> Optional[str]: """ The ODC product name """ return self.properties.get("odc:product") @product_name.setter def product_name(self, value: str): self.properties["odc:product"] = value @property def producer(self) -> str: """ Organisation that produced the data. eg. ``usgs.gov`` or ``ga.gov.au`` Shorthand for ``odc:producer`` property """ return self.properties.get("odc:producer") @producer.setter def producer(self, domain: str): self.properties["odc:producer"] = domain @property def datetime_range(self) -> Tuple[datetime, datetime]: """ An optional date range for the dataset. The ``datetime`` is still mandatory when this is set. This field is a shorthand for reading/setting the datetime-range stac 0.6 extension properties: ``dtr:start_datetime`` and ``dtr:end_datetime`` """ return ( self.properties.get("dtr:start_datetime"), self.properties.get("dtr:end_datetime"), ) @datetime_range.setter def datetime_range(self, val: Tuple[datetime, datetime]): # TODO: string type conversion, better validation/errors start, end = val self.properties["dtr:start_datetime"] = start self.properties["dtr:end_datetime"] = end @property def processed(self) -> datetime: """When the dataset was created (Defaults to UTC if not specified) Shorthand for the ``odc:processing_datetime`` field """ return self.properties.get("odc:processing_datetime") @processed.setter def processed(self, value: Union[str, datetime]): self.properties["odc:processing_datetime"] = value def processed_now(self): """ Shorthand for when the dataset was processed right now on the current system. """ self.properties["odc:processing_datetime"] = datetime.utcnow() @property def dataset_version(self) -> str: """ The version of the dataset. Typically digits separated by a dot. Eg. `1.0.0` The first digit is usually the collection number for this 'producer' organisation, such as USGS Collection 1 or GA Collection 3. """ return self.properties.get("odc:dataset_version") @property def collection_number(self) -> int: """ The version of the collection. Eg.:: metadata: product_family: wofs dataset_version: 1.6.0 collection_number: 3 """ return self.properties.get("odc:collection_number") @dataset_version.setter def dataset_version(self, value): self.properties["odc:dataset_version"] = value @collection_number.setter def collection_number(self, value): self.properties["odc:collection_number"] = value @property def naming_conventions(self) -> str: return self.properties.get("odc:naming_conventions") @naming_conventions.setter def naming_conventions(self, value): self.properties["odc:naming_conventions"] = value @property def product_family(self) -> str: """ The identifier for this "family" of products, such as ``ard``, ``level1`` or ``fc``. It's used for grouping similar products together. They products in a family are usually produced the same way but have small variations: they come from different sensors, or are written in different projections, etc. ``ard`` family of products: ``ls7_ard``, ``ls5_ard`` .... On older versions of Open Data Cube this was called ``product_type``. Shorthand for ``odc:product_family`` property. """ return self.properties.get("odc:product_family") @product_family.setter def product_family(self, value): self.properties["odc:product_family"] = value @product_family.deleter def product_family(self): del self.properties["odc:product_family"] @property def region_code(self) -> Optional[str]: """ The "region" of acquisition. This is a platform-agnostic representation of things like the Landsat Path+Row. Datasets with the same Region Code will *roughly* (but usually not *exactly*) cover the same spatial footprint. It's generally treated as an opaque string to group datasets and process as stacks. For Landsat products it's the concatenated ``{path}{row}`` (both numbers formatted to three digits). For Sentinel 2, it's the MGRS grid (TODO presumably?). Shorthand for ``odc:region_code`` property. """ return self.properties.get("odc:region_code") @region_code.setter def region_code(self, value: str): self.properties["odc:region_code"] = value @property def maturity(self) -> str: """ The dataset maturity. The same data may be processed multiple times -- becoming more mature -- as new ancillary data becomes available. Typical values (from least to most mature): ``nrt`` (near real time), ``interim``, ``final`` """ return self.properties.get("dea:dataset_maturity") @maturity.setter def maturity(self, value): self.properties["dea:dataset_maturity"] = value @property def product_maturity(self) -> str: """ Classification: is this a 'provisional' or 'stable' release of the product? """ return self.properties.get("dea:product_maturity") @product_maturity.setter def product_maturity(self, value): self.properties["dea:product_maturity"] = value # Note that giving a method the name 'datetime' will override the 'datetime' type # for class-level declarations (ie, for any types on functions!) # So we make an alias: from datetime import datetime as datetime_ @property def datetime(self) -> datetime_: """ The searchable date and time of the assets. (Default to UTC if not specified) """ return self.properties.get("datetime") @datetime.setter def datetime(self, val: datetime_): self.properties["datetime"] = val def _github_suggest_new_property_url(key: str, value: object) -> str: """Get a URL to create a Github issue suggesting new properties to be added.""" issue_parameters = urlencode( dict( title=f"Include property {key!r}", labels="known-properties", body=dedent( f"""\ Hello! The property {key!r} does not appear to be in the KNOWN_STAC_PROPERTIES list, but I believe it to be valid. An example value of this property is: {value!r} Thank you! """ ), ) ) return f"https://github.com/GeoscienceAustralia/eo-datasets/issues/new?{issue_parameters}"
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license. """ import json import logging from django.db.models import Q, Avg, Count, Sum, Value, BooleanField, Case, When from django.conf import settings from django.utils.translation import gettext_lazy as _ from django.db.models import JSONField from django.core.validators import MinLengthValidator, MaxLengthValidator from django.db import transaction, models from annoying.fields import AutoOneToOneField from tasks.models import Task, Prediction, Annotation, Q_task_finished_annotations, bulk_update_stats_project_tasks from core.utils.common import create_hash, sample_query, get_attr_or_item, load_func from core.utils.exceptions import LabelStudioValidationErrorSentryIgnored from core.label_config import ( parse_config, validate_label_config, extract_data_types, get_all_object_tag_names, config_line_stipped, get_sample_task, get_all_labels, get_all_control_tag_tuples, get_annotation_tuple ) logger = logging.getLogger(__name__) class ProjectManager(models.Manager): def for_user(self, user): return self.filter(organization=user.active_organization) def with_counts(self): return self.annotate( task_number=Count('tasks', distinct=True), finished_task_number=Count( 'tasks', distinct=True, filter=Q(tasks__is_labeled=True) ), total_predictions_number=Count('tasks__predictions', distinct=True), total_annotations_number=Count( 'tasks__annotations__id', distinct=True, filter=Q(tasks__annotations__was_cancelled=False) ), num_tasks_with_annotations=Count( 'tasks__id', distinct=True, filter=Q(tasks__annotations__isnull=False) & Q(tasks__annotations__ground_truth=False) & Q(tasks__annotations__was_cancelled=False) & Q(tasks__annotations__result__isnull=False) ), useful_annotation_number=Count( 'tasks__annotations__id', distinct=True, filter=Q(tasks__annotations__was_cancelled=False) & Q(tasks__annotations__ground_truth=False) & Q(tasks__annotations__result__isnull=False) ), ground_truth_number=Count( 'tasks__annotations__id', distinct=True, filter=Q(tasks__annotations__ground_truth=True) ), skipped_annotations_number=Count( 'tasks__annotations__id', distinct=True, filter=Q(tasks__annotations__was_cancelled=True) ), ) ProjectMixin = load_func(settings.PROJECT_MIXIN) class Project(ProjectMixin, models.Model): """ """ objects = ProjectManager() __original_label_config = None title = models.CharField(_('title'), null=True, blank=True, default='', max_length=settings.PROJECT_TITLE_MAX_LEN, help_text=f'Project name. Must be between {settings.PROJECT_TITLE_MIN_LEN} and {settings.PROJECT_TITLE_MAX_LEN} characters long.', validators=[MinLengthValidator(settings.PROJECT_TITLE_MIN_LEN), MaxLengthValidator(settings.PROJECT_TITLE_MAX_LEN)]) description = models.TextField(_('description'), blank=True, null=True, default='', help_text='Project description') organization = models.ForeignKey('organizations.Organization', on_delete=models.CASCADE, related_name='projects', null=True) label_config = models.TextField(_('label config'), blank=True, null=True, default='<View></View>', help_text='Label config in XML format. See more about it in documentation') expert_instruction = models.TextField(_('expert instruction'), blank=True, null=True, default='', help_text='Labeling instructions in HTML format') show_instruction = models.BooleanField(_('show instruction'), default=False, help_text='Show instructions to the annotator before they start') show_skip_button = models.BooleanField(_('show skip button'), default=True, help_text='Show a skip button in interface and allow annotators to skip the task') enable_empty_annotation = models.BooleanField(_('enable empty annotation'), default=True, help_text='Allow annotators to submit empty annotations') show_annotation_history = models.BooleanField(_('show annotation history'), default=False, help_text='Show annotation history to annotator') show_collab_predictions = models.BooleanField(_('show predictions to annotator'), default=True, help_text='If set, the annotator can view model predictions') evaluate_predictions_automatically = models.BooleanField(_('evaluate predictions automatically'), default=False, help_text='Retrieve and display predictions when loading a task') token = models.CharField(_('token'), max_length=256, default=create_hash, null=True, blank=True) result_count = models.IntegerField(_('result count'), default=0, help_text='Total results inside of annotations counter') color = models.CharField(_('color'), max_length=16, default='#FFFFFF', null=True, blank=True) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='created_projects', on_delete=models.SET_NULL, null=True, verbose_name=_('created by') ) maximum_annotations = models.IntegerField(_('maximum annotation number'), default=1, help_text='Maximum number of annotations for one task. ' 'If the number of annotations per task is equal or greater ' 'to this value, the task is completed (is_labeled=True)') min_annotations_to_start_training = models.IntegerField( _('min_annotations_to_start_training'), default=10, help_text='Minimum number of completed tasks after which model training is started' ) control_weights = JSONField(_('control weights'), null=True, default=dict, help_text='Weights for control tags') model_version = models.TextField(_('model version'), blank=True, null=True, default='', help_text='Machine learning model version') data_types = JSONField(_('data_types'), default=dict, null=True) is_draft = models.BooleanField( _('is draft'), default=False, help_text='Whether or not the project is in the middle of being created') is_published = models.BooleanField(_('published'), default=False, help_text='Whether or not the project is published to annotators') created_at = models.DateTimeField(_('created at'), auto_now_add=True) updated_at = models.DateTimeField(_('updated at'), auto_now=True) SEQUENCE = 'Sequential sampling' UNIFORM = 'Uniform sampling' UNCERTAINTY = 'Uncertainty sampling' SAMPLING_CHOICES = ( (SEQUENCE, 'Tasks are ordered by Data manager ordering'), (UNIFORM, 'Tasks are chosen randomly'), (UNCERTAINTY, 'Tasks are chosen according to model uncertainty scores (active learning mode)') ) sampling = models.CharField(max_length=100, choices=SAMPLING_CHOICES, null=True, default=SEQUENCE) show_ground_truth_first = models.BooleanField(_('show ground truth first'), default=False) show_overlap_first = models.BooleanField(_('show overlap first'), default=False) overlap_cohort_percentage = models.IntegerField(_('overlap_cohort_percentage'), default=100) task_data_login = models.CharField( _('task_data_login'), max_length=256, blank=True, null=True, help_text='Task data credentials: login') task_data_password = models.CharField( _('task_data_password'), max_length=256, blank=True, null=True, help_text='Task data credentials: password') def __init__(self, *args, **kwargs): super(Project, self).__init__(*args, **kwargs) self.__original_label_config = self.label_config self.__maximum_annotations = self.maximum_annotations self.__overlap_cohort_percentage = self.overlap_cohort_percentage # TODO: once bugfix with incorrect data types in List # logging.warning('! Please, remove code below after patching of all projects (extract_data_types)') if self.label_config is not None: if self.data_types != extract_data_types(self.label_config): self.data_types = extract_data_types(self.label_config) @property def num_tasks(self): return self.tasks.count() def get_current_predictions(self): return Prediction.objects.filter(Q(task__project=self.id) & Q(model_version=self.model_version)) @property def num_predictions(self): return self.get_current_predictions().count() @property def num_annotations(self): return Annotation.objects.filter(task__project=self).count() @property def has_predictions(self): return self.get_current_predictions().exists() @property def has_any_predictions(self): return Prediction.objects.filter(Q(task__project=self.id)).exists() @property def business(self): return self.created_by.business @property def is_private(self): return None @property def secure_mode(self): return False @property def one_object_in_label_config(self): return len(self.data_types) <= 1 @property def only_undefined_field(self): return self.one_object_in_label_config and self.summary.common_data_columns \ and self.summary.common_data_columns[0] == settings.DATA_UNDEFINED_NAME @property def get_labeled_count(self): return self.tasks.filter(is_labeled=True).count() @property def get_collected_count(self): return self.tasks.count() @property def get_total_possible_count(self): """ Tasks has overlap - how many tc should be accepted possible count = sum [ t.overlap for t in tasks] :return: N int total amount of Annotations that should be submitted """ if self.tasks.count() == 0: return 0 return self.tasks.aggregate(Sum('overlap'))['overlap__sum'] @property def get_available_for_labeling(self): return self.get_collected_count - self.get_labeled_count @property def need_annotators(self): return self.maximum_annotations - self.num_annotators @classmethod def find_by_invite_url(cls, url): token = url.strip('/').split('/')[-1] if len(token): return Project.objects.get(token=token) else: raise KeyError(f'Can\'t find Project by invite URL: {url}') def reset_token(self): self.token = create_hash() self.save() def add_collaborator(self, user): created = False with transaction.atomic(): try: ProjectMember.objects.get(user=user, project=self) except ProjectMember.DoesNotExist: ProjectMember.objects.create(user=user, project=self) created = True else: logger.debug(f'Project membership {self} for user {user} already exists') return created def has_collaborator(self, user): return ProjectMember.objects.filter(user=user, project=self).exists() def has_collaborator_enabled(self, user): membership = ProjectMember.objects.filter(user=user, project=self) return membership.exists() and membership.first().enabled def update_tasks_states(self, maximum_annotations_changed, overlap_cohort_percentage_changed, tasks_number_changed): # if only maximum annotations parameter is tweaked if maximum_annotations_changed and not overlap_cohort_percentage_changed: tasks_with_overlap = self.tasks.filter(overlap__gt=1) if tasks_with_overlap.exists(): # if there is a part with overlaped tasks, affect only them tasks_with_overlap.update(overlap=self.maximum_annotations) else: # otherwise affect all tasks self.tasks.update(overlap=self.maximum_annotations) # if cohort slider is tweaked elif overlap_cohort_percentage_changed and self.maximum_annotations > 1: self._rearrange_overlap_cohort() # if adding/deleting tasks and cohort settings are applied elif tasks_number_changed and self.overlap_cohort_percentage < 100 and self.maximum_annotations > 1: self._rearrange_overlap_cohort() if maximum_annotations_changed or overlap_cohort_percentage_changed: bulk_update_stats_project_tasks(self.tasks.filter( Q(annotations__isnull=False) & Q(annotations__ground_truth=False))) def _rearrange_overlap_cohort(self): tasks_with_overlap = self.tasks.filter(overlap__gt=1) tasks_with_overlap_count = tasks_with_overlap.count() total_tasks = self.tasks.count() new_tasks_with_overlap_count = int(self.overlap_cohort_percentage / 100 * total_tasks + 0.5) if tasks_with_overlap_count > new_tasks_with_overlap_count: # TODO: warn if we try to reduce current cohort that is already labeled with overlap reduce_by = tasks_with_overlap_count - new_tasks_with_overlap_count reduce_tasks = sample_query(tasks_with_overlap, reduce_by) reduce_tasks.update(overlap=1) reduced_tasks_ids = reduce_tasks.values_list('id', flat=True) tasks_with_overlap.exclude(id__in=reduced_tasks_ids).update(overlap=self.maximum_annotations) elif tasks_with_overlap_count < new_tasks_with_overlap_count: increase_by = new_tasks_with_overlap_count - tasks_with_overlap_count tasks_without_overlap = self.tasks.filter(overlap=1) increase_tasks = sample_query(tasks_without_overlap, increase_by) increase_tasks.update(overlap=self.maximum_annotations) tasks_with_overlap.update(overlap=self.maximum_annotations) def remove_tasks_by_file_uploads(self, file_upload_ids): self.tasks.filter(file_upload_id__in=file_upload_ids).delete() def advance_onboarding(self): """ Move project to next onboarding step """ po_qs = self.steps_left.order_by('step__order') count = po_qs.count() if count: po = po_qs.first() po.finished = True po.save() return count != 1 def created_at_prettify(self): return self.created_at.strftime("%d %b %Y %H:%M:%S") def onboarding_step_finished(self, step): """ Mark specific step as finished """ pos = ProjectOnboardingSteps.objects.get(code=step) po = ProjectOnboarding.objects.get(project=self, step=pos) po.finished = True po.save() return po def data_types_json(self): return json.dumps(self.data_types) def available_data_keys(self): return sorted(list(self.data_types.keys())) @classmethod def validate_label_config(cls, config_string): validate_label_config(config_string) def validate_config(self, config_string): self.validate_label_config(config_string) if not hasattr(self, 'summary'): return if self.num_tasks == 0: logger.debug(f'Project {self} has no tasks: nothing to validate here. Ensure project summary is empty') self.summary.reset() return # validate data columns consistency fields_from_config = get_all_object_tag_names(config_string) if not fields_from_config: logger.debug(f'Data fields not found in labeling config') return fields_from_data = set(self.summary.common_data_columns) fields_from_data.discard(settings.DATA_UNDEFINED_NAME) if fields_from_data and not fields_from_config.issubset(fields_from_data): different_fields = list(fields_from_config.difference(fields_from_data)) raise LabelStudioValidationErrorSentryIgnored(f'These fields are not present in the data: {','.join(different_fields)}') if self.num_annotations == 0: logger.debug(f'Project {self} has no annotations: nothing to validate here. ' f'Ensure annotations-related project summary is empty') self.summary.reset(tasks_data_based=False) return # validate annotations consistency annotations_from_config = set(get_all_control_tag_tuples(config_string)) if not annotations_from_config: logger.debug(f'Annotation schema is not found in config') return annotations_from_data = set(self.summary.created_annotations) if annotations_from_data and not annotations_from_data.issubset(annotations_from_config): different_annotations = list(annotations_from_data.difference(annotations_from_config)) diff_str = [] for ann_tuple in different_annotations: from_name, to_name, t = ann_tuple.split('|') diff_str.append( f'{self.summary.created_annotations[ann_tuple]} ' f'with from_name={from_name}, to_name={to_name}, type={t}') diff_str = '\n'.join(diff_str) raise LabelStudioValidationErrorSentryIgnored( f'Created annotations are incompatible with provided labeling schema, we found:\n{diff_str}') # validate labels consistency labels_from_config = get_all_labels(config_string) created_labels = self.summary.created_labels for control_tag_from_data, labels_from_data in created_labels.items(): # Check if labels created in annotations, and their control tag has been removed if labels_from_data and control_tag_from_data not in labels_from_config: raise LabelStudioValidationErrorSentryIgnored( f'There are {sum(labels_from_data.values(), 0)} annotation(s) created with tag ' f'"{control_tag_from_data}", you can\'t remove it') labels_from_config_by_tag = set(labels_from_config[control_tag_from_data]) if not set(labels_from_data).issubset(set(labels_from_config_by_tag)): different_labels = list(set(labels_from_data).difference(labels_from_config_by_tag)) diff_str = '\n'.join(f'{l} ({labels_from_data[l]} annotations)' for l in different_labels) raise LabelStudioValidationErrorSentryIgnored(f'These labels still exist in annotations:\n{diff_str}') def _label_config_has_changed(self): return self.label_config != self.__original_label_config def delete_predictions(self): predictions = Prediction.objects.filter(task__project=self) count = predictions.count() predictions.delete() return {'deleted_predictions': count} def get_updated_weights(self): outputs = parse_config(self.label_config) control_weights = {} exclude_control_types = ('Filter',) for control_name in outputs: control_type = outputs[control_name]['type'] if control_type in exclude_control_types: continue control_weights[control_name] = { 'overall': 1.0, 'type': control_type, 'labels': {label: 1.0 for label in outputs[control_name].get('labels', [])} } return control_weights def save(self, *args, recalc=True, **kwargs): exists = True if self.pk else False if self.label_config and (self._label_config_has_changed() or not exists or not self.control_weights): self.control_weights = self.get_updated_weights() super(Project, self).save(*args, **kwargs) project_with_config_just_created = not exists and self.pk and self.label_config if self._label_config_has_changed() or project_with_config_just_created: self.data_types = extract_data_types(self.label_config) if self._label_config_has_changed(): self.__original_label_config = self.label_config if not exists: steps = ProjectOnboardingSteps.objects.all() objs = [ProjectOnboarding(project=self, step=step) for step in steps] ProjectOnboarding.objects.bulk_create(objs) # argument for recalculate project task stats if recalc: self.update_tasks_states( maximum_annotations_changed=self.__maximum_annotations != self.maximum_annotations, overlap_cohort_percentage_changed=self.__overlap_cohort_percentage != self.overlap_cohort_percentage, tasks_number_changed=False ) self.__maximum_annotations = self.maximum_annotations self.__overlap_cohort_percentage = self.overlap_cohort_percentage if hasattr(self, 'summary'): # Ensure project.summary is consistent with current tasks / annotations if self.num_tasks == 0: self.summary.reset() elif self.num_annotations == 0: self.summary.reset(tasks_data_based=False) def get_member_ids(self): if hasattr(self, 'team_link'): # project has defined team scope # TODO: avoid checking team but rather add all project members when creating a project return self.team_link.team.members.values_list('user', flat=True) else: from users.models import User # TODO: may want to return all users from organization return User.objects.none() def has_team_user(self, user): return hasattr(self, 'team_link') and self.team_link.team.has_user(user) def annotators(self): """ Annotators connected to this project including team members """ from users.models import User member_ids = self.get_member_ids() team_members = User.objects.filter(id__in=member_ids).order_by('email') # add members from invited projects project_member_ids = self.members.values_list('user__id', flat=True) project_members = User.objects.filter(id__in=project_member_ids) annotators = team_members | project_members # set annotator.team_member=True if annotator is not an invited user annotators = annotators.annotate( team_member=Case( When(id__in=project_member_ids, then=Value(False)), default=Value(True), output_field=BooleanField(), ) ) return annotators def annotators_with_annotations(self, min_count=500): """ Annotators with annotation number > min_number :param min_count: minimal annotation number to leave an annotators :return: filtered annotators """ annotators = self.annotators() q = Q(annotations__task__project=self) & Q_task_finished_annotations & Q(annotations__ground_truth=False) annotators = annotators.annotate(annotation_count=Count('annotations', filter=q, distinct=True)) return annotators.filter(annotation_count__gte=min_count) def labeled_tasks(self): return self.tasks.filter(is_labeled=True) def has_annotations(self): from tasks.models import Annotation # prevent cycling imports return Annotation.objects.filter(Q(task__project=self) & Q(ground_truth=False)).count() > 0 # [TODO] this should be a template tag or something like this @property def label_config_line(self): c = self.label_config return config_line_stipped(c) def get_sample_task(self, label_config=None): config = label_config or self.label_config task, _, _ = get_sample_task(config) return task def eta(self): """ Show eta for project to be finished eta = avg task annotations finish time * remain annotations task has overlap = amount of task annotations to consider as finished (is_labeled) remain annotations = sum ( task annotations to be done to fulfill each unfinished task overlap) :return: time in seconds """ # finished tasks * overlap finished_tasks = Task.objects.filter(project=self.id, is_labeled=True) # one could make more than need to overlap min_n_finished_annotations = sum([ft.overlap for ft in finished_tasks]) annotations_unfinished_tasks = Annotation.objects.filter( task__project=self.id, task__is_labeled=False, ground_truth=False, result__isnull=False).count() # get minimum remain annotations total_annotations_needed = self.get_total_possible_count annotations_remain = total_annotations_needed - min_n_finished_annotations - annotations_unfinished_tasks # get average time of all finished TC finished_annotations = Annotation.objects.filter( Q(task__project=self.id) & Q(ground_truth=False), result__isnull=False).values('lead_time') avg_lead_time = finished_annotations.aggregate(avg_lead_time=Avg('lead_time'))['avg_lead_time'] if avg_lead_time is None: return None return avg_lead_time * annotations_remain def finished(self): return not self.tasks.filter(is_labeled=False).exists() def annotations_lead_time(self): annotations = Annotation.objects.filter(Q(task__project=self.id) & Q(ground_truth=False)) return annotations.aggregate(avg_lead_time=Avg('lead_time'))['avg_lead_time'] @staticmethod def django_settings(): return settings @staticmethod def max_tasks_file_size(): return settings.TASKS_MAX_FILE_SIZE def get_control_tags_from_config(self): return parse_config(self.label_config) def get_parsed_config(self): return parse_config(self.label_config) def __str__(self): return f'{self.title} (id={self.id})' or _("Business number %d") % self.pk class Meta: db_table = 'project' class ProjectOnboardingSteps(models.Model): """ """ DATA_UPLOAD = "DU" CONF_SETTINGS = "CF" PUBLISH = "PB" INVITE_EXPERTS = "IE" STEPS_CHOICES = ( (DATA_UPLOAD, "Import your data"), (CONF_SETTINGS, "Configure settings"), (PUBLISH, "Publish project"), (INVITE_EXPERTS, "Invite collaborators") ) code = models.CharField(max_length=2, choices=STEPS_CHOICES, null=True) title = models.CharField(_('title'), max_length=1000, null=False) description = models.TextField(_('description'), null=False) order = models.IntegerField(default=0) created_at = models.DateTimeField(_('created at'), auto_now_add=True) updated_at = models.DateTimeField(_('updated at'), auto_now=True) class Meta: ordering = ['order'] class ProjectOnboarding(models.Model): """ """ step = models.ForeignKey(ProjectOnboardingSteps, on_delete=models.CASCADE, related_name="po_through") project = models.ForeignKey(Project, on_delete=models.CASCADE) finished = models.BooleanField(default=False) created_at = models.DateTimeField(_('created at'), auto_now_add=True) updated_at = models.DateTimeField(_('updated at'), auto_now=True) def save(self, *args, **kwargs): super(ProjectOnboarding, self).save(*args, **kwargs) if ProjectOnboarding.objects.filter(project=self.project, finished=True).count() == 4: self.project.skip_onboarding = True self.project.save(recalc=False) class ProjectMember(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='project_memberships', help_text='User ID') # noqa project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='members', help_text='Project ID') enabled = models.BooleanField(default=True, help_text='Project member is enabled') created_at = models.DateTimeField(_('created at'), auto_now_add=True) updated_at = models.DateTimeField(_('updated at'), auto_now=True) class ProjectSummary(models.Model): project = AutoOneToOneField(Project, primary_key=True, on_delete=models.CASCADE, related_name='summary') created_at = models.DateTimeField(_('created at'), auto_now_add=True, help_text='Creation time') # { col1: task_count_with_col1, col2: task_count_with_col2 } all_data_columns = JSONField( _('all data columns'), null=True, default=dict, help_text='All data columns found in imported tasks') # [col1, col2] common_data_columns = JSONField( _('common data columns'), null=True, default=list, help_text='Common data columns found across imported tasks') # { (from_name, to_name, type): annotation_count } created_annotations = JSONField( _('created annotations'), null=True, default=dict, help_text='Unique annotation types identified by tuple (from_name, to_name, type)') # noqa # { from_name: {label1: task_count_with_label1, label2: task_count_with_label2} } created_labels = JSONField( _('created labels'), null=True, default=dict, help_text='Unique labels') def has_permission(self, user): return self.project.has_permission(user) def reset(self, tasks_data_based=True): if tasks_data_based: self.all_data_columns = {} self.common_data_columns = [] self.created_annotations = {} self.created_labels = {} self.save() def update_data_columns(self, tasks): common_data_columns = set() all_data_columns = dict(self.all_data_columns) for task in tasks: try: task_data = get_attr_or_item(task, 'data') except KeyError: task_data = task task_data_keys = task_data.keys() for column in task_data_keys: all_data_columns[column] = all_data_columns.get(column, 0) + 1 if not common_data_columns: common_data_columns = set(task_data_keys) else: common_data_columns &= set(task_data_keys) self.all_data_columns = all_data_columns if not self.common_data_columns: self.common_data_columns = list(sorted(common_data_columns)) else: self.common_data_columns = list(sorted(set(self.common_data_columns) & common_data_columns)) logger.debug(f'summary.all_data_columns = {self.all_data_columns}') logger.debug(f'summary.common_data_columns = {self.common_data_columns}') self.save() def remove_data_columns(self, tasks): all_data_columns = dict(self.all_data_columns) keys_to_remove = [] for task in tasks: task_data = get_attr_or_item(task, 'data') for key in task_data.keys(): if key in all_data_columns: all_data_columns[key] -= 1 if all_data_columns[key] == 0: keys_to_remove.append(key) all_data_columns.pop(key) self.all_data_columns = all_data_columns if keys_to_remove: common_data_columns = list(self.common_data_columns) for key in keys_to_remove: if key in common_data_columns: common_data_columns.remove(key) self.common_data_columns = common_data_columns logger.debug(f'summary.all_data_columns = {self.all_data_columns}') logger.debug(f'summary.common_data_columns = {self.common_data_columns}') self.save() def _get_annotation_key(self, result): result_type = result.get('type', None) if result_type in ('relation', 'pairwise', None): return None if 'from_name' not in result or 'to_name' not in result: logger.error( 'Unexpected annotation.result format: "from_name" or "to_name" not found in %r', result, extra={'sentry_skip': True} ) return None result_from_name = result['from_name'] key = get_annotation_tuple(result_from_name, result['to_name'], result_type or '') return key def _get_labels(self, result): result_type = result.get('type') result_value = result['value'].get(result_type) if not result_value or not isinstance(result_value, list) or result_type == 'text': # Non-list values are not labels. TextArea list values (texts) are not labels too. return [] # Labels are stored in list labels = [] for label in result_value: labels.append(str(label)) return labels def update_created_annotations_and_labels(self, annotations): created_annotations = dict(self.created_annotations) labels = dict(self.created_labels) for annotation in annotations: results = get_attr_or_item(annotation, 'result') or [] if not isinstance(results, list): continue for result in results: # aggregate annotation types key = self._get_annotation_key(result) if not key: continue created_annotations[key] = created_annotations.get(key, 0) + 1 from_name = result['from_name'] # aggregate labels if from_name not in self.created_labels: labels[from_name] = dict() for label in self._get_labels(result): labels[from_name][label] = labels[from_name].get(label, 0) + 1 logger.debug(f'summary.created_annotations = {created_annotations}') logger.debug(f'summary.created_labels = {labels}') self.created_annotations = created_annotations self.created_labels = labels self.save() def remove_created_annotations_and_labels(self, annotations): created_annotations = dict(self.created_annotations) labels = dict(self.created_labels) for annotation in annotations: results = get_attr_or_item(annotation, 'result') or [] if not isinstance(results, list): continue for result in results: # reduce annotation counters key = self._get_annotation_key(result) if key in created_annotations: created_annotations[key] -= 1 if created_annotations[key] == 0: created_annotations.pop(key) # reduce labels counters from_name = result.get('from_name', None) if from_name not in labels: continue for label in self._get_labels(result): label = str(label) if label in labels[from_name]: labels[from_name][label] -= 1 if labels[from_name][label] == 0: labels[from_name].pop(label) if not labels[from_name]: labels.pop(from_name) logger.debug(f'summary.created_annotations = {created_annotations}') logger.debug(f'summary.created_labels = {labels}') self.created_annotations = created_annotations self.created_labels = labels self.save()
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license. """ import json import logging from django.db.models import Q, Avg, Count, Sum, Value, BooleanField, Case, When from django.conf import settings from django.utils.translation import gettext_lazy as _ from django.db.models import JSONField from django.core.validators import MinLengthValidator, MaxLengthValidator from django.db import transaction, models from annoying.fields import AutoOneToOneField from tasks.models import Task, Prediction, Annotation, Q_task_finished_annotations, bulk_update_stats_project_tasks from core.utils.common import create_hash, sample_query, get_attr_or_item, load_func from core.utils.exceptions import LabelStudioValidationErrorSentryIgnored from core.label_config import ( parse_config, validate_label_config, extract_data_types, get_all_object_tag_names, config_line_stipped, get_sample_task, get_all_labels, get_all_control_tag_tuples, get_annotation_tuple ) logger = logging.getLogger(__name__) class ProjectManager(models.Manager): def for_user(self, user): return self.filter(organization=user.active_organization) def with_counts(self): return self.annotate( task_number=Count('tasks', distinct=True), finished_task_number=Count( 'tasks', distinct=True, filter=Q(tasks__is_labeled=True) ), total_predictions_number=Count('tasks__predictions', distinct=True), total_annotations_number=Count( 'tasks__annotations__id', distinct=True, filter=Q(tasks__annotations__was_cancelled=False) ), num_tasks_with_annotations=Count( 'tasks__id', distinct=True, filter=Q(tasks__annotations__isnull=False) & Q(tasks__annotations__ground_truth=False) & Q(tasks__annotations__was_cancelled=False) & Q(tasks__annotations__result__isnull=False) ), useful_annotation_number=Count( 'tasks__annotations__id', distinct=True, filter=Q(tasks__annotations__was_cancelled=False) & Q(tasks__annotations__ground_truth=False) & Q(tasks__annotations__result__isnull=False) ), ground_truth_number=Count( 'tasks__annotations__id', distinct=True, filter=Q(tasks__annotations__ground_truth=True) ), skipped_annotations_number=Count( 'tasks__annotations__id', distinct=True, filter=Q(tasks__annotations__was_cancelled=True) ), ) ProjectMixin = load_func(settings.PROJECT_MIXIN) class Project(ProjectMixin, models.Model): """ """ objects = ProjectManager() __original_label_config = None title = models.CharField(_('title'), null=True, blank=True, default='', max_length=settings.PROJECT_TITLE_MAX_LEN, help_text=f'Project name. Must be between {settings.PROJECT_TITLE_MIN_LEN} and {settings.PROJECT_TITLE_MAX_LEN} characters long.', validators=[MinLengthValidator(settings.PROJECT_TITLE_MIN_LEN), MaxLengthValidator(settings.PROJECT_TITLE_MAX_LEN)]) description = models.TextField(_('description'), blank=True, null=True, default='', help_text='Project description') organization = models.ForeignKey('organizations.Organization', on_delete=models.CASCADE, related_name='projects', null=True) label_config = models.TextField(_('label config'), blank=True, null=True, default='<View></View>', help_text='Label config in XML format. See more about it in documentation') expert_instruction = models.TextField(_('expert instruction'), blank=True, null=True, default='', help_text='Labeling instructions in HTML format') show_instruction = models.BooleanField(_('show instruction'), default=False, help_text='Show instructions to the annotator before they start') show_skip_button = models.BooleanField(_('show skip button'), default=True, help_text='Show a skip button in interface and allow annotators to skip the task') enable_empty_annotation = models.BooleanField(_('enable empty annotation'), default=True, help_text='Allow annotators to submit empty annotations') show_annotation_history = models.BooleanField(_('show annotation history'), default=False, help_text='Show annotation history to annotator') show_collab_predictions = models.BooleanField(_('show predictions to annotator'), default=True, help_text='If set, the annotator can view model predictions') evaluate_predictions_automatically = models.BooleanField(_('evaluate predictions automatically'), default=False, help_text='Retrieve and display predictions when loading a task') token = models.CharField(_('token'), max_length=256, default=create_hash, null=True, blank=True) result_count = models.IntegerField(_('result count'), default=0, help_text='Total results inside of annotations counter') color = models.CharField(_('color'), max_length=16, default='#FFFFFF', null=True, blank=True) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='created_projects', on_delete=models.SET_NULL, null=True, verbose_name=_('created by') ) maximum_annotations = models.IntegerField(_('maximum annotation number'), default=1, help_text='Maximum number of annotations for one task. ' 'If the number of annotations per task is equal or greater ' 'to this value, the task is completed (is_labeled=True)') min_annotations_to_start_training = models.IntegerField( _('min_annotations_to_start_training'), default=10, help_text='Minimum number of completed tasks after which model training is started' ) control_weights = JSONField(_('control weights'), null=True, default=dict, help_text='Weights for control tags') model_version = models.TextField(_('model version'), blank=True, null=True, default='', help_text='Machine learning model version') data_types = JSONField(_('data_types'), default=dict, null=True) is_draft = models.BooleanField( _('is draft'), default=False, help_text='Whether or not the project is in the middle of being created') is_published = models.BooleanField(_('published'), default=False, help_text='Whether or not the project is published to annotators') created_at = models.DateTimeField(_('created at'), auto_now_add=True) updated_at = models.DateTimeField(_('updated at'), auto_now=True) SEQUENCE = 'Sequential sampling' UNIFORM = 'Uniform sampling' UNCERTAINTY = 'Uncertainty sampling' SAMPLING_CHOICES = ( (SEQUENCE, 'Tasks are ordered by Data manager ordering'), (UNIFORM, 'Tasks are chosen randomly'), (UNCERTAINTY, 'Tasks are chosen according to model uncertainty scores (active learning mode)') ) sampling = models.CharField(max_length=100, choices=SAMPLING_CHOICES, null=True, default=SEQUENCE) show_ground_truth_first = models.BooleanField(_('show ground truth first'), default=False) show_overlap_first = models.BooleanField(_('show overlap first'), default=False) overlap_cohort_percentage = models.IntegerField(_('overlap_cohort_percentage'), default=100) task_data_login = models.CharField( _('task_data_login'), max_length=256, blank=True, null=True, help_text='Task data credentials: login') task_data_password = models.CharField( _('task_data_password'), max_length=256, blank=True, null=True, help_text='Task data credentials: password') def __init__(self, *args, **kwargs): super(Project, self).__init__(*args, **kwargs) self.__original_label_config = self.label_config self.__maximum_annotations = self.maximum_annotations self.__overlap_cohort_percentage = self.overlap_cohort_percentage # TODO: once bugfix with incorrect data types in List # logging.warning('! Please, remove code below after patching of all projects (extract_data_types)') if self.label_config is not None: if self.data_types != extract_data_types(self.label_config): self.data_types = extract_data_types(self.label_config) @property def num_tasks(self): return self.tasks.count() def get_current_predictions(self): return Prediction.objects.filter(Q(task__project=self.id) & Q(model_version=self.model_version)) @property def num_predictions(self): return self.get_current_predictions().count() @property def num_annotations(self): return Annotation.objects.filter(task__project=self).count() @property def has_predictions(self): return self.get_current_predictions().exists() @property def has_any_predictions(self): return Prediction.objects.filter(Q(task__project=self.id)).exists() @property def business(self): return self.created_by.business @property def is_private(self): return None @property def secure_mode(self): return False @property def one_object_in_label_config(self): return len(self.data_types) <= 1 @property def only_undefined_field(self): return self.one_object_in_label_config and self.summary.common_data_columns \ and self.summary.common_data_columns[0] == settings.DATA_UNDEFINED_NAME @property def get_labeled_count(self): return self.tasks.filter(is_labeled=True).count() @property def get_collected_count(self): return self.tasks.count() @property def get_total_possible_count(self): """ Tasks has overlap - how many tc should be accepted possible count = sum [ t.overlap for t in tasks] :return: N int total amount of Annotations that should be submitted """ if self.tasks.count() == 0: return 0 return self.tasks.aggregate(Sum('overlap'))['overlap__sum'] @property def get_available_for_labeling(self): return self.get_collected_count - self.get_labeled_count @property def need_annotators(self): return self.maximum_annotations - self.num_annotators @classmethod def find_by_invite_url(cls, url): token = url.strip('/').split('/')[-1] if len(token): return Project.objects.get(token=token) else: raise KeyError(f'Can\'t find Project by invite URL: {url}') def reset_token(self): self.token = create_hash() self.save() def add_collaborator(self, user): created = False with transaction.atomic(): try: ProjectMember.objects.get(user=user, project=self) except ProjectMember.DoesNotExist: ProjectMember.objects.create(user=user, project=self) created = True else: logger.debug(f'Project membership {self} for user {user} already exists') return created def has_collaborator(self, user): return ProjectMember.objects.filter(user=user, project=self).exists() def has_collaborator_enabled(self, user): membership = ProjectMember.objects.filter(user=user, project=self) return membership.exists() and membership.first().enabled def update_tasks_states(self, maximum_annotations_changed, overlap_cohort_percentage_changed, tasks_number_changed): # if only maximum annotations parameter is tweaked if maximum_annotations_changed and not overlap_cohort_percentage_changed: tasks_with_overlap = self.tasks.filter(overlap__gt=1) if tasks_with_overlap.exists(): # if there is a part with overlaped tasks, affect only them tasks_with_overlap.update(overlap=self.maximum_annotations) else: # otherwise affect all tasks self.tasks.update(overlap=self.maximum_annotations) # if cohort slider is tweaked elif overlap_cohort_percentage_changed and self.maximum_annotations > 1: self._rearrange_overlap_cohort() # if adding/deleting tasks and cohort settings are applied elif tasks_number_changed and self.overlap_cohort_percentage < 100 and self.maximum_annotations > 1: self._rearrange_overlap_cohort() if maximum_annotations_changed or overlap_cohort_percentage_changed: bulk_update_stats_project_tasks(self.tasks.filter( Q(annotations__isnull=False) & Q(annotations__ground_truth=False))) def _rearrange_overlap_cohort(self): tasks_with_overlap = self.tasks.filter(overlap__gt=1) tasks_with_overlap_count = tasks_with_overlap.count() total_tasks = self.tasks.count() new_tasks_with_overlap_count = int(self.overlap_cohort_percentage / 100 * total_tasks + 0.5) if tasks_with_overlap_count > new_tasks_with_overlap_count: # TODO: warn if we try to reduce current cohort that is already labeled with overlap reduce_by = tasks_with_overlap_count - new_tasks_with_overlap_count reduce_tasks = sample_query(tasks_with_overlap, reduce_by) reduce_tasks.update(overlap=1) reduced_tasks_ids = reduce_tasks.values_list('id', flat=True) tasks_with_overlap.exclude(id__in=reduced_tasks_ids).update(overlap=self.maximum_annotations) elif tasks_with_overlap_count < new_tasks_with_overlap_count: increase_by = new_tasks_with_overlap_count - tasks_with_overlap_count tasks_without_overlap = self.tasks.filter(overlap=1) increase_tasks = sample_query(tasks_without_overlap, increase_by) increase_tasks.update(overlap=self.maximum_annotations) tasks_with_overlap.update(overlap=self.maximum_annotations) def remove_tasks_by_file_uploads(self, file_upload_ids): self.tasks.filter(file_upload_id__in=file_upload_ids).delete() def advance_onboarding(self): """ Move project to next onboarding step """ po_qs = self.steps_left.order_by('step__order') count = po_qs.count() if count: po = po_qs.first() po.finished = True po.save() return count != 1 def created_at_prettify(self): return self.created_at.strftime("%d %b %Y %H:%M:%S") def onboarding_step_finished(self, step): """ Mark specific step as finished """ pos = ProjectOnboardingSteps.objects.get(code=step) po = ProjectOnboarding.objects.get(project=self, step=pos) po.finished = True po.save() return po def data_types_json(self): return json.dumps(self.data_types) def available_data_keys(self): return sorted(list(self.data_types.keys())) @classmethod def validate_label_config(cls, config_string): validate_label_config(config_string) def validate_config(self, config_string): self.validate_label_config(config_string) if not hasattr(self, 'summary'): return if self.num_tasks == 0: logger.debug(f'Project {self} has no tasks: nothing to validate here. Ensure project summary is empty') self.summary.reset() return # validate data columns consistency fields_from_config = get_all_object_tag_names(config_string) if not fields_from_config: logger.debug(f'Data fields not found in labeling config') return fields_from_data = set(self.summary.common_data_columns) fields_from_data.discard(settings.DATA_UNDEFINED_NAME) if fields_from_data and not fields_from_config.issubset(fields_from_data): different_fields = list(fields_from_config.difference(fields_from_data)) raise LabelStudioValidationErrorSentryIgnored(f'These fields are not present in the data: {",".join(different_fields)}') if self.num_annotations == 0: logger.debug(f'Project {self} has no annotations: nothing to validate here. ' f'Ensure annotations-related project summary is empty') self.summary.reset(tasks_data_based=False) return # validate annotations consistency annotations_from_config = set(get_all_control_tag_tuples(config_string)) if not annotations_from_config: logger.debug(f'Annotation schema is not found in config') return annotations_from_data = set(self.summary.created_annotations) if annotations_from_data and not annotations_from_data.issubset(annotations_from_config): different_annotations = list(annotations_from_data.difference(annotations_from_config)) diff_str = [] for ann_tuple in different_annotations: from_name, to_name, t = ann_tuple.split('|') diff_str.append( f'{self.summary.created_annotations[ann_tuple]} ' f'with from_name={from_name}, to_name={to_name}, type={t}') diff_str = '\n'.join(diff_str) raise LabelStudioValidationErrorSentryIgnored( f'Created annotations are incompatible with provided labeling schema, we found:\n{diff_str}') # validate labels consistency labels_from_config = get_all_labels(config_string) created_labels = self.summary.created_labels for control_tag_from_data, labels_from_data in created_labels.items(): # Check if labels created in annotations, and their control tag has been removed if labels_from_data and control_tag_from_data not in labels_from_config: raise LabelStudioValidationErrorSentryIgnored( f'There are {sum(labels_from_data.values(), 0)} annotation(s) created with tag ' f'"{control_tag_from_data}", you can\'t remove it') labels_from_config_by_tag = set(labels_from_config[control_tag_from_data]) if not set(labels_from_data).issubset(set(labels_from_config_by_tag)): different_labels = list(set(labels_from_data).difference(labels_from_config_by_tag)) diff_str = '\n'.join(f'{l} ({labels_from_data[l]} annotations)' for l in different_labels) raise LabelStudioValidationErrorSentryIgnored(f'These labels still exist in annotations:\n{diff_str}') def _label_config_has_changed(self): return self.label_config != self.__original_label_config def delete_predictions(self): predictions = Prediction.objects.filter(task__project=self) count = predictions.count() predictions.delete() return {'deleted_predictions': count} def get_updated_weights(self): outputs = parse_config(self.label_config) control_weights = {} exclude_control_types = ('Filter',) for control_name in outputs: control_type = outputs[control_name]['type'] if control_type in exclude_control_types: continue control_weights[control_name] = { 'overall': 1.0, 'type': control_type, 'labels': {label: 1.0 for label in outputs[control_name].get('labels', [])} } return control_weights def save(self, *args, recalc=True, **kwargs): exists = True if self.pk else False if self.label_config and (self._label_config_has_changed() or not exists or not self.control_weights): self.control_weights = self.get_updated_weights() super(Project, self).save(*args, **kwargs) project_with_config_just_created = not exists and self.pk and self.label_config if self._label_config_has_changed() or project_with_config_just_created: self.data_types = extract_data_types(self.label_config) if self._label_config_has_changed(): self.__original_label_config = self.label_config if not exists: steps = ProjectOnboardingSteps.objects.all() objs = [ProjectOnboarding(project=self, step=step) for step in steps] ProjectOnboarding.objects.bulk_create(objs) # argument for recalculate project task stats if recalc: self.update_tasks_states( maximum_annotations_changed=self.__maximum_annotations != self.maximum_annotations, overlap_cohort_percentage_changed=self.__overlap_cohort_percentage != self.overlap_cohort_percentage, tasks_number_changed=False ) self.__maximum_annotations = self.maximum_annotations self.__overlap_cohort_percentage = self.overlap_cohort_percentage if hasattr(self, 'summary'): # Ensure project.summary is consistent with current tasks / annotations if self.num_tasks == 0: self.summary.reset() elif self.num_annotations == 0: self.summary.reset(tasks_data_based=False) def get_member_ids(self): if hasattr(self, 'team_link'): # project has defined team scope # TODO: avoid checking team but rather add all project members when creating a project return self.team_link.team.members.values_list('user', flat=True) else: from users.models import User # TODO: may want to return all users from organization return User.objects.none() def has_team_user(self, user): return hasattr(self, 'team_link') and self.team_link.team.has_user(user) def annotators(self): """ Annotators connected to this project including team members """ from users.models import User member_ids = self.get_member_ids() team_members = User.objects.filter(id__in=member_ids).order_by('email') # add members from invited projects project_member_ids = self.members.values_list('user__id', flat=True) project_members = User.objects.filter(id__in=project_member_ids) annotators = team_members | project_members # set annotator.team_member=True if annotator is not an invited user annotators = annotators.annotate( team_member=Case( When(id__in=project_member_ids, then=Value(False)), default=Value(True), output_field=BooleanField(), ) ) return annotators def annotators_with_annotations(self, min_count=500): """ Annotators with annotation number > min_number :param min_count: minimal annotation number to leave an annotators :return: filtered annotators """ annotators = self.annotators() q = Q(annotations__task__project=self) & Q_task_finished_annotations & Q(annotations__ground_truth=False) annotators = annotators.annotate(annotation_count=Count('annotations', filter=q, distinct=True)) return annotators.filter(annotation_count__gte=min_count) def labeled_tasks(self): return self.tasks.filter(is_labeled=True) def has_annotations(self): from tasks.models import Annotation # prevent cycling imports return Annotation.objects.filter(Q(task__project=self) & Q(ground_truth=False)).count() > 0 # [TODO] this should be a template tag or something like this @property def label_config_line(self): c = self.label_config return config_line_stipped(c) def get_sample_task(self, label_config=None): config = label_config or self.label_config task, _, _ = get_sample_task(config) return task def eta(self): """ Show eta for project to be finished eta = avg task annotations finish time * remain annotations task has overlap = amount of task annotations to consider as finished (is_labeled) remain annotations = sum ( task annotations to be done to fulfill each unfinished task overlap) :return: time in seconds """ # finished tasks * overlap finished_tasks = Task.objects.filter(project=self.id, is_labeled=True) # one could make more than need to overlap min_n_finished_annotations = sum([ft.overlap for ft in finished_tasks]) annotations_unfinished_tasks = Annotation.objects.filter( task__project=self.id, task__is_labeled=False, ground_truth=False, result__isnull=False).count() # get minimum remain annotations total_annotations_needed = self.get_total_possible_count annotations_remain = total_annotations_needed - min_n_finished_annotations - annotations_unfinished_tasks # get average time of all finished TC finished_annotations = Annotation.objects.filter( Q(task__project=self.id) & Q(ground_truth=False), result__isnull=False).values('lead_time') avg_lead_time = finished_annotations.aggregate(avg_lead_time=Avg('lead_time'))['avg_lead_time'] if avg_lead_time is None: return None return avg_lead_time * annotations_remain def finished(self): return not self.tasks.filter(is_labeled=False).exists() def annotations_lead_time(self): annotations = Annotation.objects.filter(Q(task__project=self.id) & Q(ground_truth=False)) return annotations.aggregate(avg_lead_time=Avg('lead_time'))['avg_lead_time'] @staticmethod def django_settings(): return settings @staticmethod def max_tasks_file_size(): return settings.TASKS_MAX_FILE_SIZE def get_control_tags_from_config(self): return parse_config(self.label_config) def get_parsed_config(self): return parse_config(self.label_config) def __str__(self): return f'{self.title} (id={self.id})' or _("Business number %d") % self.pk class Meta: db_table = 'project' class ProjectOnboardingSteps(models.Model): """ """ DATA_UPLOAD = "DU" CONF_SETTINGS = "CF" PUBLISH = "PB" INVITE_EXPERTS = "IE" STEPS_CHOICES = ( (DATA_UPLOAD, "Import your data"), (CONF_SETTINGS, "Configure settings"), (PUBLISH, "Publish project"), (INVITE_EXPERTS, "Invite collaborators") ) code = models.CharField(max_length=2, choices=STEPS_CHOICES, null=True) title = models.CharField(_('title'), max_length=1000, null=False) description = models.TextField(_('description'), null=False) order = models.IntegerField(default=0) created_at = models.DateTimeField(_('created at'), auto_now_add=True) updated_at = models.DateTimeField(_('updated at'), auto_now=True) class Meta: ordering = ['order'] class ProjectOnboarding(models.Model): """ """ step = models.ForeignKey(ProjectOnboardingSteps, on_delete=models.CASCADE, related_name="po_through") project = models.ForeignKey(Project, on_delete=models.CASCADE) finished = models.BooleanField(default=False) created_at = models.DateTimeField(_('created at'), auto_now_add=True) updated_at = models.DateTimeField(_('updated at'), auto_now=True) def save(self, *args, **kwargs): super(ProjectOnboarding, self).save(*args, **kwargs) if ProjectOnboarding.objects.filter(project=self.project, finished=True).count() == 4: self.project.skip_onboarding = True self.project.save(recalc=False) class ProjectMember(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='project_memberships', help_text='User ID') # noqa project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='members', help_text='Project ID') enabled = models.BooleanField(default=True, help_text='Project member is enabled') created_at = models.DateTimeField(_('created at'), auto_now_add=True) updated_at = models.DateTimeField(_('updated at'), auto_now=True) class ProjectSummary(models.Model): project = AutoOneToOneField(Project, primary_key=True, on_delete=models.CASCADE, related_name='summary') created_at = models.DateTimeField(_('created at'), auto_now_add=True, help_text='Creation time') # { col1: task_count_with_col1, col2: task_count_with_col2 } all_data_columns = JSONField( _('all data columns'), null=True, default=dict, help_text='All data columns found in imported tasks') # [col1, col2] common_data_columns = JSONField( _('common data columns'), null=True, default=list, help_text='Common data columns found across imported tasks') # { (from_name, to_name, type): annotation_count } created_annotations = JSONField( _('created annotations'), null=True, default=dict, help_text='Unique annotation types identified by tuple (from_name, to_name, type)') # noqa # { from_name: {label1: task_count_with_label1, label2: task_count_with_label2} } created_labels = JSONField( _('created labels'), null=True, default=dict, help_text='Unique labels') def has_permission(self, user): return self.project.has_permission(user) def reset(self, tasks_data_based=True): if tasks_data_based: self.all_data_columns = {} self.common_data_columns = [] self.created_annotations = {} self.created_labels = {} self.save() def update_data_columns(self, tasks): common_data_columns = set() all_data_columns = dict(self.all_data_columns) for task in tasks: try: task_data = get_attr_or_item(task, 'data') except KeyError: task_data = task task_data_keys = task_data.keys() for column in task_data_keys: all_data_columns[column] = all_data_columns.get(column, 0) + 1 if not common_data_columns: common_data_columns = set(task_data_keys) else: common_data_columns &= set(task_data_keys) self.all_data_columns = all_data_columns if not self.common_data_columns: self.common_data_columns = list(sorted(common_data_columns)) else: self.common_data_columns = list(sorted(set(self.common_data_columns) & common_data_columns)) logger.debug(f'summary.all_data_columns = {self.all_data_columns}') logger.debug(f'summary.common_data_columns = {self.common_data_columns}') self.save() def remove_data_columns(self, tasks): all_data_columns = dict(self.all_data_columns) keys_to_remove = [] for task in tasks: task_data = get_attr_or_item(task, 'data') for key in task_data.keys(): if key in all_data_columns: all_data_columns[key] -= 1 if all_data_columns[key] == 0: keys_to_remove.append(key) all_data_columns.pop(key) self.all_data_columns = all_data_columns if keys_to_remove: common_data_columns = list(self.common_data_columns) for key in keys_to_remove: if key in common_data_columns: common_data_columns.remove(key) self.common_data_columns = common_data_columns logger.debug(f'summary.all_data_columns = {self.all_data_columns}') logger.debug(f'summary.common_data_columns = {self.common_data_columns}') self.save() def _get_annotation_key(self, result): result_type = result.get('type', None) if result_type in ('relation', 'pairwise', None): return None if 'from_name' not in result or 'to_name' not in result: logger.error( 'Unexpected annotation.result format: "from_name" or "to_name" not found in %r', result, extra={'sentry_skip': True} ) return None result_from_name = result['from_name'] key = get_annotation_tuple(result_from_name, result['to_name'], result_type or '') return key def _get_labels(self, result): result_type = result.get('type') result_value = result['value'].get(result_type) if not result_value or not isinstance(result_value, list) or result_type == 'text': # Non-list values are not labels. TextArea list values (texts) are not labels too. return [] # Labels are stored in list labels = [] for label in result_value: labels.append(str(label)) return labels def update_created_annotations_and_labels(self, annotations): created_annotations = dict(self.created_annotations) labels = dict(self.created_labels) for annotation in annotations: results = get_attr_or_item(annotation, 'result') or [] if not isinstance(results, list): continue for result in results: # aggregate annotation types key = self._get_annotation_key(result) if not key: continue created_annotations[key] = created_annotations.get(key, 0) + 1 from_name = result['from_name'] # aggregate labels if from_name not in self.created_labels: labels[from_name] = dict() for label in self._get_labels(result): labels[from_name][label] = labels[from_name].get(label, 0) + 1 logger.debug(f'summary.created_annotations = {created_annotations}') logger.debug(f'summary.created_labels = {labels}') self.created_annotations = created_annotations self.created_labels = labels self.save() def remove_created_annotations_and_labels(self, annotations): created_annotations = dict(self.created_annotations) labels = dict(self.created_labels) for annotation in annotations: results = get_attr_or_item(annotation, 'result') or [] if not isinstance(results, list): continue for result in results: # reduce annotation counters key = self._get_annotation_key(result) if key in created_annotations: created_annotations[key] -= 1 if created_annotations[key] == 0: created_annotations.pop(key) # reduce labels counters from_name = result.get('from_name', None) if from_name not in labels: continue for label in self._get_labels(result): label = str(label) if label in labels[from_name]: labels[from_name][label] -= 1 if labels[from_name][label] == 0: labels[from_name].pop(label) if not labels[from_name]: labels.pop(from_name) logger.debug(f'summary.created_annotations = {created_annotations}') logger.debug(f'summary.created_labels = {labels}') self.created_annotations = created_annotations self.created_labels = labels self.save()
# Copyright (c) 2018-2021 Patricio Cubillos. # bibmanager is open-source software under the MIT license (see LICENSE). __all__ = [ 'browse', ] import re import os from asyncio import Future, ensure_future import io from contextlib import redirect_stdout import textwrap import webbrowser from prompt_toolkit import print_formatted_text, search from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app from prompt_toolkit.buffer import Buffer from prompt_toolkit.completion import PathCompleter, WordCompleter from prompt_toolkit.filters import Condition from prompt_toolkit.formatted_text import PygmentsTokens from prompt_toolkit.formatted_text.utils import fragment_list_to_text from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.key_binding.bindings.scroll import ( scroll_half_page_down, scroll_half_page_up,) from prompt_toolkit.layout.containers import ( Float, FloatContainer, HSplit, VSplit, Window, WindowAlign,) from prompt_toolkit.layout.controls import FormattedTextControl from prompt_toolkit.layout.dimension import D from prompt_toolkit.layout.layout import Layout from prompt_toolkit.layout.menus import CompletionsMenu from prompt_toolkit.layout.processors import Transformation, Processor from prompt_toolkit.layout.utils import explode_text_fragments from prompt_toolkit.lexers import PygmentsLexer from prompt_toolkit.selection import PasteMode from prompt_toolkit.styles import Style, style_from_pygments_cls, merge_styles from prompt_toolkit.widgets import ( Button, Dialog, Label, SearchToolbar, TextArea,) import pygments from pygments.lexers.bibtex import BibTeXLexer from . import bib_manager as bm from .. import config_manager as cm from .. import pdf_manager as pm from .. import utils as u from ..__init__ import __version__ as ver help_message = f"""\ h Show this message enter Select/unselect entry for saving s Save selected entries to file or screen output f,/,? Start forward (f or /) or reverse (?) search e Expand/collapse content of current entry E Expand/collapse all entries o Open PDF of entry (ask to fetch if needed) b Open entry in ADS throught the web browser q Quit Navigation Arrow keys Move up, down, left, and right g/G Go to first/last line u/d Scroll up/down n/N Go to next/previous search occurrence This is bibmanager version {ver} Created by Patricio Cubillos.""" class TextInputDialog: """Hello, this is doc""" def __init__(self, title="", label_text="", completer=None): self.future = Future() def accept_text(buf): buf.complete_state = None self.future.set_result(self.text_area.text) if self.text_area.text == "": get_app().exit() self.text_area = TextArea( completer=completer, multiline=False, width=D(preferred=40), accept_handler=accept_text, ) self.dialog = Dialog( title=title, body=HSplit([ Label(text=label_text), self.text_area, Label(text="")]), width=D(preferred=75), modal=True, ) def __pt_container__(self): return self.dialog class MessageDialog: def __init__(self, title, text, asking=False): self.future = Future() def set_done(): self.future.set_result(None) def accept(): self.future.set_result(True) def cancel(): self.future.set_result(False) if asking: buttons = [ Button(text="Yes", handler=accept), Button(text="No", handler=cancel), ] else: buttons = [Button(text="OK", handler=set_done)] text = "\n".join([ textwrap.fill(line, width=71) for line in text.splitlines() ]) self.dialog = Dialog( title=title, body=HSplit([Label(text=text)]), buttons=buttons, width=D(preferred=75), modal=True, ) def __pt_container__(self): return self.dialog def show_message(title, text): async def coroutine(): dialog = MessageDialog(title, text) await show_dialog_as_float(dialog) ensure_future(coroutine()) async def show_dialog_as_float(dialog): """Coroutine.""" app = get_app() root_container = app.layout.container float_ = Float(content=dialog) root_container.floats.insert(0, float_) focused_before = app.layout.current_window app.layout.focus(dialog) app.layout.current_window.dialog = dialog result = await dialog.future if hasattr(app.layout.current_window, 'dialog'): del(app.layout.current_window.dialog) app.layout.focus(focused_before) if float_ in root_container.floats: root_container.floats.remove(float_) return result class HighlightEntryProcessor(Processor): """Processor to highlight a list of texts in the document.""" match_fragment = " class:search " selected_entries = [] def toggle_selected_entry(self, entry_key): """Select/deselect entry_key from the list of highlighted texts.""" if entry_key in self.selected_entries: self.selected_entries.remove(entry_key) else: self.selected_entries.append(entry_key) def apply_transformation(self, transformation_input): ( buffer_control, document, lineno, source_to_display, fragments, _, _, ) = transformation_input.unpack() if self.selected_entries and not get_app().is_done: # For each search match, replace the style string. line_text = fragment_list_to_text(fragments) fragments = explode_text_fragments(fragments) pattern = "|".join(re.escape(key) for key in self.selected_entries) matches = re.finditer(pattern, line_text, flags=re.RegexFlag(0)) for match in matches: for i in range(match.start(), match.end()): old_fragment, text, *_ = fragments[i] fragments[i] = ( old_fragment + self.match_fragment, fragments[i][1], ) return Transformation(fragments) def get_current_key(doc, keys, get_start_end=False, get_expanded=False): """ Get the key for the bibtex entry currently under the cursor. """ position = doc.cursor_position if doc.current_line in keys: is_expanded = False key = doc.current_line if get_start_end: start_pos = position + doc.get_start_of_line_position() end_pos = position + doc.get_end_of_line_position() else: is_expanded = True start_pos = position if doc.current_char != '@': start_pos += doc.find_backwards('@') key_start = doc.text.find('{', start_pos) key_end = doc.text.find(',', start_pos) key = doc.text[key_start+1:key_end].strip() if get_start_end: end_pos = u.find_closing_bracket(doc.text, start_pos) + 2 if not (get_start_end or get_expanded): return key output = [key] if get_start_end: output.append((start_pos, end_pos)) if get_expanded: output.append(is_expanded) return tuple(output) def browse(): """ A browser for the bibmanager database. """ # Content of the text buffer: bibs = bm.load() keys = [bib.key for bib in bibs] compact_text = "\n".join(keys) expanded_text = "\n\n".join(bib.content for bib in bibs) # A list object, since I want this to be a global variable selected_content = [None] lex_style = style_from_pygments_cls( pygments.styles.get_style_by_name(cm.get('style'))) custom_style = Style.from_dict({ "status": "reverse", "status.position": "#aaaa00", "status.key": "#ffaa00", "shadow": "bg:#440044", "not-searching": "#888888", }) style = merge_styles([lex_style, custom_style]) def get_menubar_text(): return [ ("class:status", " ("), ("class:status.key", "enter"), ("class:status", ")select entry ("), ("class:status.key", "e"), ("class:status", ")xpand entry ("), ("class:status.key", "f"), ("class:status", ")ind ("), ("class:status.key", "s"), ("class:status", ")ave ("), ("class:status.key", "h"), ("class:status", ")elp ("), ("class:status.key", "q"), ("class:status", ")uit"), ] def get_menubar_right_text(): """Get index of entry under cursor.""" key = get_current_key(text_field.buffer.document, keys) return f" {keys.index(key) + 1} " def get_infobar_text(): """Get author-year-title of entry under cursor.""" key = get_current_key(text_field.buffer.document, keys) bib = bibs[keys.index(key)] year = '' if bib.year is None else bib.year title = 'NO_TITLE' if bib.title is None else bib.title return f"{bib.get_authors("ushort")}{year}: {title}" search_buffer = Buffer( completer=WordCompleter(keys), complete_while_typing=False, multiline=False) search_field = SearchToolbar( search_buffer=search_buffer, forward_search_prompt = "Search: ", backward_search_prompt = "Search backward: ", ignore_case=False) text_field = TextArea( text=compact_text, lexer=PygmentsLexer(BibTeXLexer), scrollbar=True, line_numbers=False, read_only=True, search_field=search_field, input_processors=[HighlightEntryProcessor()], ) text_field.buffer.name = 'text_area_buffer' text_field.is_expanded = False # Shortcut to HighlightEntryProcessor: for processor in text_field.control.input_processors: if processor.__class__.__name__ == 'HighlightEntryProcessor': text_field.bm_processor = processor # Do not highlight searched text: sp = text_field.control.default_input_processors[0] sp._classname = ' ' sp._classname_current = ' ' menu_bar = VSplit([ Window( FormattedTextControl(get_menubar_text), style="class:status"), Window( FormattedTextControl(get_menubar_right_text), style="class:status.right", width=9, align=WindowAlign.RIGHT), ], height=1, ) info_bar = Window( content=FormattedTextControl(get_infobar_text), height=D.exact(1), style="class:status", ) body = HSplit([ menu_bar, text_field, search_field, info_bar, ]) root_container = FloatContainer( content=body, floats=[ Float( xcursor=True, ycursor=True, content=CompletionsMenu(max_height=16, scroll_offset=1), ), ], ) # Key bindings: bindings = KeyBindings() text_focus = Condition( lambda: get_app().layout.current_window == text_field.window) dialog_focus = Condition( lambda: hasattr(get_app().layout.current_window, 'dialog')) @bindings.add("q", filter=text_focus) def _quit(event): event.app.exit() # Navigation: @bindings.add("g", filter=text_focus) def _go_to_first_line(event): event.current_buffer.cursor_position = 0 @bindings.add("G", filter=text_focus) def _go_to_last_line(event) -> None: event.current_buffer.cursor_position = len(event.current_buffer.text) @bindings.add("d", filter=text_focus) def _scroll_down(event): scroll_half_page_down(event) @bindings.add("u", filter=text_focus) def _scroll_up(event): scroll_half_page_up(event) @bindings.add("n", filter=text_focus) def _find_next(event): search_state = event.app.current_search_state event.current_buffer.apply_search( search_state, include_current_position=False, count=event.arg) @bindings.add("N", filter=text_focus) def _find_previous(event): search_state = event.app.current_search_state event.current_buffer.apply_search( ~search_state, include_current_position=False, count=event.arg) @bindings.add("h", filter=text_focus) def _show_help(event): show_message("Shortcuts", help_message) @bindings.add("f", filter=text_focus) def _start_search(event): search.start_search(direction=search.SearchDirection.FORWARD) @bindings.add("b", filter=text_focus) def _open_in_browser(event): key = get_current_key(event.current_buffer.document, keys) bib = bm.find(key=key, bibs=bibs) if bib.adsurl is not None: webbrowser.open(bib.adsurl, new=2) else: show_message("Message", f"Entry '{key}' does not have an ADS url.") @bindings.add("c-c", filter=dialog_focus) def _close_dialog(event): get_app().layout.current_window.dialog.future.set_result(None) @bindings.add("s", filter=text_focus) def _save_selected_to_file(event): selected = text_field.bm_processor.selected_entries if len(selected) == 0: show_message("Message", "Nothing to save.") return async def coroutine(): dialog = TextInputDialog( title="Save to File", label_text="\nEnter a file path or leave blank to quit " "and print to screen:\n(press Control-c to cancel)\n", completer=PathCompleter(), ) path = await show_dialog_as_float(dialog) content = '\n\n'.join( bibs[keys.index(key)].content for key in selected) if path == "": selected_content[0] = content # The program termination is in TextInputDialog() since I # need to close this coroutine first. return if path is not None: try: with open(path, "w") as f: f.write(content) except IOError as e: show_message("Error", str(e)) ensure_future(coroutine()) @bindings.add("enter", filter=text_focus) def _toggle_selected_entry(event): "Select/deselect entry pointed by the cursor." key = get_current_key(event.current_buffer.document, keys) text_field.bm_processor.toggle_selected_entry(key) @bindings.add("e", filter=text_focus) def _expand_collapse_entry(event): "Expand/collapse current entry." key, start_end, is_expanded = get_current_key( event.current_buffer.document, keys, get_start_end=True, get_expanded=True) bib = bm.find(key=key, bibs=bibs) if is_expanded: event.app.clipboard.set_text(bib.key) else: event.app.clipboard.set_text(bib.content + '\n') text_field.read_only = False event.current_buffer.cursor_position = start_end[0] event.current_buffer.delete(count=start_end[1] - start_end[0]) event.current_buffer.paste_clipboard_data( event.app.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.VI_BEFORE) text_field.read_only = True if is_expanded: event.current_buffer.cursor_position = start_end[0] @bindings.add("E", filter=text_focus) def _expand_collapse_all(event): "Expand/collapse all entries." buffer = event.current_buffer key = get_current_key(buffer.document, keys) if text_field.is_expanded: text_field.text = compact_text else: text_field.text = expanded_text buffer.cursor_position = buffer.text.index(key) text_field.is_expanded = not text_field.is_expanded @bindings.add("o", filter=text_focus) def _open_pdf(event): buffer = event.current_buffer key = get_current_key(buffer.document, keys) bib = bm.find(key=key, bibs=bibs) has_pdf = bib.pdf is not None has_bibcode = bib.bibcode is not None is_missing = has_pdf and not os.path.exists(f'{u.BM_PDF()}{bib.pdf}') if not has_pdf and not has_bibcode: show_message("Message", f"BibTeX entry '{key}' does not have a PDF.") return if has_pdf and not is_missing: pm.open(key=key) #except Exception as e: # show_message("Message", textwrap.fill(str(e), width=70)) return if has_pdf and is_missing and not has_bibcode: show_message("Message", f"BibTeX entry has a PDF file: {bib.pdf}, but the file " "could not be found.") return # Need to fetch before opening: async def coroutine(): dialog = MessageDialog( "PDF file not found", "Fetch from ADS?\n(might take a few seconds ...)", asking=True) fetch = await show_dialog_as_float(dialog) if fetch: with io.StringIO() as buf, redirect_stdout(buf): fetched = pm.fetch(bib.bibcode, replace=True) fetch_output = buf.getvalue() if fetched is None: show_message("PDF fetch failed", fetch_output) else: show_message("PDF fetch succeeded.", fetch_output) pm.open(key=key) ensure_future(coroutine()) application = Application( layout=Layout(root_container, focused_element=text_field), key_bindings=bindings, enable_page_navigation_bindings=True, style=style, full_screen=True, ) application.run() if selected_content[0] is not None: tokens = list(pygments.lex(selected_content[0], lexer=BibTeXLexer())) print_formatted_text( PygmentsTokens(tokens), end="", style=lex_style, #output=create_output(sys.stdout), )
# Copyright (c) 2018-2021 Patricio Cubillos. # bibmanager is open-source software under the MIT license (see LICENSE). __all__ = [ 'browse', ] import re import os from asyncio import Future, ensure_future import io from contextlib import redirect_stdout import textwrap import webbrowser from prompt_toolkit import print_formatted_text, search from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app from prompt_toolkit.buffer import Buffer from prompt_toolkit.completion import PathCompleter, WordCompleter from prompt_toolkit.filters import Condition from prompt_toolkit.formatted_text import PygmentsTokens from prompt_toolkit.formatted_text.utils import fragment_list_to_text from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.key_binding.bindings.scroll import ( scroll_half_page_down, scroll_half_page_up,) from prompt_toolkit.layout.containers import ( Float, FloatContainer, HSplit, VSplit, Window, WindowAlign,) from prompt_toolkit.layout.controls import FormattedTextControl from prompt_toolkit.layout.dimension import D from prompt_toolkit.layout.layout import Layout from prompt_toolkit.layout.menus import CompletionsMenu from prompt_toolkit.layout.processors import Transformation, Processor from prompt_toolkit.layout.utils import explode_text_fragments from prompt_toolkit.lexers import PygmentsLexer from prompt_toolkit.selection import PasteMode from prompt_toolkit.styles import Style, style_from_pygments_cls, merge_styles from prompt_toolkit.widgets import ( Button, Dialog, Label, SearchToolbar, TextArea,) import pygments from pygments.lexers.bibtex import BibTeXLexer from . import bib_manager as bm from .. import config_manager as cm from .. import pdf_manager as pm from .. import utils as u from ..__init__ import __version__ as ver help_message = f"""\ h Show this message enter Select/unselect entry for saving s Save selected entries to file or screen output f,/,? Start forward (f or /) or reverse (?) search e Expand/collapse content of current entry E Expand/collapse all entries o Open PDF of entry (ask to fetch if needed) b Open entry in ADS throught the web browser q Quit Navigation Arrow keys Move up, down, left, and right g/G Go to first/last line u/d Scroll up/down n/N Go to next/previous search occurrence This is bibmanager version {ver} Created by Patricio Cubillos.""" class TextInputDialog: """Hello, this is doc""" def __init__(self, title="", label_text="", completer=None): self.future = Future() def accept_text(buf): buf.complete_state = None self.future.set_result(self.text_area.text) if self.text_area.text == "": get_app().exit() self.text_area = TextArea( completer=completer, multiline=False, width=D(preferred=40), accept_handler=accept_text, ) self.dialog = Dialog( title=title, body=HSplit([ Label(text=label_text), self.text_area, Label(text="")]), width=D(preferred=75), modal=True, ) def __pt_container__(self): return self.dialog class MessageDialog: def __init__(self, title, text, asking=False): self.future = Future() def set_done(): self.future.set_result(None) def accept(): self.future.set_result(True) def cancel(): self.future.set_result(False) if asking: buttons = [ Button(text="Yes", handler=accept), Button(text="No", handler=cancel), ] else: buttons = [Button(text="OK", handler=set_done)] text = "\n".join([ textwrap.fill(line, width=71) for line in text.splitlines() ]) self.dialog = Dialog( title=title, body=HSplit([Label(text=text)]), buttons=buttons, width=D(preferred=75), modal=True, ) def __pt_container__(self): return self.dialog def show_message(title, text): async def coroutine(): dialog = MessageDialog(title, text) await show_dialog_as_float(dialog) ensure_future(coroutine()) async def show_dialog_as_float(dialog): """Coroutine.""" app = get_app() root_container = app.layout.container float_ = Float(content=dialog) root_container.floats.insert(0, float_) focused_before = app.layout.current_window app.layout.focus(dialog) app.layout.current_window.dialog = dialog result = await dialog.future if hasattr(app.layout.current_window, 'dialog'): del(app.layout.current_window.dialog) app.layout.focus(focused_before) if float_ in root_container.floats: root_container.floats.remove(float_) return result class HighlightEntryProcessor(Processor): """Processor to highlight a list of texts in the document.""" match_fragment = " class:search " selected_entries = [] def toggle_selected_entry(self, entry_key): """Select/deselect entry_key from the list of highlighted texts.""" if entry_key in self.selected_entries: self.selected_entries.remove(entry_key) else: self.selected_entries.append(entry_key) def apply_transformation(self, transformation_input): ( buffer_control, document, lineno, source_to_display, fragments, _, _, ) = transformation_input.unpack() if self.selected_entries and not get_app().is_done: # For each search match, replace the style string. line_text = fragment_list_to_text(fragments) fragments = explode_text_fragments(fragments) pattern = "|".join(re.escape(key) for key in self.selected_entries) matches = re.finditer(pattern, line_text, flags=re.RegexFlag(0)) for match in matches: for i in range(match.start(), match.end()): old_fragment, text, *_ = fragments[i] fragments[i] = ( old_fragment + self.match_fragment, fragments[i][1], ) return Transformation(fragments) def get_current_key(doc, keys, get_start_end=False, get_expanded=False): """ Get the key for the bibtex entry currently under the cursor. """ position = doc.cursor_position if doc.current_line in keys: is_expanded = False key = doc.current_line if get_start_end: start_pos = position + doc.get_start_of_line_position() end_pos = position + doc.get_end_of_line_position() else: is_expanded = True start_pos = position if doc.current_char != '@': start_pos += doc.find_backwards('@') key_start = doc.text.find('{', start_pos) key_end = doc.text.find(',', start_pos) key = doc.text[key_start+1:key_end].strip() if get_start_end: end_pos = u.find_closing_bracket(doc.text, start_pos) + 2 if not (get_start_end or get_expanded): return key output = [key] if get_start_end: output.append((start_pos, end_pos)) if get_expanded: output.append(is_expanded) return tuple(output) def browse(): """ A browser for the bibmanager database. """ # Content of the text buffer: bibs = bm.load() keys = [bib.key for bib in bibs] compact_text = "\n".join(keys) expanded_text = "\n\n".join(bib.content for bib in bibs) # A list object, since I want this to be a global variable selected_content = [None] lex_style = style_from_pygments_cls( pygments.styles.get_style_by_name(cm.get('style'))) custom_style = Style.from_dict({ "status": "reverse", "status.position": "#aaaa00", "status.key": "#ffaa00", "shadow": "bg:#440044", "not-searching": "#888888", }) style = merge_styles([lex_style, custom_style]) def get_menubar_text(): return [ ("class:status", " ("), ("class:status.key", "enter"), ("class:status", ")select entry ("), ("class:status.key", "e"), ("class:status", ")xpand entry ("), ("class:status.key", "f"), ("class:status", ")ind ("), ("class:status.key", "s"), ("class:status", ")ave ("), ("class:status.key", "h"), ("class:status", ")elp ("), ("class:status.key", "q"), ("class:status", ")uit"), ] def get_menubar_right_text(): """Get index of entry under cursor.""" key = get_current_key(text_field.buffer.document, keys) return f" {keys.index(key) + 1} " def get_infobar_text(): """Get author-year-title of entry under cursor.""" key = get_current_key(text_field.buffer.document, keys) bib = bibs[keys.index(key)] year = '' if bib.year is None else bib.year title = 'NO_TITLE' if bib.title is None else bib.title return f"{bib.get_authors('ushort')}{year}: {title}" search_buffer = Buffer( completer=WordCompleter(keys), complete_while_typing=False, multiline=False) search_field = SearchToolbar( search_buffer=search_buffer, forward_search_prompt = "Search: ", backward_search_prompt = "Search backward: ", ignore_case=False) text_field = TextArea( text=compact_text, lexer=PygmentsLexer(BibTeXLexer), scrollbar=True, line_numbers=False, read_only=True, search_field=search_field, input_processors=[HighlightEntryProcessor()], ) text_field.buffer.name = 'text_area_buffer' text_field.is_expanded = False # Shortcut to HighlightEntryProcessor: for processor in text_field.control.input_processors: if processor.__class__.__name__ == 'HighlightEntryProcessor': text_field.bm_processor = processor # Do not highlight searched text: sp = text_field.control.default_input_processors[0] sp._classname = ' ' sp._classname_current = ' ' menu_bar = VSplit([ Window( FormattedTextControl(get_menubar_text), style="class:status"), Window( FormattedTextControl(get_menubar_right_text), style="class:status.right", width=9, align=WindowAlign.RIGHT), ], height=1, ) info_bar = Window( content=FormattedTextControl(get_infobar_text), height=D.exact(1), style="class:status", ) body = HSplit([ menu_bar, text_field, search_field, info_bar, ]) root_container = FloatContainer( content=body, floats=[ Float( xcursor=True, ycursor=True, content=CompletionsMenu(max_height=16, scroll_offset=1), ), ], ) # Key bindings: bindings = KeyBindings() text_focus = Condition( lambda: get_app().layout.current_window == text_field.window) dialog_focus = Condition( lambda: hasattr(get_app().layout.current_window, 'dialog')) @bindings.add("q", filter=text_focus) def _quit(event): event.app.exit() # Navigation: @bindings.add("g", filter=text_focus) def _go_to_first_line(event): event.current_buffer.cursor_position = 0 @bindings.add("G", filter=text_focus) def _go_to_last_line(event) -> None: event.current_buffer.cursor_position = len(event.current_buffer.text) @bindings.add("d", filter=text_focus) def _scroll_down(event): scroll_half_page_down(event) @bindings.add("u", filter=text_focus) def _scroll_up(event): scroll_half_page_up(event) @bindings.add("n", filter=text_focus) def _find_next(event): search_state = event.app.current_search_state event.current_buffer.apply_search( search_state, include_current_position=False, count=event.arg) @bindings.add("N", filter=text_focus) def _find_previous(event): search_state = event.app.current_search_state event.current_buffer.apply_search( ~search_state, include_current_position=False, count=event.arg) @bindings.add("h", filter=text_focus) def _show_help(event): show_message("Shortcuts", help_message) @bindings.add("f", filter=text_focus) def _start_search(event): search.start_search(direction=search.SearchDirection.FORWARD) @bindings.add("b", filter=text_focus) def _open_in_browser(event): key = get_current_key(event.current_buffer.document, keys) bib = bm.find(key=key, bibs=bibs) if bib.adsurl is not None: webbrowser.open(bib.adsurl, new=2) else: show_message("Message", f"Entry '{key}' does not have an ADS url.") @bindings.add("c-c", filter=dialog_focus) def _close_dialog(event): get_app().layout.current_window.dialog.future.set_result(None) @bindings.add("s", filter=text_focus) def _save_selected_to_file(event): selected = text_field.bm_processor.selected_entries if len(selected) == 0: show_message("Message", "Nothing to save.") return async def coroutine(): dialog = TextInputDialog( title="Save to File", label_text="\nEnter a file path or leave blank to quit " "and print to screen:\n(press Control-c to cancel)\n", completer=PathCompleter(), ) path = await show_dialog_as_float(dialog) content = '\n\n'.join( bibs[keys.index(key)].content for key in selected) if path == "": selected_content[0] = content # The program termination is in TextInputDialog() since I # need to close this coroutine first. return if path is not None: try: with open(path, "w") as f: f.write(content) except IOError as e: show_message("Error", str(e)) ensure_future(coroutine()) @bindings.add("enter", filter=text_focus) def _toggle_selected_entry(event): "Select/deselect entry pointed by the cursor." key = get_current_key(event.current_buffer.document, keys) text_field.bm_processor.toggle_selected_entry(key) @bindings.add("e", filter=text_focus) def _expand_collapse_entry(event): "Expand/collapse current entry." key, start_end, is_expanded = get_current_key( event.current_buffer.document, keys, get_start_end=True, get_expanded=True) bib = bm.find(key=key, bibs=bibs) if is_expanded: event.app.clipboard.set_text(bib.key) else: event.app.clipboard.set_text(bib.content + '\n') text_field.read_only = False event.current_buffer.cursor_position = start_end[0] event.current_buffer.delete(count=start_end[1] - start_end[0]) event.current_buffer.paste_clipboard_data( event.app.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.VI_BEFORE) text_field.read_only = True if is_expanded: event.current_buffer.cursor_position = start_end[0] @bindings.add("E", filter=text_focus) def _expand_collapse_all(event): "Expand/collapse all entries." buffer = event.current_buffer key = get_current_key(buffer.document, keys) if text_field.is_expanded: text_field.text = compact_text else: text_field.text = expanded_text buffer.cursor_position = buffer.text.index(key) text_field.is_expanded = not text_field.is_expanded @bindings.add("o", filter=text_focus) def _open_pdf(event): buffer = event.current_buffer key = get_current_key(buffer.document, keys) bib = bm.find(key=key, bibs=bibs) has_pdf = bib.pdf is not None has_bibcode = bib.bibcode is not None is_missing = has_pdf and not os.path.exists(f'{u.BM_PDF()}{bib.pdf}') if not has_pdf and not has_bibcode: show_message("Message", f"BibTeX entry '{key}' does not have a PDF.") return if has_pdf and not is_missing: pm.open(key=key) #except Exception as e: # show_message("Message", textwrap.fill(str(e), width=70)) return if has_pdf and is_missing and not has_bibcode: show_message("Message", f"BibTeX entry has a PDF file: {bib.pdf}, but the file " "could not be found.") return # Need to fetch before opening: async def coroutine(): dialog = MessageDialog( "PDF file not found", "Fetch from ADS?\n(might take a few seconds ...)", asking=True) fetch = await show_dialog_as_float(dialog) if fetch: with io.StringIO() as buf, redirect_stdout(buf): fetched = pm.fetch(bib.bibcode, replace=True) fetch_output = buf.getvalue() if fetched is None: show_message("PDF fetch failed", fetch_output) else: show_message("PDF fetch succeeded.", fetch_output) pm.open(key=key) ensure_future(coroutine()) application = Application( layout=Layout(root_container, focused_element=text_field), key_bindings=bindings, enable_page_navigation_bindings=True, style=style, full_screen=True, ) application.run() if selected_content[0] is not None: tokens = list(pygments.lex(selected_content[0], lexer=BibTeXLexer())) print_formatted_text( PygmentsTokens(tokens), end="", style=lex_style, #output=create_output(sys.stdout), )
import requests import zipfile import shutil import csv import pandas as pd from datetime import date from datetime import datetime from pathlib import Path from urllib.parse import urlparse class BhavCopy(object): """description of class""" def __init__(self, date: date): self.date = date self._url_eq = urlparse(f'https://www.nseindia.com/content/historical/EQUITIES/{date.strftime('%Y')}/{date.strftime('%b').upper()}/cm{date.strftime('%d%b%Y').upper()}bhav.csv.zip') self._file_eq_zip = Path(self._url_eq.path[1:]) self._file_eq = Path(self._url_eq.path[1:-4]) self._url_fo = urlparse(f'https://www.nseindia.com/content/historical/DERIVATIVES/{date.strftime('%Y')}/{date.strftime('%b').upper()}/fo{date.strftime('%d%b%Y').upper()}bhav.csv.zip') self._file_fo_zip = Path(self._url_fo.path[1:]) self._file_fo = Path(self._url_fo.path[1:-4]) self.market_close = False self._initialize() def _initialize(self): if self.date.weekday() == 5 or self.date.weekday() == 6: self.market_close = True return self._try_download(self._url_eq, self._file_eq_zip) self._try_download(self._url_fo, self._file_fo_zip) def _try_download(self, url: urlparse, path: Path): if not path.is_file(): path.parent.mkdir(parents=True, exist_ok=True) with requests.get(url.geturl(), stream=True) as r: if r.status_code == 200: with path.open('wb') as f: r.raw.decode_content = True shutil.copyfileobj(r.raw, f) with zipfile.ZipFile(path, 'r') as zf: zf.extractall(path.parent) if r.status_code == 404: self.market_close = True def read_fo(self): if self._file_fo.is_file(): with self._file_fo.open('rt') as f: csv_reader = csv.reader(f, delimiter=',') self.headers_fo = next(csv_reader, None) for row in csv_reader: yield (row[0], row[1], datetime.strptime(row[2], '%d-%b-%Y').strftime('%Y-%m-%d'), row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13], datetime.strptime(row[14], '%d-%b-%Y').strftime('%Y-%m-%d')) def read_eq(self): if self._file_eq.is_file(): with self._file_eq.open('rt') as f: csv_reader = csv.reader(f, delimiter=',') self.headers_eq = next(csv_reader, None) for row in csv.reader(f, delimiter=','): yield row def read_eq_as_pd(self): if self.market_close: return return pd.read_csv(self._file_eq) def read_fo_as_pd(self): if self.market_close: return return pd.read_csv(self._file_fo)
import requests import zipfile import shutil import csv import pandas as pd from datetime import date from datetime import datetime from pathlib import Path from urllib.parse import urlparse class BhavCopy(object): """description of class""" def __init__(self, date: date): self.date = date self._url_eq = urlparse(f'https://www.nseindia.com/content/historical/EQUITIES/{date.strftime("%Y")}/{date.strftime("%b").upper()}/cm{date.strftime("%d%b%Y").upper()}bhav.csv.zip') self._file_eq_zip = Path(self._url_eq.path[1:]) self._file_eq = Path(self._url_eq.path[1:-4]) self._url_fo = urlparse(f'https://www.nseindia.com/content/historical/DERIVATIVES/{date.strftime("%Y")}/{date.strftime("%b").upper()}/fo{date.strftime("%d%b%Y").upper()}bhav.csv.zip') self._file_fo_zip = Path(self._url_fo.path[1:]) self._file_fo = Path(self._url_fo.path[1:-4]) self.market_close = False self._initialize() def _initialize(self): if self.date.weekday() == 5 or self.date.weekday() == 6: self.market_close = True return self._try_download(self._url_eq, self._file_eq_zip) self._try_download(self._url_fo, self._file_fo_zip) def _try_download(self, url: urlparse, path: Path): if not path.is_file(): path.parent.mkdir(parents=True, exist_ok=True) with requests.get(url.geturl(), stream=True) as r: if r.status_code == 200: with path.open('wb') as f: r.raw.decode_content = True shutil.copyfileobj(r.raw, f) with zipfile.ZipFile(path, 'r') as zf: zf.extractall(path.parent) if r.status_code == 404: self.market_close = True def read_fo(self): if self._file_fo.is_file(): with self._file_fo.open('rt') as f: csv_reader = csv.reader(f, delimiter=',') self.headers_fo = next(csv_reader, None) for row in csv_reader: yield (row[0], row[1], datetime.strptime(row[2], '%d-%b-%Y').strftime('%Y-%m-%d'), row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13], datetime.strptime(row[14], '%d-%b-%Y').strftime('%Y-%m-%d')) def read_eq(self): if self._file_eq.is_file(): with self._file_eq.open('rt') as f: csv_reader = csv.reader(f, delimiter=',') self.headers_eq = next(csv_reader, None) for row in csv.reader(f, delimiter=','): yield row def read_eq_as_pd(self): if self.market_close: return return pd.read_csv(self._file_eq) def read_fo_as_pd(self): if self.market_close: return return pd.read_csv(self._file_fo)
"""Stock Context Controller""" __docformat__ = "numpy" import argparse import logging import os from datetime import datetime, timedelta from typing import List import financedatabase import yfinance as yf from prompt_toolkit.completion import NestedCompleter from openbb_terminal import feature_flags as obbff from openbb_terminal.common import newsapi_view from openbb_terminal.common.quantitative_analysis import qa_view from openbb_terminal.decorators import log_start_end from openbb_terminal.helper_funcs import ( EXPORT_ONLY_RAW_DATA_ALLOWED, export_data, valid_date, ) from openbb_terminal.helper_classes import AllowArgsWithWhiteSpace from openbb_terminal.helper_funcs import choice_check_after_action from openbb_terminal.menu import session from openbb_terminal.parent_classes import StockBaseController from openbb_terminal.rich_config import console, translate, MenuText from openbb_terminal.stocks import stocks_helper # pylint: disable=R1710,import-outside-toplevel,R0913,R1702,no-member logger = logging.getLogger(__name__) class StocksController(StockBaseController): """Stocks Controller class""" CHOICES_COMMANDS = [ "search", "load", "quote", "candle", "news", "resources", "codes", ] CHOICES_MENUS = [ "ta", "ba", "qa", "pred", "disc", "dps", "scr", "sia", "ins", "gov", "res", "fa", "bt", "dd", "ca", "options", "th", ] PATH = "/stocks/" FILE_PATH = os.path.join(os.path.dirname(__file__), "README.md") country = financedatabase.show_options("equities", "countries") sector = financedatabase.show_options("equities", "sectors") industry = financedatabase.show_options("equities", "industries") def __init__(self, queue: List[str] = None): """Constructor""" super().__init__(queue) if session and obbff.USE_PROMPT_TOOLKIT: choices: dict = {c: {} for c in self.controller_choices} choices["search"]["--country"] = {c: None for c in self.country} choices["search"]["-c"] = {c: None for c in self.country} choices["search"]["--sector"] = {c: None for c in self.sector} choices["search"]["-s"] = {c: None for c in self.sector} choices["search"]["--industry"] = {c: None for c in self.industry} choices["search"]["-i"] = {c: None for c in self.industry} choices["search"]["--exchange"] = { c: None for c in stocks_helper.market_coverage_suffix } choices["search"]["-e"] = { c: None for c in stocks_helper.market_coverage_suffix } choices["support"] = self.SUPPORT_CHOICES self.completer = NestedCompleter.from_nested_dict(choices) def print_help(self): """Print help""" stock_text = "" if self.ticker: s_intraday = (f"Intraday {self.interval}", "Daily")[ self.interval == "1440min" ] if self.start: stock_text = f"{s_intraday} {self.ticker} (from {self.start.strftime("%Y-%m-%d")})" else: stock_text = f"{s_intraday} {self.ticker}" mt = MenuText("stocks/", 80) mt.add_cmd("search") mt.add_cmd("load") mt.add_raw("\n") mt.add_param("_ticker", stock_text) mt.add_raw(self.add_info) mt.add_raw("\n") mt.add_cmd("quote", "", self.ticker) mt.add_cmd("candle", "", self.ticker) mt.add_cmd("news", "News API", self.ticker) mt.add_cmd("codes", "Polygon", self.ticker) mt.add_raw("\n") mt.add_menu("th") mt.add_menu("options") mt.add_menu("disc") mt.add_menu("sia") mt.add_menu("dps") mt.add_menu("scr") mt.add_menu("ins") mt.add_menu("gov") mt.add_menu("ba") mt.add_menu("ca") mt.add_menu("fa", self.ticker) mt.add_menu("res", self.ticker) mt.add_menu("dd", self.ticker) mt.add_menu("bt", self.ticker) mt.add_menu("ta", self.ticker) mt.add_menu("qa", self.ticker) mt.add_menu("pred", self.ticker) console.print(text=mt.menu_text, menu="Stocks") def custom_reset(self): """Class specific component of reset command""" if self.ticker: return [ "stocks", f"load {self.ticker}.{self.suffix}" if self.suffix else f"load {self.ticker}", ] return [] @log_start_end(log=logger) def call_search(self, other_args: List[str]): """Process search command""" parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="search", description=translate("stocks/SEARCH"), ) parser.add_argument( "-q", "--query", action="store", dest="query", type=str.lower, default="", help=translate("stocks/SEARCH_query"), ) parser.add_argument( "-c", "--country", default="", nargs=argparse.ONE_OR_MORE, action=choice_check_after_action(AllowArgsWithWhiteSpace, self.country), dest="country", help=translate("stocks/SEARCH_country"), ) parser.add_argument( "-s", "--sector", default="", nargs=argparse.ONE_OR_MORE, action=choice_check_after_action(AllowArgsWithWhiteSpace, self.sector), dest="sector", help=translate("stocks/SEARCH_sector"), ) parser.add_argument( "-i", "--industry", default="", nargs=argparse.ONE_OR_MORE, action=choice_check_after_action(AllowArgsWithWhiteSpace, self.industry), dest="industry", help=translate("stocks/SEARCH_industry"), ) parser.add_argument( "-e", "--exchange", default="", choices=list(stocks_helper.market_coverage_suffix.keys()), dest="exchange_country", help=translate("stocks/SEARCH_exchange"), ) if other_args and "-" not in other_args[0][0]: other_args.insert(0, "-q") ns_parser = self.parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED, limit=10, ) if ns_parser: stocks_helper.search( query=ns_parser.query, country=ns_parser.country, sector=ns_parser.sector, industry=ns_parser.industry, exchange_country=ns_parser.exchange_country, limit=ns_parser.limit, export=ns_parser.export, ) @log_start_end(log=logger) def call_quote(self, other_args: List[str]): """Process quote command""" ticker = self.ticker + "." + self.suffix if self.suffix else self.ticker parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="quote", description=translate("stocks/QUOTE"), ) if self.ticker: parser.add_argument( "-t", "--ticker", action="store", dest="s_ticker", default=ticker, help=translate("stocks/QUOTE_ticker"), ) else: parser.add_argument( "-t", "--ticker", action="store", dest="s_ticker", required="-h" not in other_args, help=translate("stocks/QUOTE_ticker"), ) # For the case where a user uses: 'quote BB' if other_args and "-" not in other_args[0][0]: other_args.insert(0, "-t") ns_parser = self.parse_known_args_and_warn(parser, other_args) if ns_parser: stocks_helper.quote(ns_parser.s_ticker) @log_start_end(log=logger) def call_codes(self, _): """Process codes command""" parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="codes", description="Show CIK, FIGI and SCI code from polygon for loaded ticker.", ) ns_parser = self.parse_known_args_and_warn(parser, _) if ns_parser: if not self.ticker: console.print("No ticker loaded. First use `load {ticker}`\n") return stocks_helper.show_codes_polygon(self.ticker) @log_start_end(log=logger) def call_candle(self, other_args: List[str]): """Process candle command""" parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="candle", description=translate("stocks/CANDLE"), ) parser.add_argument( "-p", "--plotly", dest="plotly", action="store_false", default=True, help=translate("stocks/CANDLE_plotly"), ) parser.add_argument( "--sort", choices=[ "AdjClose", "Open", "Close", "High", "Low", "Volume", "Returns", "LogRet", ], default="", type=str, dest="sort", help=translate("stocks/CANDLE_sort"), ) parser.add_argument( "-d", "--descending", action="store_false", dest="descending", default=True, help=translate("stocks/CANDLE_descending"), ) parser.add_argument( "--raw", action="store_true", dest="raw", default=False, help=translate("stocks/CANDLE_raw"), ) parser.add_argument( "-t", "--trend", action="store_true", default=False, help=translate("stocks/CANDLE_trend"), dest="trendlines", ) parser.add_argument( "--ma", dest="mov_avg", type=str, help=translate("stocks/CANDLE_mov_avg"), default=None, ) ns_parser = self.parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED, limit=20, ) if ns_parser: if self.ticker: export_data( ns_parser.export, os.path.join( os.path.dirname(os.path.abspath(__file__)), "raw_data" ), f"{self.ticker}", self.stock, ) if ns_parser.raw: qa_view.display_raw( df=self.stock, sort=ns_parser.sort, des=ns_parser.descending, num=ns_parser.limit, ) else: data = stocks_helper.process_candle(self.stock) mov_avgs = [] if ns_parser.mov_avg: mov_list = (num for num in ns_parser.mov_avg.split(",")) for num in mov_list: try: mov_avgs.append(int(num)) except ValueError: console.print( f"{num} is not a valid moving average, must be integer" ) stocks_helper.display_candle( s_ticker=self.ticker, df_stock=data, use_matplotlib=ns_parser.plotly, intraday=self.interval != "1440min", add_trend=ns_parser.trendlines, ma=mov_avgs, ) else: console.print("No ticker loaded. First use `load {ticker}`\n") @log_start_end(log=logger) def call_news(self, other_args: List[str]): """Process news command""" if not self.ticker: console.print("Use 'load <ticker>' prior to this command!", "\n") return parser = argparse.ArgumentParser( add_help=False, prog="news", description=translate("stocks/NEWS"), ) parser.add_argument( "-d", "--date", action="store", dest="n_start_date", type=valid_date, default=datetime.now() - timedelta(days=7), help=translate("stocks/NEWS_date"), ) parser.add_argument( "-o", "--oldest", action="store_false", dest="n_oldest", default=True, help=translate("stocks/NEWS_oldest"), ) parser.add_argument( "-s", "--sources", dest="sources", default=[], nargs="+", help=translate("stocks/NEWS_sources"), ) if other_args and "-" not in other_args[0][0]: other_args.insert(0, "-l") ns_parser = self.parse_known_args_and_warn(parser, other_args, limit=5) if ns_parser: sources = ns_parser.sources for idx, source in enumerate(sources): if source.find(".") == -1: sources[idx] += ".com" d_stock = yf.Ticker(self.ticker).info newsapi_view.display_news( term=d_stock["shortName"].replace(" ", "+") if "shortName" in d_stock else self.ticker, num=ns_parser.limit, s_from=ns_parser.n_start_date.strftime("%Y-%m-%d"), show_newest=ns_parser.n_oldest, sources=",".join(sources), ) @log_start_end(log=logger) def call_disc(self, _): """Process disc command""" from openbb_terminal.stocks.discovery.disc_controller import ( DiscoveryController, ) self.queue = self.load_class(DiscoveryController, self.queue) @log_start_end(log=logger) def call_dps(self, _): """Process dps command""" from openbb_terminal.stocks.dark_pool_shorts.dps_controller import ( DarkPoolShortsController, ) self.queue = self.load_class( DarkPoolShortsController, self.ticker, self.start, self.stock, self.queue ) @log_start_end(log=logger) def call_scr(self, _): """Process scr command""" from openbb_terminal.stocks.screener.screener_controller import ( ScreenerController, ) self.queue = self.load_class(ScreenerController, self.queue) @log_start_end(log=logger) def call_sia(self, _): """Process ins command""" from openbb_terminal.stocks.sector_industry_analysis.sia_controller import ( SectorIndustryAnalysisController, ) self.queue = self.load_class( SectorIndustryAnalysisController, self.ticker, self.queue ) @log_start_end(log=logger) def call_ins(self, _): """Process ins command""" from openbb_terminal.stocks.insider.insider_controller import ( InsiderController, ) self.queue = self.load_class( InsiderController, self.ticker, self.start, self.interval, self.stock, self.queue, ) @log_start_end(log=logger) def call_gov(self, _): """Process gov command""" from openbb_terminal.stocks.government.gov_controller import GovController self.queue = self.load_class(GovController, self.ticker, self.queue) @log_start_end(log=logger) def call_options(self, _): """Process options command""" from openbb_terminal.stocks.options.options_controller import ( OptionsController, ) self.queue = self.load_class(OptionsController, self.ticker, self.queue) @log_start_end(log=logger) def call_th(self, _): """Process th command""" from openbb_terminal.stocks.tradinghours.tradinghours_controller import ( TradingHoursController, ) self.queue = self.load_class(TradingHoursController, self.queue) @log_start_end(log=logger) def call_res(self, _): """Process res command""" if self.ticker: from openbb_terminal.stocks.research.res_controller import ( ResearchController, ) self.queue = self.load_class( ResearchController, self.ticker, self.start, self.interval, self.queue ) else: console.print("Use 'load <ticker>' prior to this command!", "\n") @log_start_end(log=logger) def call_dd(self, _): """Process dd command""" if self.ticker: from openbb_terminal.stocks.due_diligence import dd_controller self.queue = self.load_class( dd_controller.DueDiligenceController, self.ticker, self.start, self.interval, self.stock, self.queue, ) else: console.print("Use 'load <ticker>' prior to this command!", "\n") @log_start_end(log=logger) def call_ca(self, _): """Process ca command""" from openbb_terminal.stocks.comparison_analysis import ca_controller self.queue = self.load_class( ca_controller.ComparisonAnalysisController, [self.ticker] if self.ticker else "", self.queue, ) @log_start_end(log=logger) def call_fa(self, _): """Process fa command""" if self.ticker: from openbb_terminal.stocks.fundamental_analysis import fa_controller self.queue = self.load_class( fa_controller.FundamentalAnalysisController, self.ticker, self.start, self.interval, self.suffix, self.queue, ) else: console.print("Use 'load <ticker>' prior to this command!", "\n") @log_start_end(log=logger) def call_bt(self, _): """Process bt command""" if self.ticker: from openbb_terminal.stocks.backtesting import bt_controller self.queue = self.load_class( bt_controller.BacktestingController, self.ticker, self.stock, self.queue ) else: console.print("Use 'load <ticker>' prior to this command!", "\n") @log_start_end(log=logger) def call_ta(self, _): """Process ta command""" if self.ticker: from openbb_terminal.stocks.technical_analysis import ta_controller self.queue = self.load_class( ta_controller.TechnicalAnalysisController, self.ticker, self.start, self.interval, self.stock, self.queue, ) else: console.print("Use 'load <ticker>' prior to this command!", "\n") @log_start_end(log=logger) def call_ba(self, _): """Process ba command""" from openbb_terminal.stocks.behavioural_analysis import ba_controller self.queue = self.load_class( ba_controller.BehaviouralAnalysisController, self.ticker, self.start, self.queue, ) @log_start_end(log=logger) def call_qa(self, _): """Process qa command""" if self.ticker: from openbb_terminal.stocks.quantitative_analysis import ( qa_controller, ) self.queue = self.load_class( qa_controller.QaController, self.ticker, self.start, self.interval, self.stock, self.queue, ) # TODO: This menu should work regardless of data being daily or not! # James: 5/27 I think it does now else: console.print("Use 'load <ticker>' prior to this command!", "\n") @log_start_end(log=logger) def call_pred(self, _): """Process pred command""" if obbff.ENABLE_PREDICT: if self.ticker: if self.interval == "1440min": try: from openbb_terminal.stocks.prediction_techniques import ( pred_controller, ) self.queue = self.load_class( pred_controller.PredictionTechniquesController, self.ticker, self.start, self.interval, self.stock, self.queue, ) except ModuleNotFoundError as e: logger.exception( "One of the optional packages seems to be missing: %s", str(e), ) console.print( "One of the optional packages seems to be missing: ", e, "\n", ) # TODO: This menu should work regardless of data being daily or not! else: console.print("Load daily data to use this menu!", "\n") else: console.print("Use 'load <ticker>' prior to this command!", "\n") else: console.print( "Predict is disabled. Check ENABLE_PREDICT flag on feature_flags.py", "\n", )
"""Stock Context Controller""" __docformat__ = "numpy" import argparse import logging import os from datetime import datetime, timedelta from typing import List import financedatabase import yfinance as yf from prompt_toolkit.completion import NestedCompleter from openbb_terminal import feature_flags as obbff from openbb_terminal.common import newsapi_view from openbb_terminal.common.quantitative_analysis import qa_view from openbb_terminal.decorators import log_start_end from openbb_terminal.helper_funcs import ( EXPORT_ONLY_RAW_DATA_ALLOWED, export_data, valid_date, ) from openbb_terminal.helper_classes import AllowArgsWithWhiteSpace from openbb_terminal.helper_funcs import choice_check_after_action from openbb_terminal.menu import session from openbb_terminal.parent_classes import StockBaseController from openbb_terminal.rich_config import console, translate, MenuText from openbb_terminal.stocks import stocks_helper # pylint: disable=R1710,import-outside-toplevel,R0913,R1702,no-member logger = logging.getLogger(__name__) class StocksController(StockBaseController): """Stocks Controller class""" CHOICES_COMMANDS = [ "search", "load", "quote", "candle", "news", "resources", "codes", ] CHOICES_MENUS = [ "ta", "ba", "qa", "pred", "disc", "dps", "scr", "sia", "ins", "gov", "res", "fa", "bt", "dd", "ca", "options", "th", ] PATH = "/stocks/" FILE_PATH = os.path.join(os.path.dirname(__file__), "README.md") country = financedatabase.show_options("equities", "countries") sector = financedatabase.show_options("equities", "sectors") industry = financedatabase.show_options("equities", "industries") def __init__(self, queue: List[str] = None): """Constructor""" super().__init__(queue) if session and obbff.USE_PROMPT_TOOLKIT: choices: dict = {c: {} for c in self.controller_choices} choices["search"]["--country"] = {c: None for c in self.country} choices["search"]["-c"] = {c: None for c in self.country} choices["search"]["--sector"] = {c: None for c in self.sector} choices["search"]["-s"] = {c: None for c in self.sector} choices["search"]["--industry"] = {c: None for c in self.industry} choices["search"]["-i"] = {c: None for c in self.industry} choices["search"]["--exchange"] = { c: None for c in stocks_helper.market_coverage_suffix } choices["search"]["-e"] = { c: None for c in stocks_helper.market_coverage_suffix } choices["support"] = self.SUPPORT_CHOICES self.completer = NestedCompleter.from_nested_dict(choices) def print_help(self): """Print help""" stock_text = "" if self.ticker: s_intraday = (f"Intraday {self.interval}", "Daily")[ self.interval == "1440min" ] if self.start: stock_text = f"{s_intraday} {self.ticker} (from {self.start.strftime('%Y-%m-%d')})" else: stock_text = f"{s_intraday} {self.ticker}" mt = MenuText("stocks/", 80) mt.add_cmd("search") mt.add_cmd("load") mt.add_raw("\n") mt.add_param("_ticker", stock_text) mt.add_raw(self.add_info) mt.add_raw("\n") mt.add_cmd("quote", "", self.ticker) mt.add_cmd("candle", "", self.ticker) mt.add_cmd("news", "News API", self.ticker) mt.add_cmd("codes", "Polygon", self.ticker) mt.add_raw("\n") mt.add_menu("th") mt.add_menu("options") mt.add_menu("disc") mt.add_menu("sia") mt.add_menu("dps") mt.add_menu("scr") mt.add_menu("ins") mt.add_menu("gov") mt.add_menu("ba") mt.add_menu("ca") mt.add_menu("fa", self.ticker) mt.add_menu("res", self.ticker) mt.add_menu("dd", self.ticker) mt.add_menu("bt", self.ticker) mt.add_menu("ta", self.ticker) mt.add_menu("qa", self.ticker) mt.add_menu("pred", self.ticker) console.print(text=mt.menu_text, menu="Stocks") def custom_reset(self): """Class specific component of reset command""" if self.ticker: return [ "stocks", f"load {self.ticker}.{self.suffix}" if self.suffix else f"load {self.ticker}", ] return [] @log_start_end(log=logger) def call_search(self, other_args: List[str]): """Process search command""" parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="search", description=translate("stocks/SEARCH"), ) parser.add_argument( "-q", "--query", action="store", dest="query", type=str.lower, default="", help=translate("stocks/SEARCH_query"), ) parser.add_argument( "-c", "--country", default="", nargs=argparse.ONE_OR_MORE, action=choice_check_after_action(AllowArgsWithWhiteSpace, self.country), dest="country", help=translate("stocks/SEARCH_country"), ) parser.add_argument( "-s", "--sector", default="", nargs=argparse.ONE_OR_MORE, action=choice_check_after_action(AllowArgsWithWhiteSpace, self.sector), dest="sector", help=translate("stocks/SEARCH_sector"), ) parser.add_argument( "-i", "--industry", default="", nargs=argparse.ONE_OR_MORE, action=choice_check_after_action(AllowArgsWithWhiteSpace, self.industry), dest="industry", help=translate("stocks/SEARCH_industry"), ) parser.add_argument( "-e", "--exchange", default="", choices=list(stocks_helper.market_coverage_suffix.keys()), dest="exchange_country", help=translate("stocks/SEARCH_exchange"), ) if other_args and "-" not in other_args[0][0]: other_args.insert(0, "-q") ns_parser = self.parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED, limit=10, ) if ns_parser: stocks_helper.search( query=ns_parser.query, country=ns_parser.country, sector=ns_parser.sector, industry=ns_parser.industry, exchange_country=ns_parser.exchange_country, limit=ns_parser.limit, export=ns_parser.export, ) @log_start_end(log=logger) def call_quote(self, other_args: List[str]): """Process quote command""" ticker = self.ticker + "." + self.suffix if self.suffix else self.ticker parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="quote", description=translate("stocks/QUOTE"), ) if self.ticker: parser.add_argument( "-t", "--ticker", action="store", dest="s_ticker", default=ticker, help=translate("stocks/QUOTE_ticker"), ) else: parser.add_argument( "-t", "--ticker", action="store", dest="s_ticker", required="-h" not in other_args, help=translate("stocks/QUOTE_ticker"), ) # For the case where a user uses: 'quote BB' if other_args and "-" not in other_args[0][0]: other_args.insert(0, "-t") ns_parser = self.parse_known_args_and_warn(parser, other_args) if ns_parser: stocks_helper.quote(ns_parser.s_ticker) @log_start_end(log=logger) def call_codes(self, _): """Process codes command""" parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="codes", description="Show CIK, FIGI and SCI code from polygon for loaded ticker.", ) ns_parser = self.parse_known_args_and_warn(parser, _) if ns_parser: if not self.ticker: console.print("No ticker loaded. First use `load {ticker}`\n") return stocks_helper.show_codes_polygon(self.ticker) @log_start_end(log=logger) def call_candle(self, other_args: List[str]): """Process candle command""" parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="candle", description=translate("stocks/CANDLE"), ) parser.add_argument( "-p", "--plotly", dest="plotly", action="store_false", default=True, help=translate("stocks/CANDLE_plotly"), ) parser.add_argument( "--sort", choices=[ "AdjClose", "Open", "Close", "High", "Low", "Volume", "Returns", "LogRet", ], default="", type=str, dest="sort", help=translate("stocks/CANDLE_sort"), ) parser.add_argument( "-d", "--descending", action="store_false", dest="descending", default=True, help=translate("stocks/CANDLE_descending"), ) parser.add_argument( "--raw", action="store_true", dest="raw", default=False, help=translate("stocks/CANDLE_raw"), ) parser.add_argument( "-t", "--trend", action="store_true", default=False, help=translate("stocks/CANDLE_trend"), dest="trendlines", ) parser.add_argument( "--ma", dest="mov_avg", type=str, help=translate("stocks/CANDLE_mov_avg"), default=None, ) ns_parser = self.parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED, limit=20, ) if ns_parser: if self.ticker: export_data( ns_parser.export, os.path.join( os.path.dirname(os.path.abspath(__file__)), "raw_data" ), f"{self.ticker}", self.stock, ) if ns_parser.raw: qa_view.display_raw( df=self.stock, sort=ns_parser.sort, des=ns_parser.descending, num=ns_parser.limit, ) else: data = stocks_helper.process_candle(self.stock) mov_avgs = [] if ns_parser.mov_avg: mov_list = (num for num in ns_parser.mov_avg.split(",")) for num in mov_list: try: mov_avgs.append(int(num)) except ValueError: console.print( f"{num} is not a valid moving average, must be integer" ) stocks_helper.display_candle( s_ticker=self.ticker, df_stock=data, use_matplotlib=ns_parser.plotly, intraday=self.interval != "1440min", add_trend=ns_parser.trendlines, ma=mov_avgs, ) else: console.print("No ticker loaded. First use `load {ticker}`\n") @log_start_end(log=logger) def call_news(self, other_args: List[str]): """Process news command""" if not self.ticker: console.print("Use 'load <ticker>' prior to this command!", "\n") return parser = argparse.ArgumentParser( add_help=False, prog="news", description=translate("stocks/NEWS"), ) parser.add_argument( "-d", "--date", action="store", dest="n_start_date", type=valid_date, default=datetime.now() - timedelta(days=7), help=translate("stocks/NEWS_date"), ) parser.add_argument( "-o", "--oldest", action="store_false", dest="n_oldest", default=True, help=translate("stocks/NEWS_oldest"), ) parser.add_argument( "-s", "--sources", dest="sources", default=[], nargs="+", help=translate("stocks/NEWS_sources"), ) if other_args and "-" not in other_args[0][0]: other_args.insert(0, "-l") ns_parser = self.parse_known_args_and_warn(parser, other_args, limit=5) if ns_parser: sources = ns_parser.sources for idx, source in enumerate(sources): if source.find(".") == -1: sources[idx] += ".com" d_stock = yf.Ticker(self.ticker).info newsapi_view.display_news( term=d_stock["shortName"].replace(" ", "+") if "shortName" in d_stock else self.ticker, num=ns_parser.limit, s_from=ns_parser.n_start_date.strftime("%Y-%m-%d"), show_newest=ns_parser.n_oldest, sources=",".join(sources), ) @log_start_end(log=logger) def call_disc(self, _): """Process disc command""" from openbb_terminal.stocks.discovery.disc_controller import ( DiscoveryController, ) self.queue = self.load_class(DiscoveryController, self.queue) @log_start_end(log=logger) def call_dps(self, _): """Process dps command""" from openbb_terminal.stocks.dark_pool_shorts.dps_controller import ( DarkPoolShortsController, ) self.queue = self.load_class( DarkPoolShortsController, self.ticker, self.start, self.stock, self.queue ) @log_start_end(log=logger) def call_scr(self, _): """Process scr command""" from openbb_terminal.stocks.screener.screener_controller import ( ScreenerController, ) self.queue = self.load_class(ScreenerController, self.queue) @log_start_end(log=logger) def call_sia(self, _): """Process ins command""" from openbb_terminal.stocks.sector_industry_analysis.sia_controller import ( SectorIndustryAnalysisController, ) self.queue = self.load_class( SectorIndustryAnalysisController, self.ticker, self.queue ) @log_start_end(log=logger) def call_ins(self, _): """Process ins command""" from openbb_terminal.stocks.insider.insider_controller import ( InsiderController, ) self.queue = self.load_class( InsiderController, self.ticker, self.start, self.interval, self.stock, self.queue, ) @log_start_end(log=logger) def call_gov(self, _): """Process gov command""" from openbb_terminal.stocks.government.gov_controller import GovController self.queue = self.load_class(GovController, self.ticker, self.queue) @log_start_end(log=logger) def call_options(self, _): """Process options command""" from openbb_terminal.stocks.options.options_controller import ( OptionsController, ) self.queue = self.load_class(OptionsController, self.ticker, self.queue) @log_start_end(log=logger) def call_th(self, _): """Process th command""" from openbb_terminal.stocks.tradinghours.tradinghours_controller import ( TradingHoursController, ) self.queue = self.load_class(TradingHoursController, self.queue) @log_start_end(log=logger) def call_res(self, _): """Process res command""" if self.ticker: from openbb_terminal.stocks.research.res_controller import ( ResearchController, ) self.queue = self.load_class( ResearchController, self.ticker, self.start, self.interval, self.queue ) else: console.print("Use 'load <ticker>' prior to this command!", "\n") @log_start_end(log=logger) def call_dd(self, _): """Process dd command""" if self.ticker: from openbb_terminal.stocks.due_diligence import dd_controller self.queue = self.load_class( dd_controller.DueDiligenceController, self.ticker, self.start, self.interval, self.stock, self.queue, ) else: console.print("Use 'load <ticker>' prior to this command!", "\n") @log_start_end(log=logger) def call_ca(self, _): """Process ca command""" from openbb_terminal.stocks.comparison_analysis import ca_controller self.queue = self.load_class( ca_controller.ComparisonAnalysisController, [self.ticker] if self.ticker else "", self.queue, ) @log_start_end(log=logger) def call_fa(self, _): """Process fa command""" if self.ticker: from openbb_terminal.stocks.fundamental_analysis import fa_controller self.queue = self.load_class( fa_controller.FundamentalAnalysisController, self.ticker, self.start, self.interval, self.suffix, self.queue, ) else: console.print("Use 'load <ticker>' prior to this command!", "\n") @log_start_end(log=logger) def call_bt(self, _): """Process bt command""" if self.ticker: from openbb_terminal.stocks.backtesting import bt_controller self.queue = self.load_class( bt_controller.BacktestingController, self.ticker, self.stock, self.queue ) else: console.print("Use 'load <ticker>' prior to this command!", "\n") @log_start_end(log=logger) def call_ta(self, _): """Process ta command""" if self.ticker: from openbb_terminal.stocks.technical_analysis import ta_controller self.queue = self.load_class( ta_controller.TechnicalAnalysisController, self.ticker, self.start, self.interval, self.stock, self.queue, ) else: console.print("Use 'load <ticker>' prior to this command!", "\n") @log_start_end(log=logger) def call_ba(self, _): """Process ba command""" from openbb_terminal.stocks.behavioural_analysis import ba_controller self.queue = self.load_class( ba_controller.BehaviouralAnalysisController, self.ticker, self.start, self.queue, ) @log_start_end(log=logger) def call_qa(self, _): """Process qa command""" if self.ticker: from openbb_terminal.stocks.quantitative_analysis import ( qa_controller, ) self.queue = self.load_class( qa_controller.QaController, self.ticker, self.start, self.interval, self.stock, self.queue, ) # TODO: This menu should work regardless of data being daily or not! # James: 5/27 I think it does now else: console.print("Use 'load <ticker>' prior to this command!", "\n") @log_start_end(log=logger) def call_pred(self, _): """Process pred command""" if obbff.ENABLE_PREDICT: if self.ticker: if self.interval == "1440min": try: from openbb_terminal.stocks.prediction_techniques import ( pred_controller, ) self.queue = self.load_class( pred_controller.PredictionTechniquesController, self.ticker, self.start, self.interval, self.stock, self.queue, ) except ModuleNotFoundError as e: logger.exception( "One of the optional packages seems to be missing: %s", str(e), ) console.print( "One of the optional packages seems to be missing: ", e, "\n", ) # TODO: This menu should work regardless of data being daily or not! else: console.print("Load daily data to use this menu!", "\n") else: console.print("Use 'load <ticker>' prior to this command!", "\n") else: console.print( "Predict is disabled. Check ENABLE_PREDICT flag on feature_flags.py", "\n", )
#!/usr/bin/env python3 import argparse import copy from datetime import datetime import json import modulefinder import os import shutil import signal import subprocess import sys import tempfile import torch from torch.utils import cpp_extension from torch.testing._internal.common_utils import TEST_WITH_ROCM, shell, set_cwd, FILE_SCHEMA from torch.testing._internal.framework_utils import calculate_shards import torch.distributed as dist from typing import Dict, Optional, Tuple, List, Any from typing_extensions import TypedDict try: sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) from tools.stats_utils.s3_stat_parser import (get_previous_reports_for_branch, Report, HAVE_BOTO3) except ImportError: print("Unable to import s3_stat_parser from tools. Running without S3 stats...") HAVE_BOTO3 = False TESTS = [ 'test_import_time', 'test_public_bindings', 'test_type_hints', 'test_autograd', 'benchmark_utils/test_benchmark_utils', 'test_binary_ufuncs', 'test_bundled_inputs', 'test_complex', 'test_cpp_api_parity', 'test_cpp_extensions_aot_no_ninja', 'test_cpp_extensions_aot_ninja', 'test_cpp_extensions_jit', 'distributed/test_c10d_common', 'distributed/test_c10d_gloo', 'distributed/test_c10d_nccl', 'distributed/test_jit_c10d', 'distributed/test_c10d_spawn_gloo', 'distributed/test_c10d_spawn_nccl', 'test_cuda', 'test_jit_cuda_fuser', 'test_cuda_primary_ctx', 'test_dataloader', 'test_datapipe', 'distributed/test_data_parallel', 'distributed/test_distributed_fork', 'distributed/test_distributed_spawn', 'distributions/test_constraints', 'distributions/test_distributions', 'test_dispatch', 'test_expecttest', 'test_foreach', 'test_indexing', 'test_jit', 'test_linalg', 'test_logging', 'test_mkldnn', 'test_model_dump', 'test_module_init', 'test_multiprocessing', 'test_multiprocessing_spawn', 'distributed/test_nccl', 'test_native_functions', 'test_numba_integration', 'test_nn', 'test_ops', 'test_optim', 'test_pytree', 'test_mobile_optimizer', 'test_set_default_mobile_cpu_allocator', 'test_xnnpack_integration', 'test_vulkan', 'test_sparse', 'test_sparse_csr', 'test_quantization', 'test_pruning_op', 'test_spectral_ops', 'test_serialization', 'test_shape_ops', 'test_show_pickle', 'test_sort_and_select', 'test_tensor_creation_ops', 'test_testing', 'test_torch', 'test_type_info', 'test_unary_ufuncs', 'test_utils', 'test_view_ops', 'test_vmap', 'test_namedtuple_return_api', 'test_numpy_interop', 'test_jit_profiling', 'test_jit_legacy', 'test_jit_fuser_legacy', 'test_tensorboard', 'test_namedtensor', 'test_reductions', 'test_type_promotion', 'test_jit_disabled', 'test_function_schema', 'test_op_aliases', 'test_overrides', 'test_jit_fuser_te', 'test_tensorexpr', 'test_tensorexpr_pybind', 'test_openmp', 'test_profiler', "distributed/test_launcher", 'distributed/nn/jit/test_instantiator', 'distributed/rpc/test_faulty_agent', 'distributed/rpc/test_process_group_agent', 'distributed/rpc/cuda/test_process_group_agent', 'distributed/rpc/test_tensorpipe_agent', 'distributed/rpc/cuda/test_tensorpipe_agent', 'test_determination', 'test_futures', 'test_fx', 'test_fx_experimental', 'test_functional_autograd_benchmark', 'test_package', 'test_license', 'distributed/pipeline/sync/skip/test_api', 'distributed/pipeline/sync/skip/test_gpipe', 'distributed/pipeline/sync/skip/test_inspect_skip_layout', 'distributed/pipeline/sync/skip/test_leak', 'distributed/pipeline/sync/skip/test_portal', 'distributed/pipeline/sync/skip/test_stash_pop', 'distributed/pipeline/sync/skip/test_tracker', 'distributed/pipeline/sync/skip/test_verify_skippables', 'distributed/pipeline/sync/test_balance', 'distributed/pipeline/sync/test_bugs', 'distributed/pipeline/sync/test_checkpoint', 'distributed/pipeline/sync/test_copy', 'distributed/pipeline/sync/test_deferred_batch_norm', 'distributed/pipeline/sync/test_dependency', 'distributed/pipeline/sync/test_inplace', 'distributed/pipeline/sync/test_microbatch', 'distributed/pipeline/sync/test_phony', 'distributed/pipeline/sync/test_pipe', 'distributed/pipeline/sync/test_pipeline', 'distributed/pipeline/sync/test_stream', 'distributed/pipeline/sync/test_transparency', 'distributed/pipeline/sync/test_worker', 'distributed/optim/test_zero_redundancy_optimizer', 'distributed/elastic/timer/api_test', 'distributed/elastic/timer/local_timer_example', 'distributed/elastic/timer/local_timer_test', 'distributed/elastic/events/lib_test', 'distributed/elastic/metrics/api_test', 'distributed/elastic/utils/logging_test', 'distributed/elastic/utils/util_test', 'distributed/elastic/utils/distributed_test', 'distributed/elastic/multiprocessing/api_test', ] # Tests need to be run with pytest. USE_PYTEST_LIST = [ 'distributed/pipeline/sync/skip/test_api', 'distributed/pipeline/sync/skip/test_gpipe', 'distributed/pipeline/sync/skip/test_inspect_skip_layout', 'distributed/pipeline/sync/skip/test_leak', 'distributed/pipeline/sync/skip/test_portal', 'distributed/pipeline/sync/skip/test_stash_pop', 'distributed/pipeline/sync/skip/test_tracker', 'distributed/pipeline/sync/skip/test_verify_skippables', 'distributed/pipeline/sync/test_balance', 'distributed/pipeline/sync/test_bugs', 'distributed/pipeline/sync/test_checkpoint', 'distributed/pipeline/sync/test_copy', 'distributed/pipeline/sync/test_deferred_batch_norm', 'distributed/pipeline/sync/test_dependency', 'distributed/pipeline/sync/test_inplace', 'distributed/pipeline/sync/test_microbatch', 'distributed/pipeline/sync/test_phony', 'distributed/pipeline/sync/test_pipe', 'distributed/pipeline/sync/test_pipeline', 'distributed/pipeline/sync/test_stream', 'distributed/pipeline/sync/test_transparency', 'distributed/pipeline/sync/test_worker', 'distributions/test_constraints', 'distributions/test_transforms', 'distributions/test_utils', 'test_typing', "distributed/elastic/events/lib_test", "distributed/elastic/agent/server/test/api_test", ] WINDOWS_BLOCKLIST = [ 'distributed/nn/jit/test_instantiator', 'distributed/rpc/test_faulty_agent', 'distributed/rpc/test_process_group_agent', 'distributed/rpc/cuda/test_process_group_agent', 'distributed/rpc/test_tensorpipe_agent', 'distributed/rpc/cuda/test_tensorpipe_agent', 'distributed/test_distributed_fork', 'distributed/pipeline/sync/skip/test_api', 'distributed/pipeline/sync/skip/test_gpipe', 'distributed/pipeline/sync/skip/test_inspect_skip_layout', 'distributed/pipeline/sync/skip/test_leak', 'distributed/pipeline/sync/skip/test_portal', 'distributed/pipeline/sync/skip/test_stash_pop', 'distributed/pipeline/sync/skip/test_tracker', 'distributed/pipeline/sync/skip/test_verify_skippables', 'distributed/pipeline/sync/test_balance', 'distributed/pipeline/sync/test_bugs', 'distributed/pipeline/sync/test_checkpoint', 'distributed/pipeline/sync/test_copy', 'distributed/pipeline/sync/test_deferred_batch_norm', 'distributed/pipeline/sync/test_dependency', 'distributed/pipeline/sync/test_inplace', 'distributed/pipeline/sync/test_microbatch', 'distributed/pipeline/sync/test_phony', 'distributed/pipeline/sync/test_pipe', 'distributed/pipeline/sync/test_pipeline', 'distributed/pipeline/sync/test_stream', 'distributed/pipeline/sync/test_transparency', 'distributed/pipeline/sync/test_worker', 'distributed/optim/test_zero_redundancy_optimizer', "distributed/elastic/agent/server/test/api_test", 'distributed/elastic/multiprocessing/api_test', ] ROCM_BLOCKLIST = [ 'distributed/nn/jit/test_instantiator', 'distributed/rpc/test_faulty_agent', 'distributed/rpc/test_process_group_agent', 'distributed/rpc/cuda/test_process_group_agent', 'distributed/rpc/test_tensorpipe_agent', 'distributed/rpc/cuda/test_tensorpipe_agent', 'test_determination', 'test_multiprocessing', 'test_jit_legacy', 'test_type_hints', 'test_openmp', ] RUN_PARALLEL_BLOCKLIST = [ 'test_cpp_extensions_jit', 'test_expecttest', 'test_jit_disabled', 'test_mobile_optimizer', 'test_multiprocessing', 'test_multiprocessing_spawn', 'test_namedtuple_return_api', 'test_overrides', 'test_show_pickle', 'test_tensorexpr', 'test_cuda_primary_ctx', ] + [test for test in TESTS if test.startswith('distributed/')] WINDOWS_COVERAGE_BLOCKLIST = [ ] # These tests are slow enough that it's worth calculating whether the patch # touched any related files first. This list was manually generated, but for every # run with --determine-from, we use another generated list based on this one and the # previous test stats. TARGET_DET_LIST = [ 'distributions/test_distributions', 'test_nn', 'test_autograd', 'test_cpp_extensions_jit', 'test_jit_legacy', 'test_dataloader', 'test_overrides', 'test_linalg', 'test_jit', 'test_jit_profiling', 'test_torch', 'test_binary_ufuncs', 'test_numpy_interop', 'test_reductions', 'test_shape_ops', 'test_sort_and_select', 'test_testing', 'test_view_ops', 'distributed/nn/jit/test_instantiator', 'distributed/test_distributed_fork', 'distributed/rpc/test_process_group_agent', 'distributed/rpc/cuda/test_process_group_agent', 'distributed/rpc/test_tensorpipe_agent', 'distributed/rpc/cuda/test_tensorpipe_agent', 'distributed/algorithms/ddp_comm_hooks/test_ddp_hooks', 'distributed/test_distributed_spawn', 'test_cuda', 'test_cuda_primary_ctx', 'test_cpp_extensions_aot_ninja', 'test_cpp_extensions_aot_no_ninja', 'test_serialization', 'test_optim', 'test_utils', 'test_multiprocessing', 'test_tensorboard', 'distributed/test_c10d_common', 'distributed/test_c10d_gloo', 'distributed/test_c10d_nccl', 'distributed/test_jit_c10d', 'distributed/test_c10d_spawn_gloo', 'distributed/test_c10d_spawn_nccl', 'test_quantization', 'test_pruning_op', 'test_determination', 'test_futures', 'distributed/pipeline/sync/skip/test_api', 'distributed/pipeline/sync/skip/test_gpipe', 'distributed/pipeline/sync/skip/test_inspect_skip_layout', 'distributed/pipeline/sync/skip/test_leak', 'distributed/pipeline/sync/skip/test_portal', 'distributed/pipeline/sync/skip/test_stash_pop', 'distributed/pipeline/sync/skip/test_tracker', 'distributed/pipeline/sync/skip/test_verify_skippables', 'distributed/pipeline/sync/test_balance', 'distributed/pipeline/sync/test_bugs', 'distributed/pipeline/sync/test_checkpoint', 'distributed/pipeline/sync/test_copy', 'distributed/pipeline/sync/test_deferred_batch_norm', 'distributed/pipeline/sync/test_dependency', 'distributed/pipeline/sync/test_inplace', 'distributed/pipeline/sync/test_microbatch', 'distributed/pipeline/sync/test_phony', 'distributed/pipeline/sync/test_pipe', 'distributed/pipeline/sync/test_pipeline', 'distributed/pipeline/sync/test_stream', 'distributed/pipeline/sync/test_transparency', 'distributed/pipeline/sync/test_worker', ] # the JSON file to store the S3 test stats TEST_TIMES_FILE = '.pytorch-test-times' # if a test file takes longer than 5 min, we add it to TARGET_DET_LIST SLOW_TEST_THRESHOLD = 300 _DEP_MODULES_CACHE: Dict[str, set] = {} DISTRIBUTED_TESTS_CONFIG = {} if dist.is_available(): DISTRIBUTED_TESTS_CONFIG['test'] = { 'WORLD_SIZE': '1' } if not TEST_WITH_ROCM and dist.is_mpi_available(): DISTRIBUTED_TESTS_CONFIG['mpi'] = { 'WORLD_SIZE': '3', 'TEST_REPORT_SOURCE_OVERRIDE': 'dist-mpi' } if dist.is_nccl_available(): DISTRIBUTED_TESTS_CONFIG['nccl'] = { 'WORLD_SIZE': '2' if torch.cuda.device_count() == 2 else '3', 'TEST_REPORT_SOURCE_OVERRIDE': 'dist-nccl' } if dist.is_gloo_available(): DISTRIBUTED_TESTS_CONFIG['gloo'] = { 'WORLD_SIZE': '2' if torch.cuda.device_count() == 2 else '3', 'TEST_REPORT_SOURCE_OVERRIDE': 'dist-gloo' } # https://stackoverflow.com/questions/2549939/get-signal-names-from-numbers-in-python SIGNALS_TO_NAMES_DICT = {getattr(signal, n): n for n in dir(signal) if n.startswith('SIG') and '_' not in n} CPP_EXTENSIONS_ERROR = """ Ninja (https://ninja-build.org) is required for some of the C++ extensions tests, but it could not be found. Install ninja with `pip install ninja` or `conda install ninja`. Alternatively, disable said tests with `run_test.py --exclude test_cpp_extensions_aot_ninja test_cpp_extensions_jit`. """ PYTORCH_COLLECT_COVERAGE = bool(os.environ.get("PYTORCH_COLLECT_COVERAGE")) JIT_EXECUTOR_TESTS = [ 'test_jit_cuda_fuser', 'test_jit_profiling', 'test_jit_legacy', 'test_jit_fuser_legacy', ] def print_to_stderr(message): print(message, file=sys.stderr) # Convert something like pytorch_windows_vs2019_py36_cuda10.1_build to pytorch_windows_vs2019_py36_cuda10.1 def get_stripped_CI_job() -> str: job = os.environ.get("CIRCLE_JOB", "").rstrip('0123456789') if job.endswith('_slow_test'): job = job[:len(job) - len('_slow_test')] elif job.endswith('_test'): job = job[:len(job) - len('_test')] elif job.endswith('_build'): job = job[:len(job) - len('_build')] return job def calculate_job_times(reports: List["Report"]) -> Dict[str, float]: # an entry will be like ("test_file_name" -> (current_avg, # values)) jobs_to_times: Dict[str, Tuple[float, int]] = dict() for report in reports: assert report.get('format_version') == 2, "S3 format currently handled is version 2 only" files: Dict[str, Any] = report['files'] for name, test_file in files.items(): if name not in jobs_to_times: jobs_to_times[name] = (test_file['total_seconds'], 1) else: curr_avg, curr_count = jobs_to_times[name] new_count = curr_count + 1 new_avg = (curr_avg * curr_count + test_file['total_seconds']) / new_count jobs_to_times[name] = (new_avg, new_count) # if there's 'test_cpp_extensions_aot' entry in jobs_to_times, add 'test_cpp_extensions_aot_ninja' # and 'test_cpp_extensions_aot_no_ninja' duplicate entries to ease future computation since # test_cpp_extensions_aot_no_ninja and test_cpp_extensions_aot_ninja are Python test jobs that # both use the test_cpp_extensions_aot.py file. if 'test_cpp_extensions_aot' in jobs_to_times: jobs_to_times['test_cpp_extensions_aot_ninja'] = jobs_to_times['test_cpp_extensions_aot'] jobs_to_times['test_cpp_extensions_aot_no_ninja'] = jobs_to_times['test_cpp_extensions_aot'] return {job: time for job, (time, _) in jobs_to_times.items()} def pull_job_times_from_S3() -> Dict[str, float]: if HAVE_BOTO3: ci_job_prefix = get_stripped_CI_job() s3_reports: List["Report"] = get_previous_reports_for_branch('origin/nightly', ci_job_prefix) else: print('Uh oh, boto3 is not found. Either it is not installed or we failed to import s3_stat_parser.') print('If not installed, please install boto3 for automatic sharding and test categorization.') s3_reports = [] if len(s3_reports) == 0: print('Gathered no reports from S3. Please proceed without them.') return dict() return calculate_job_times(s3_reports) def get_past_job_times() -> Dict[str, float]: if os.path.exists(TEST_TIMES_FILE): with open(TEST_TIMES_FILE) as file: test_times_json: JobTimeJSON = json.load(file) curr_commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], encoding="ascii").strip() file_commit = test_times_json.get('commit', '') curr_ci_job = get_stripped_CI_job() file_ci_job = test_times_json.get('CIRCLE_JOB', 'N/A') if curr_commit != file_commit: print(f'Current test times file is from different commit {file_commit}.') elif curr_ci_job != file_ci_job: print(f'Current test times file is for different CI job {file_ci_job}.') else: print(f'Found stats for current commit: {curr_commit} and job: {curr_ci_job}. Proceeding with those values.') return test_times_json.get('job_times', {}) # Found file, but commit or CI job in JSON doesn't match print(f'Overwriting current file with stats based on current commit: {curr_commit} and CI job: {curr_ci_job}') job_times = pull_job_times_from_S3() print(f'Exporting S3 test stats to {TEST_TIMES_FILE}.') export_S3_test_times(TEST_TIMES_FILE, job_times) return job_times class JobTimeJSON(TypedDict): commit: str job_times: Dict[str, float] def get_job_times_json(job_times: Dict[str, float]) -> JobTimeJSON: return { 'commit': subprocess.check_output(['git', 'rev-parse', 'HEAD'], encoding="ascii").strip(), 'CIRCLE_JOB': get_stripped_CI_job(), 'job_times': job_times, } def get_shard(which_shard: int, num_shards: int, tests: List[str]) -> List[str]: jobs_to_times = get_past_job_times() # Got no stats from S3, returning early to save runtime if len(jobs_to_times) == 0: print('Gathered no stats from S3. Proceeding with default sharding plan.') return tests[which_shard - 1 :: num_shards] shards = calculate_shards(num_shards, tests, jobs_to_times) _, tests_from_shard = shards[which_shard - 1] return tests_from_shard def get_slow_tests_based_on_S3() -> List[str]: jobs_to_times: Dict[str, float] = get_past_job_times() # Got no stats from S3, returning early to save runtime if len(jobs_to_times) == 0: print('Gathered no stats from S3. No new slow tests calculated.') return [] slow_tests: List[str] = [] for test in TESTS: if test in jobs_to_times and test not in TARGET_DET_LIST: if jobs_to_times[test] > SLOW_TEST_THRESHOLD: slow_tests.append(test) return slow_tests def get_executable_command(options, allow_pytest, disable_coverage=False): if options.coverage and not disable_coverage: executable = ['coverage', 'run', '--parallel-mode', '--source=torch'] else: executable = [sys.executable] if options.pytest: if allow_pytest: executable += ['-m', 'pytest'] else: print_to_stderr('Pytest cannot be used for this test. Falling back to unittest.') return executable def run_test(test_module, test_directory, options, launcher_cmd=None, extra_unittest_args=None): unittest_args = options.additional_unittest_args.copy() if options.verbose: unittest_args.append(f'-{'v'*options.verbose}') # in case of pytest if test_module in RUN_PARALLEL_BLOCKLIST: unittest_args = [arg for arg in unittest_args if not arg.startswith('--run-parallel')] if extra_unittest_args: assert isinstance(extra_unittest_args, list) unittest_args.extend(extra_unittest_args) # If using pytest, replace -f with equivalent -x if options.pytest: unittest_args = [arg if arg != '-f' else '-x' for arg in unittest_args] # Can't call `python -m unittest test_*` here because it doesn't run code # in `if __name__ == '__main__': `. So call `python test_*.py` instead. argv = [test_module + '.py'] + unittest_args # Multiprocessing related tests cannot run with coverage. # Tracking issue: https://github.com/pytorch/pytorch/issues/50661 disable_coverage = sys.platform == 'win32' and test_module in WINDOWS_COVERAGE_BLOCKLIST # Extra arguments are not supported with pytest executable = get_executable_command(options, allow_pytest=not extra_unittest_args, disable_coverage=disable_coverage) command = (launcher_cmd or []) + executable + argv print_to_stderr('Executing {} ... [{}]'.format(command, datetime.now())) return shell(command, test_directory) def test_cuda_primary_ctx(test_module, test_directory, options): return run_test(test_module, test_directory, options, extra_unittest_args=['--subprocess']) def _test_cpp_extensions_aot(test_module, test_directory, options, use_ninja): if use_ninja: try: cpp_extension.verify_ninja_availability() except RuntimeError: print(CPP_EXTENSIONS_ERROR) return 1 # Wipe the build folder, if it exists already cpp_extensions_test_dir = os.path.join(test_directory, 'cpp_extensions') cpp_extensions_test_build_dir = os.path.join(cpp_extensions_test_dir, 'build') if os.path.exists(cpp_extensions_test_build_dir): shutil.rmtree(cpp_extensions_test_build_dir) # Build the test cpp extensions modules shell_env = os.environ.copy() shell_env['USE_NINJA'] = str(1 if use_ninja else 0) cmd = [sys.executable, 'setup.py', 'install', '--root', './install'] return_code = shell(cmd, cwd=cpp_extensions_test_dir, env=shell_env) if return_code != 0: return return_code if sys.platform != 'win32': return_code = shell(cmd, cwd=os.path.join(cpp_extensions_test_dir, 'no_python_abi_suffix_test'), env=shell_env) if return_code != 0: return return_code # "install" the test modules and run tests python_path = os.environ.get('PYTHONPATH', '') try: cpp_extensions = os.path.join(test_directory, 'cpp_extensions') install_directory = '' # install directory is the one that is named site-packages for root, directories, _ in os.walk(os.path.join(cpp_extensions, 'install')): for directory in directories: if '-packages' in directory: install_directory = os.path.join(root, directory) assert install_directory, 'install_directory must not be empty' os.environ['PYTHONPATH'] = os.pathsep.join([install_directory, python_path]) return run_test(test_module, test_directory, options) finally: os.environ['PYTHONPATH'] = python_path def test_cpp_extensions_aot_ninja(test_module, test_directory, options): return _test_cpp_extensions_aot('test_cpp_extensions_aot', test_directory, options, use_ninja=True) def test_cpp_extensions_aot_no_ninja(test_module, test_directory, options): return _test_cpp_extensions_aot('test_cpp_extensions_aot', test_directory, options, use_ninja=False) def test_distributed(test_module, test_directory, options): # MPI tests are broken with Python-3.9 mpi_available = subprocess.call('command -v mpiexec', shell=True) == 0 and sys.version_info < (3, 9) if options.verbose and not mpi_available: print_to_stderr( 'MPI not available -- MPI backend tests will be skipped') config = DISTRIBUTED_TESTS_CONFIG for backend, env_vars in config.items(): if sys.platform == 'win32' and backend != 'gloo': continue if backend == 'mpi' and not mpi_available: continue for with_init_file in {True, False}: if sys.platform == 'win32' and not with_init_file: continue tmp_dir = tempfile.mkdtemp() if options.verbose: init_str = "with {} init_method" with_init = init_str.format("file" if with_init_file else "env") print_to_stderr( 'Running distributed tests for the {} backend {}'.format( backend, with_init)) os.environ['TEMP_DIR'] = tmp_dir os.environ['BACKEND'] = backend os.environ['INIT_METHOD'] = 'env://' os.environ.update(env_vars) if with_init_file: if test_module in ["test_distributed_fork", "test_distributed_spawn"]: init_method = f'{FILE_SCHEMA}{tmp_dir}/' else: init_method = f'{FILE_SCHEMA}{tmp_dir}/shared_init_file' os.environ['INIT_METHOD'] = init_method try: os.mkdir(os.path.join(tmp_dir, 'barrier')) os.mkdir(os.path.join(tmp_dir, 'test_dir')) if backend == 'mpi': # test mpiexec for --noprefix option with open(os.devnull, 'w') as devnull: allowrunasroot_opt = '--allow-run-as-root' if subprocess.call( 'mpiexec --allow-run-as-root -n 1 bash -c ""', shell=True, stdout=devnull, stderr=subprocess.STDOUT) == 0 else '' noprefix_opt = '--noprefix' if subprocess.call( f'mpiexec {allowrunasroot_opt} -n 1 --noprefix bash -c ""', shell=True, stdout=devnull, stderr=subprocess.STDOUT) == 0 else '' mpiexec = ['mpiexec', '-n', '3', noprefix_opt, allowrunasroot_opt] return_code = run_test(test_module, test_directory, options, launcher_cmd=mpiexec) else: return_code = run_test(test_module, test_directory, options) if return_code != 0: return return_code finally: shutil.rmtree(tmp_dir) return 0 CUSTOM_HANDLERS = { 'test_cuda_primary_ctx': test_cuda_primary_ctx, 'test_cpp_extensions_aot_no_ninja': test_cpp_extensions_aot_no_ninja, 'test_cpp_extensions_aot_ninja': test_cpp_extensions_aot_ninja, 'distributed/test_distributed_fork': test_distributed, 'distributed/test_distributed_spawn': test_distributed, } def parse_test_module(test): return test.split('.')[0] class TestChoices(list): def __init__(self, *args, **kwargs): super(TestChoices, self).__init__(args[0]) def __contains__(self, item): return list.__contains__(self, parse_test_module(item)) def parse_args(): parser = argparse.ArgumentParser( description='Run the PyTorch unit test suite', epilog='where TESTS is any of: {}'.format(', '.join(TESTS))) parser.add_argument( '-v', '--verbose', action='count', default=0, help='print verbose information and test-by-test results') parser.add_argument( '--jit', '--jit', action='store_true', help='run all jit tests') parser.add_argument( '-pt', '--pytest', action='store_true', help='If true, use `pytest` to execute the tests. E.g., this runs ' 'TestTorch with pytest in verbose and coverage mode: ' 'python run_test.py -vci torch -pt') parser.add_argument( '-c', '--coverage', action='store_true', help='enable coverage', default=PYTORCH_COLLECT_COVERAGE) parser.add_argument( '-i', '--include', nargs='+', choices=TestChoices(TESTS), default=TESTS, metavar='TESTS', help='select a set of tests to include (defaults to ALL tests).' ' tests can be specified with module name, module.TestClass' ' or module.TestClass.test_method') parser.add_argument( '-x', '--exclude', nargs='+', choices=TESTS, metavar='TESTS', default=[], help='select a set of tests to exclude') parser.add_argument( '-f', '--first', choices=TESTS, metavar='TESTS', help='select the test to start from (excludes previous tests)') parser.add_argument( '-l', '--last', choices=TESTS, metavar='TESTS', help='select the last test to run (excludes following tests)') parser.add_argument( '--bring-to-front', nargs='+', choices=TestChoices(TESTS), default=[], metavar='TESTS', help='select a set of tests to run first. This can be used in situations' ' where you want to run all tests, but care more about some set, ' 'e.g. after making a change to a specific component') parser.add_argument( '--ignore-win-blocklist', action='store_true', help='always run blocklisted windows tests') parser.add_argument( '--determine-from', help='File of affected source filenames to determine which tests to run.') parser.add_argument( '--continue-through-error', action='store_true', help='Runs the full test suite despite one of the tests failing') parser.add_argument( 'additional_unittest_args', nargs='*', help='additional arguments passed through to unittest, e.g., ' 'python run_test.py -i sparse -- TestSparse.test_factory_size_check') parser.add_argument( '--export-past-test-times', nargs='?', type=str, const=TEST_TIMES_FILE, help='dumps test times from previous S3 stats into a file, format JSON', ) parser.add_argument( '--shard', nargs=2, type=int, help='runs a shard of the tests (taking into account other selections), e.g., ' '--shard 2 3 will break up the selected tests into 3 shards and run the tests ' 'in the 2nd shard (the first number should not exceed the second)', ) parser.add_argument( '--exclude-jit-executor', action='store_true', help='exclude tests that are run for a specific jit config' ) return parser.parse_args() def find_test_index(test, selected_tests, find_last_index=False): """Find the index of the first or last occurrence of a given test/test module in the list of selected tests. This function is used to determine the indices when slicing the list of selected tests when ``options.first``(:attr:`find_last_index`=False) and/or ``options.last``(:attr:`find_last_index`=True) are used. :attr:`selected_tests` can be a list that contains multiple consequent occurrences of tests as part of the same test module, e.g.: ``` selected_tests = ['autograd', 'cuda', **'torch.TestTorch.test_acos', 'torch.TestTorch.test_tan', 'torch.TestTorch.test_add'**, 'utils'] ``` If :attr:`test`='torch' and :attr:`find_last_index`=False, result should be **2**. If :attr:`test`='torch' and :attr:`find_last_index`=True, result should be **4**. Args: test (str): Name of test to lookup selected_tests (list): List of tests find_last_index (bool, optional): should we lookup the index of first or last occurrence (first is default) Returns: index of the first or last occurrence of the given test """ idx = 0 found_idx = -1 for t in selected_tests: if t.startswith(test): found_idx = idx if not find_last_index: break idx += 1 return found_idx def exclude_tests(exclude_list, selected_tests, exclude_message=None): for exclude_test in exclude_list: tests_copy = selected_tests[:] for test in tests_copy: if test.startswith(exclude_test): if exclude_message is not None: print_to_stderr('Excluding {} {}'.format(test, exclude_message)) selected_tests.remove(test) return selected_tests def get_selected_tests(options): selected_tests = options.include if options.bring_to_front: to_front = set(options.bring_to_front) selected_tests = options.bring_to_front + list(filter(lambda name: name not in to_front, selected_tests)) if options.first: first_index = find_test_index(options.first, selected_tests) selected_tests = selected_tests[first_index:] if options.last: last_index = find_test_index(options.last, selected_tests, find_last_index=True) selected_tests = selected_tests[:last_index + 1] if options.shard: assert len(options.shard) == 2, "Unexpected shard format" assert min(options.shard) > 0, "Shards must be positive numbers" which_shard, num_shards = options.shard assert which_shard <= num_shards, "Selected shard must be less or equal that total number of shards" assert num_shards <= len(selected_tests), f"Number of shards must be less than {len(selected_tests)}" selected_tests = get_shard(which_shard, num_shards, selected_tests) if options.exclude_jit_executor: options.exclude.extend(JIT_EXECUTOR_TESTS) selected_tests = exclude_tests(options.exclude, selected_tests) if sys.platform == 'win32' and not options.ignore_win_blocklist: target_arch = os.environ.get('VSCMD_ARG_TGT_ARCH') if target_arch != 'x64': WINDOWS_BLOCKLIST.append('cpp_extensions_aot_no_ninja') WINDOWS_BLOCKLIST.append('cpp_extensions_aot_ninja') WINDOWS_BLOCKLIST.append('cpp_extensions_jit') WINDOWS_BLOCKLIST.append('jit') WINDOWS_BLOCKLIST.append('jit_fuser') selected_tests = exclude_tests(WINDOWS_BLOCKLIST, selected_tests, 'on Windows') elif TEST_WITH_ROCM: selected_tests = exclude_tests(ROCM_BLOCKLIST, selected_tests, 'on ROCm') return selected_tests def test_impact_of_file(filename): """Determine what class of impact this file has on test runs. Possible values: TORCH - torch python code CAFFE2 - caffe2 python code TEST - torch test code UNKNOWN - may affect all tests NONE - known to have no effect on test outcome CI - CI configuration files """ parts = filename.split(os.sep) if parts[0] in ['.jenkins', '.circleci']: return 'CI' if parts[0] in ['docs', 'scripts', 'CODEOWNERS', 'README.md']: return 'NONE' elif parts[0] == 'torch': if parts[-1].endswith('.py') or parts[-1].endswith('.pyi'): return 'TORCH' elif parts[0] == 'caffe2': if parts[-1].endswith('.py') or parts[-1].endswith('.pyi'): return 'CAFFE2' elif parts[0] == 'test': if parts[-1].endswith('.py') or parts[-1].endswith('.pyi'): return 'TEST' return 'UNKNOWN' def log_test_reason(file_type, filename, test, options): if options.verbose: print_to_stderr( 'Determination found {} file {} -- running {}'.format( file_type, filename, test, ) ) def get_dep_modules(test): # Cache results in case of repetition if test in _DEP_MODULES_CACHE: return _DEP_MODULES_CACHE[test] repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) test_location = os.path.join(repo_root, 'test', test + '.py') finder = modulefinder.ModuleFinder( # Ideally exclude all third party modules, to speed up calculation. excludes=[ 'scipy', 'numpy', 'numba', 'multiprocessing', 'sklearn', 'setuptools', 'hypothesis', 'llvmlite', 'joblib', 'email', 'importlib', 'unittest', 'urllib', 'json', 'collections', # Modules below are excluded because they are hitting https://bugs.python.org/issue40350 # Trigger AttributeError: 'NoneType' object has no attribute 'is_package' 'mpl_toolkits', 'google', 'onnx', # Triggers RecursionError 'mypy' ], ) # HACK: some platforms default to ascii, so we can't just run_script :( with open(test_location, 'r', encoding='utf-8') as fp: finder.load_module('__main__', fp, test_location, ('', 'r', 1)) dep_modules = set(finder.modules.keys()) _DEP_MODULES_CACHE[test] = dep_modules return dep_modules def determine_target(target_det_list, test, touched_files, options): test = parse_test_module(test) # Some tests are faster to execute than to determine. if test not in target_det_list: if options.verbose: print_to_stderr(f'Running {test} without determination') return True # HACK: "no_ninja" is not a real module if test.endswith('_no_ninja'): test = test[:(-1 * len('_no_ninja'))] if test.endswith('_ninja'): test = test[:(-1 * len('_ninja'))] dep_modules = get_dep_modules(test) for touched_file in touched_files: file_type = test_impact_of_file(touched_file) if file_type == 'NONE': continue elif file_type == 'CI': # Force all tests to run if any change is made to the CI # configurations. log_test_reason(file_type, touched_file, test, options) return True elif file_type == 'UNKNOWN': # Assume uncategorized source files can affect every test. log_test_reason(file_type, touched_file, test, options) return True elif file_type in ['TORCH', 'CAFFE2', 'TEST']: parts = os.path.splitext(touched_file)[0].split(os.sep) touched_module = ".".join(parts) # test/ path does not have a "test." namespace if touched_module.startswith('test.'): touched_module = touched_module.split('test.')[1] if ( touched_module in dep_modules or touched_module == test.replace('/', '.') ): log_test_reason(file_type, touched_file, test, options) return True # If nothing has determined the test has run, don't run the test. if options.verbose: print_to_stderr(f'Determination is skipping {test}') return False def run_test_module(test: str, test_directory: str, options) -> Optional[str]: test_module = parse_test_module(test) # Printing the date here can help diagnose which tests are slow print_to_stderr('Running {} ... [{}]'.format(test, datetime.now())) handler = CUSTOM_HANDLERS.get(test_module, run_test) return_code = handler(test_module, test_directory, options) assert isinstance(return_code, int) and not isinstance( return_code, bool), 'Return code should be an integer' if return_code == 0: return None message = f'{test} failed!' if return_code < 0: # subprocess.Popen returns the child process' exit signal as # return code -N, where N is the signal number. signal_name = SIGNALS_TO_NAMES_DICT[-return_code] message += f' Received signal: {signal_name}' return message def export_S3_test_times(test_times_filename: str, test_times: Dict[str, float]) -> None: if os.path.exists(test_times_filename): print(f'Overwriting existent file: {test_times_filename}') with open(test_times_filename, 'w+') as file: job_times_json = get_job_times_json(test_times) json.dump(job_times_json, file, indent=' ', separators=(',', ': ')) file.write('\n') def query_changed_test_files() -> List[str]: cmd = ["git", "diff", "--name-only", "origin/master", "HEAD"] proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if proc.returncode != 0: raise RuntimeError("Unable to get changed files") lines = proc.stdout.decode().strip().split("\n") lines = [line.strip() for line in lines] return lines def reorder_tests(tests: List[str]) -> List[str]: try: changed_files = query_changed_test_files() except Exception: # If unable to get changed files from git, quit without doing any sorting return tests prefix = f"test{os.path.sep}" changed_tests = [f for f in changed_files if f.startswith(prefix) and f.endswith(".py")] changed_tests = [f[len(prefix):] for f in changed_tests] changed_tests = [f[:-len(".py")] for f in changed_tests] bring_to_front = [] the_rest = [] for test in tests: if test in changed_tests: bring_to_front.append(test) else: the_rest.append(test) sorted_tests = bring_to_front + the_rest if len(sorted_tests) != len(tests): # Something went wrong, bail out without doing any sorting return tests return sorted_tests def main(): options = parse_args() test_times_filename = options.export_past_test_times if test_times_filename: print(f'Exporting past test times from S3 to {test_times_filename}, no tests will be run.') export_S3_test_times(test_times_filename, pull_job_times_from_S3()) return test_directory = os.path.dirname(os.path.abspath(__file__)) selected_tests = get_selected_tests(options) if options.verbose: print_to_stderr('Selected tests: {}'.format(', '.join(selected_tests))) if options.coverage and not PYTORCH_COLLECT_COVERAGE: shell(['coverage', 'erase']) if options.jit: selected_tests = filter(lambda test_name: "jit" in test_name, TESTS) if options.determine_from is not None and os.path.exists(options.determine_from): slow_tests = get_slow_tests_based_on_S3() print('Added the following tests to target_det tests as calculated based on S3:') print(slow_tests) with open(options.determine_from, 'r') as fh: touched_files = [ os.path.normpath(name.strip()) for name in fh.read().split('\n') if len(name.strip()) > 0 ] # HACK: Ensure the 'test' paths can be traversed by Modulefinder sys.path.append('test') selected_tests = [ test for test in selected_tests if determine_target(TARGET_DET_LIST + slow_tests, test, touched_files, options) ] sys.path.remove('test') selected_tests = reorder_tests(selected_tests) has_failed = False failure_messages = [] try: for test in selected_tests: options_clone = copy.deepcopy(options) if test in USE_PYTEST_LIST: options_clone.pytest = True err_message = run_test_module(test, test_directory, options_clone) if err_message is None: continue has_failed = True failure_messages.append(err_message) if not options_clone.continue_through_error: raise RuntimeError(err_message) print_to_stderr(err_message) finally: if options.coverage: from coverage import Coverage test_dir = os.path.dirname(os.path.abspath(__file__)) with set_cwd(test_dir): cov = Coverage() if PYTORCH_COLLECT_COVERAGE: cov.load() cov.combine(strict=False) cov.save() if not PYTORCH_COLLECT_COVERAGE: cov.html_report() if options.continue_through_error and has_failed: for err in failure_messages: print_to_stderr(err) sys.exit(1) if __name__ == '__main__': main()
#!/usr/bin/env python3 import argparse import copy from datetime import datetime import json import modulefinder import os import shutil import signal import subprocess import sys import tempfile import torch from torch.utils import cpp_extension from torch.testing._internal.common_utils import TEST_WITH_ROCM, shell, set_cwd, FILE_SCHEMA from torch.testing._internal.framework_utils import calculate_shards import torch.distributed as dist from typing import Dict, Optional, Tuple, List, Any from typing_extensions import TypedDict try: sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) from tools.stats_utils.s3_stat_parser import (get_previous_reports_for_branch, Report, HAVE_BOTO3) except ImportError: print("Unable to import s3_stat_parser from tools. Running without S3 stats...") HAVE_BOTO3 = False TESTS = [ 'test_import_time', 'test_public_bindings', 'test_type_hints', 'test_autograd', 'benchmark_utils/test_benchmark_utils', 'test_binary_ufuncs', 'test_bundled_inputs', 'test_complex', 'test_cpp_api_parity', 'test_cpp_extensions_aot_no_ninja', 'test_cpp_extensions_aot_ninja', 'test_cpp_extensions_jit', 'distributed/test_c10d_common', 'distributed/test_c10d_gloo', 'distributed/test_c10d_nccl', 'distributed/test_jit_c10d', 'distributed/test_c10d_spawn_gloo', 'distributed/test_c10d_spawn_nccl', 'test_cuda', 'test_jit_cuda_fuser', 'test_cuda_primary_ctx', 'test_dataloader', 'test_datapipe', 'distributed/test_data_parallel', 'distributed/test_distributed_fork', 'distributed/test_distributed_spawn', 'distributions/test_constraints', 'distributions/test_distributions', 'test_dispatch', 'test_expecttest', 'test_foreach', 'test_indexing', 'test_jit', 'test_linalg', 'test_logging', 'test_mkldnn', 'test_model_dump', 'test_module_init', 'test_multiprocessing', 'test_multiprocessing_spawn', 'distributed/test_nccl', 'test_native_functions', 'test_numba_integration', 'test_nn', 'test_ops', 'test_optim', 'test_pytree', 'test_mobile_optimizer', 'test_set_default_mobile_cpu_allocator', 'test_xnnpack_integration', 'test_vulkan', 'test_sparse', 'test_sparse_csr', 'test_quantization', 'test_pruning_op', 'test_spectral_ops', 'test_serialization', 'test_shape_ops', 'test_show_pickle', 'test_sort_and_select', 'test_tensor_creation_ops', 'test_testing', 'test_torch', 'test_type_info', 'test_unary_ufuncs', 'test_utils', 'test_view_ops', 'test_vmap', 'test_namedtuple_return_api', 'test_numpy_interop', 'test_jit_profiling', 'test_jit_legacy', 'test_jit_fuser_legacy', 'test_tensorboard', 'test_namedtensor', 'test_reductions', 'test_type_promotion', 'test_jit_disabled', 'test_function_schema', 'test_op_aliases', 'test_overrides', 'test_jit_fuser_te', 'test_tensorexpr', 'test_tensorexpr_pybind', 'test_openmp', 'test_profiler', "distributed/test_launcher", 'distributed/nn/jit/test_instantiator', 'distributed/rpc/test_faulty_agent', 'distributed/rpc/test_process_group_agent', 'distributed/rpc/cuda/test_process_group_agent', 'distributed/rpc/test_tensorpipe_agent', 'distributed/rpc/cuda/test_tensorpipe_agent', 'test_determination', 'test_futures', 'test_fx', 'test_fx_experimental', 'test_functional_autograd_benchmark', 'test_package', 'test_license', 'distributed/pipeline/sync/skip/test_api', 'distributed/pipeline/sync/skip/test_gpipe', 'distributed/pipeline/sync/skip/test_inspect_skip_layout', 'distributed/pipeline/sync/skip/test_leak', 'distributed/pipeline/sync/skip/test_portal', 'distributed/pipeline/sync/skip/test_stash_pop', 'distributed/pipeline/sync/skip/test_tracker', 'distributed/pipeline/sync/skip/test_verify_skippables', 'distributed/pipeline/sync/test_balance', 'distributed/pipeline/sync/test_bugs', 'distributed/pipeline/sync/test_checkpoint', 'distributed/pipeline/sync/test_copy', 'distributed/pipeline/sync/test_deferred_batch_norm', 'distributed/pipeline/sync/test_dependency', 'distributed/pipeline/sync/test_inplace', 'distributed/pipeline/sync/test_microbatch', 'distributed/pipeline/sync/test_phony', 'distributed/pipeline/sync/test_pipe', 'distributed/pipeline/sync/test_pipeline', 'distributed/pipeline/sync/test_stream', 'distributed/pipeline/sync/test_transparency', 'distributed/pipeline/sync/test_worker', 'distributed/optim/test_zero_redundancy_optimizer', 'distributed/elastic/timer/api_test', 'distributed/elastic/timer/local_timer_example', 'distributed/elastic/timer/local_timer_test', 'distributed/elastic/events/lib_test', 'distributed/elastic/metrics/api_test', 'distributed/elastic/utils/logging_test', 'distributed/elastic/utils/util_test', 'distributed/elastic/utils/distributed_test', 'distributed/elastic/multiprocessing/api_test', ] # Tests need to be run with pytest. USE_PYTEST_LIST = [ 'distributed/pipeline/sync/skip/test_api', 'distributed/pipeline/sync/skip/test_gpipe', 'distributed/pipeline/sync/skip/test_inspect_skip_layout', 'distributed/pipeline/sync/skip/test_leak', 'distributed/pipeline/sync/skip/test_portal', 'distributed/pipeline/sync/skip/test_stash_pop', 'distributed/pipeline/sync/skip/test_tracker', 'distributed/pipeline/sync/skip/test_verify_skippables', 'distributed/pipeline/sync/test_balance', 'distributed/pipeline/sync/test_bugs', 'distributed/pipeline/sync/test_checkpoint', 'distributed/pipeline/sync/test_copy', 'distributed/pipeline/sync/test_deferred_batch_norm', 'distributed/pipeline/sync/test_dependency', 'distributed/pipeline/sync/test_inplace', 'distributed/pipeline/sync/test_microbatch', 'distributed/pipeline/sync/test_phony', 'distributed/pipeline/sync/test_pipe', 'distributed/pipeline/sync/test_pipeline', 'distributed/pipeline/sync/test_stream', 'distributed/pipeline/sync/test_transparency', 'distributed/pipeline/sync/test_worker', 'distributions/test_constraints', 'distributions/test_transforms', 'distributions/test_utils', 'test_typing', "distributed/elastic/events/lib_test", "distributed/elastic/agent/server/test/api_test", ] WINDOWS_BLOCKLIST = [ 'distributed/nn/jit/test_instantiator', 'distributed/rpc/test_faulty_agent', 'distributed/rpc/test_process_group_agent', 'distributed/rpc/cuda/test_process_group_agent', 'distributed/rpc/test_tensorpipe_agent', 'distributed/rpc/cuda/test_tensorpipe_agent', 'distributed/test_distributed_fork', 'distributed/pipeline/sync/skip/test_api', 'distributed/pipeline/sync/skip/test_gpipe', 'distributed/pipeline/sync/skip/test_inspect_skip_layout', 'distributed/pipeline/sync/skip/test_leak', 'distributed/pipeline/sync/skip/test_portal', 'distributed/pipeline/sync/skip/test_stash_pop', 'distributed/pipeline/sync/skip/test_tracker', 'distributed/pipeline/sync/skip/test_verify_skippables', 'distributed/pipeline/sync/test_balance', 'distributed/pipeline/sync/test_bugs', 'distributed/pipeline/sync/test_checkpoint', 'distributed/pipeline/sync/test_copy', 'distributed/pipeline/sync/test_deferred_batch_norm', 'distributed/pipeline/sync/test_dependency', 'distributed/pipeline/sync/test_inplace', 'distributed/pipeline/sync/test_microbatch', 'distributed/pipeline/sync/test_phony', 'distributed/pipeline/sync/test_pipe', 'distributed/pipeline/sync/test_pipeline', 'distributed/pipeline/sync/test_stream', 'distributed/pipeline/sync/test_transparency', 'distributed/pipeline/sync/test_worker', 'distributed/optim/test_zero_redundancy_optimizer', "distributed/elastic/agent/server/test/api_test", 'distributed/elastic/multiprocessing/api_test', ] ROCM_BLOCKLIST = [ 'distributed/nn/jit/test_instantiator', 'distributed/rpc/test_faulty_agent', 'distributed/rpc/test_process_group_agent', 'distributed/rpc/cuda/test_process_group_agent', 'distributed/rpc/test_tensorpipe_agent', 'distributed/rpc/cuda/test_tensorpipe_agent', 'test_determination', 'test_multiprocessing', 'test_jit_legacy', 'test_type_hints', 'test_openmp', ] RUN_PARALLEL_BLOCKLIST = [ 'test_cpp_extensions_jit', 'test_expecttest', 'test_jit_disabled', 'test_mobile_optimizer', 'test_multiprocessing', 'test_multiprocessing_spawn', 'test_namedtuple_return_api', 'test_overrides', 'test_show_pickle', 'test_tensorexpr', 'test_cuda_primary_ctx', ] + [test for test in TESTS if test.startswith('distributed/')] WINDOWS_COVERAGE_BLOCKLIST = [ ] # These tests are slow enough that it's worth calculating whether the patch # touched any related files first. This list was manually generated, but for every # run with --determine-from, we use another generated list based on this one and the # previous test stats. TARGET_DET_LIST = [ 'distributions/test_distributions', 'test_nn', 'test_autograd', 'test_cpp_extensions_jit', 'test_jit_legacy', 'test_dataloader', 'test_overrides', 'test_linalg', 'test_jit', 'test_jit_profiling', 'test_torch', 'test_binary_ufuncs', 'test_numpy_interop', 'test_reductions', 'test_shape_ops', 'test_sort_and_select', 'test_testing', 'test_view_ops', 'distributed/nn/jit/test_instantiator', 'distributed/test_distributed_fork', 'distributed/rpc/test_process_group_agent', 'distributed/rpc/cuda/test_process_group_agent', 'distributed/rpc/test_tensorpipe_agent', 'distributed/rpc/cuda/test_tensorpipe_agent', 'distributed/algorithms/ddp_comm_hooks/test_ddp_hooks', 'distributed/test_distributed_spawn', 'test_cuda', 'test_cuda_primary_ctx', 'test_cpp_extensions_aot_ninja', 'test_cpp_extensions_aot_no_ninja', 'test_serialization', 'test_optim', 'test_utils', 'test_multiprocessing', 'test_tensorboard', 'distributed/test_c10d_common', 'distributed/test_c10d_gloo', 'distributed/test_c10d_nccl', 'distributed/test_jit_c10d', 'distributed/test_c10d_spawn_gloo', 'distributed/test_c10d_spawn_nccl', 'test_quantization', 'test_pruning_op', 'test_determination', 'test_futures', 'distributed/pipeline/sync/skip/test_api', 'distributed/pipeline/sync/skip/test_gpipe', 'distributed/pipeline/sync/skip/test_inspect_skip_layout', 'distributed/pipeline/sync/skip/test_leak', 'distributed/pipeline/sync/skip/test_portal', 'distributed/pipeline/sync/skip/test_stash_pop', 'distributed/pipeline/sync/skip/test_tracker', 'distributed/pipeline/sync/skip/test_verify_skippables', 'distributed/pipeline/sync/test_balance', 'distributed/pipeline/sync/test_bugs', 'distributed/pipeline/sync/test_checkpoint', 'distributed/pipeline/sync/test_copy', 'distributed/pipeline/sync/test_deferred_batch_norm', 'distributed/pipeline/sync/test_dependency', 'distributed/pipeline/sync/test_inplace', 'distributed/pipeline/sync/test_microbatch', 'distributed/pipeline/sync/test_phony', 'distributed/pipeline/sync/test_pipe', 'distributed/pipeline/sync/test_pipeline', 'distributed/pipeline/sync/test_stream', 'distributed/pipeline/sync/test_transparency', 'distributed/pipeline/sync/test_worker', ] # the JSON file to store the S3 test stats TEST_TIMES_FILE = '.pytorch-test-times' # if a test file takes longer than 5 min, we add it to TARGET_DET_LIST SLOW_TEST_THRESHOLD = 300 _DEP_MODULES_CACHE: Dict[str, set] = {} DISTRIBUTED_TESTS_CONFIG = {} if dist.is_available(): DISTRIBUTED_TESTS_CONFIG['test'] = { 'WORLD_SIZE': '1' } if not TEST_WITH_ROCM and dist.is_mpi_available(): DISTRIBUTED_TESTS_CONFIG['mpi'] = { 'WORLD_SIZE': '3', 'TEST_REPORT_SOURCE_OVERRIDE': 'dist-mpi' } if dist.is_nccl_available(): DISTRIBUTED_TESTS_CONFIG['nccl'] = { 'WORLD_SIZE': '2' if torch.cuda.device_count() == 2 else '3', 'TEST_REPORT_SOURCE_OVERRIDE': 'dist-nccl' } if dist.is_gloo_available(): DISTRIBUTED_TESTS_CONFIG['gloo'] = { 'WORLD_SIZE': '2' if torch.cuda.device_count() == 2 else '3', 'TEST_REPORT_SOURCE_OVERRIDE': 'dist-gloo' } # https://stackoverflow.com/questions/2549939/get-signal-names-from-numbers-in-python SIGNALS_TO_NAMES_DICT = {getattr(signal, n): n for n in dir(signal) if n.startswith('SIG') and '_' not in n} CPP_EXTENSIONS_ERROR = """ Ninja (https://ninja-build.org) is required for some of the C++ extensions tests, but it could not be found. Install ninja with `pip install ninja` or `conda install ninja`. Alternatively, disable said tests with `run_test.py --exclude test_cpp_extensions_aot_ninja test_cpp_extensions_jit`. """ PYTORCH_COLLECT_COVERAGE = bool(os.environ.get("PYTORCH_COLLECT_COVERAGE")) JIT_EXECUTOR_TESTS = [ 'test_jit_cuda_fuser', 'test_jit_profiling', 'test_jit_legacy', 'test_jit_fuser_legacy', ] def print_to_stderr(message): print(message, file=sys.stderr) # Convert something like pytorch_windows_vs2019_py36_cuda10.1_build to pytorch_windows_vs2019_py36_cuda10.1 def get_stripped_CI_job() -> str: job = os.environ.get("CIRCLE_JOB", "").rstrip('0123456789') if job.endswith('_slow_test'): job = job[:len(job) - len('_slow_test')] elif job.endswith('_test'): job = job[:len(job) - len('_test')] elif job.endswith('_build'): job = job[:len(job) - len('_build')] return job def calculate_job_times(reports: List["Report"]) -> Dict[str, float]: # an entry will be like ("test_file_name" -> (current_avg, # values)) jobs_to_times: Dict[str, Tuple[float, int]] = dict() for report in reports: assert report.get('format_version') == 2, "S3 format currently handled is version 2 only" files: Dict[str, Any] = report['files'] for name, test_file in files.items(): if name not in jobs_to_times: jobs_to_times[name] = (test_file['total_seconds'], 1) else: curr_avg, curr_count = jobs_to_times[name] new_count = curr_count + 1 new_avg = (curr_avg * curr_count + test_file['total_seconds']) / new_count jobs_to_times[name] = (new_avg, new_count) # if there's 'test_cpp_extensions_aot' entry in jobs_to_times, add 'test_cpp_extensions_aot_ninja' # and 'test_cpp_extensions_aot_no_ninja' duplicate entries to ease future computation since # test_cpp_extensions_aot_no_ninja and test_cpp_extensions_aot_ninja are Python test jobs that # both use the test_cpp_extensions_aot.py file. if 'test_cpp_extensions_aot' in jobs_to_times: jobs_to_times['test_cpp_extensions_aot_ninja'] = jobs_to_times['test_cpp_extensions_aot'] jobs_to_times['test_cpp_extensions_aot_no_ninja'] = jobs_to_times['test_cpp_extensions_aot'] return {job: time for job, (time, _) in jobs_to_times.items()} def pull_job_times_from_S3() -> Dict[str, float]: if HAVE_BOTO3: ci_job_prefix = get_stripped_CI_job() s3_reports: List["Report"] = get_previous_reports_for_branch('origin/nightly', ci_job_prefix) else: print('Uh oh, boto3 is not found. Either it is not installed or we failed to import s3_stat_parser.') print('If not installed, please install boto3 for automatic sharding and test categorization.') s3_reports = [] if len(s3_reports) == 0: print('Gathered no reports from S3. Please proceed without them.') return dict() return calculate_job_times(s3_reports) def get_past_job_times() -> Dict[str, float]: if os.path.exists(TEST_TIMES_FILE): with open(TEST_TIMES_FILE) as file: test_times_json: JobTimeJSON = json.load(file) curr_commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], encoding="ascii").strip() file_commit = test_times_json.get('commit', '') curr_ci_job = get_stripped_CI_job() file_ci_job = test_times_json.get('CIRCLE_JOB', 'N/A') if curr_commit != file_commit: print(f'Current test times file is from different commit {file_commit}.') elif curr_ci_job != file_ci_job: print(f'Current test times file is for different CI job {file_ci_job}.') else: print(f'Found stats for current commit: {curr_commit} and job: {curr_ci_job}. Proceeding with those values.') return test_times_json.get('job_times', {}) # Found file, but commit or CI job in JSON doesn't match print(f'Overwriting current file with stats based on current commit: {curr_commit} and CI job: {curr_ci_job}') job_times = pull_job_times_from_S3() print(f'Exporting S3 test stats to {TEST_TIMES_FILE}.') export_S3_test_times(TEST_TIMES_FILE, job_times) return job_times class JobTimeJSON(TypedDict): commit: str job_times: Dict[str, float] def get_job_times_json(job_times: Dict[str, float]) -> JobTimeJSON: return { 'commit': subprocess.check_output(['git', 'rev-parse', 'HEAD'], encoding="ascii").strip(), 'CIRCLE_JOB': get_stripped_CI_job(), 'job_times': job_times, } def get_shard(which_shard: int, num_shards: int, tests: List[str]) -> List[str]: jobs_to_times = get_past_job_times() # Got no stats from S3, returning early to save runtime if len(jobs_to_times) == 0: print('Gathered no stats from S3. Proceeding with default sharding plan.') return tests[which_shard - 1 :: num_shards] shards = calculate_shards(num_shards, tests, jobs_to_times) _, tests_from_shard = shards[which_shard - 1] return tests_from_shard def get_slow_tests_based_on_S3() -> List[str]: jobs_to_times: Dict[str, float] = get_past_job_times() # Got no stats from S3, returning early to save runtime if len(jobs_to_times) == 0: print('Gathered no stats from S3. No new slow tests calculated.') return [] slow_tests: List[str] = [] for test in TESTS: if test in jobs_to_times and test not in TARGET_DET_LIST: if jobs_to_times[test] > SLOW_TEST_THRESHOLD: slow_tests.append(test) return slow_tests def get_executable_command(options, allow_pytest, disable_coverage=False): if options.coverage and not disable_coverage: executable = ['coverage', 'run', '--parallel-mode', '--source=torch'] else: executable = [sys.executable] if options.pytest: if allow_pytest: executable += ['-m', 'pytest'] else: print_to_stderr('Pytest cannot be used for this test. Falling back to unittest.') return executable def run_test(test_module, test_directory, options, launcher_cmd=None, extra_unittest_args=None): unittest_args = options.additional_unittest_args.copy() if options.verbose: unittest_args.append(f'-{"v"*options.verbose}') # in case of pytest if test_module in RUN_PARALLEL_BLOCKLIST: unittest_args = [arg for arg in unittest_args if not arg.startswith('--run-parallel')] if extra_unittest_args: assert isinstance(extra_unittest_args, list) unittest_args.extend(extra_unittest_args) # If using pytest, replace -f with equivalent -x if options.pytest: unittest_args = [arg if arg != '-f' else '-x' for arg in unittest_args] # Can't call `python -m unittest test_*` here because it doesn't run code # in `if __name__ == '__main__': `. So call `python test_*.py` instead. argv = [test_module + '.py'] + unittest_args # Multiprocessing related tests cannot run with coverage. # Tracking issue: https://github.com/pytorch/pytorch/issues/50661 disable_coverage = sys.platform == 'win32' and test_module in WINDOWS_COVERAGE_BLOCKLIST # Extra arguments are not supported with pytest executable = get_executable_command(options, allow_pytest=not extra_unittest_args, disable_coverage=disable_coverage) command = (launcher_cmd or []) + executable + argv print_to_stderr('Executing {} ... [{}]'.format(command, datetime.now())) return shell(command, test_directory) def test_cuda_primary_ctx(test_module, test_directory, options): return run_test(test_module, test_directory, options, extra_unittest_args=['--subprocess']) def _test_cpp_extensions_aot(test_module, test_directory, options, use_ninja): if use_ninja: try: cpp_extension.verify_ninja_availability() except RuntimeError: print(CPP_EXTENSIONS_ERROR) return 1 # Wipe the build folder, if it exists already cpp_extensions_test_dir = os.path.join(test_directory, 'cpp_extensions') cpp_extensions_test_build_dir = os.path.join(cpp_extensions_test_dir, 'build') if os.path.exists(cpp_extensions_test_build_dir): shutil.rmtree(cpp_extensions_test_build_dir) # Build the test cpp extensions modules shell_env = os.environ.copy() shell_env['USE_NINJA'] = str(1 if use_ninja else 0) cmd = [sys.executable, 'setup.py', 'install', '--root', './install'] return_code = shell(cmd, cwd=cpp_extensions_test_dir, env=shell_env) if return_code != 0: return return_code if sys.platform != 'win32': return_code = shell(cmd, cwd=os.path.join(cpp_extensions_test_dir, 'no_python_abi_suffix_test'), env=shell_env) if return_code != 0: return return_code # "install" the test modules and run tests python_path = os.environ.get('PYTHONPATH', '') try: cpp_extensions = os.path.join(test_directory, 'cpp_extensions') install_directory = '' # install directory is the one that is named site-packages for root, directories, _ in os.walk(os.path.join(cpp_extensions, 'install')): for directory in directories: if '-packages' in directory: install_directory = os.path.join(root, directory) assert install_directory, 'install_directory must not be empty' os.environ['PYTHONPATH'] = os.pathsep.join([install_directory, python_path]) return run_test(test_module, test_directory, options) finally: os.environ['PYTHONPATH'] = python_path def test_cpp_extensions_aot_ninja(test_module, test_directory, options): return _test_cpp_extensions_aot('test_cpp_extensions_aot', test_directory, options, use_ninja=True) def test_cpp_extensions_aot_no_ninja(test_module, test_directory, options): return _test_cpp_extensions_aot('test_cpp_extensions_aot', test_directory, options, use_ninja=False) def test_distributed(test_module, test_directory, options): # MPI tests are broken with Python-3.9 mpi_available = subprocess.call('command -v mpiexec', shell=True) == 0 and sys.version_info < (3, 9) if options.verbose and not mpi_available: print_to_stderr( 'MPI not available -- MPI backend tests will be skipped') config = DISTRIBUTED_TESTS_CONFIG for backend, env_vars in config.items(): if sys.platform == 'win32' and backend != 'gloo': continue if backend == 'mpi' and not mpi_available: continue for with_init_file in {True, False}: if sys.platform == 'win32' and not with_init_file: continue tmp_dir = tempfile.mkdtemp() if options.verbose: init_str = "with {} init_method" with_init = init_str.format("file" if with_init_file else "env") print_to_stderr( 'Running distributed tests for the {} backend {}'.format( backend, with_init)) os.environ['TEMP_DIR'] = tmp_dir os.environ['BACKEND'] = backend os.environ['INIT_METHOD'] = 'env://' os.environ.update(env_vars) if with_init_file: if test_module in ["test_distributed_fork", "test_distributed_spawn"]: init_method = f'{FILE_SCHEMA}{tmp_dir}/' else: init_method = f'{FILE_SCHEMA}{tmp_dir}/shared_init_file' os.environ['INIT_METHOD'] = init_method try: os.mkdir(os.path.join(tmp_dir, 'barrier')) os.mkdir(os.path.join(tmp_dir, 'test_dir')) if backend == 'mpi': # test mpiexec for --noprefix option with open(os.devnull, 'w') as devnull: allowrunasroot_opt = '--allow-run-as-root' if subprocess.call( 'mpiexec --allow-run-as-root -n 1 bash -c ""', shell=True, stdout=devnull, stderr=subprocess.STDOUT) == 0 else '' noprefix_opt = '--noprefix' if subprocess.call( f'mpiexec {allowrunasroot_opt} -n 1 --noprefix bash -c ""', shell=True, stdout=devnull, stderr=subprocess.STDOUT) == 0 else '' mpiexec = ['mpiexec', '-n', '3', noprefix_opt, allowrunasroot_opt] return_code = run_test(test_module, test_directory, options, launcher_cmd=mpiexec) else: return_code = run_test(test_module, test_directory, options) if return_code != 0: return return_code finally: shutil.rmtree(tmp_dir) return 0 CUSTOM_HANDLERS = { 'test_cuda_primary_ctx': test_cuda_primary_ctx, 'test_cpp_extensions_aot_no_ninja': test_cpp_extensions_aot_no_ninja, 'test_cpp_extensions_aot_ninja': test_cpp_extensions_aot_ninja, 'distributed/test_distributed_fork': test_distributed, 'distributed/test_distributed_spawn': test_distributed, } def parse_test_module(test): return test.split('.')[0] class TestChoices(list): def __init__(self, *args, **kwargs): super(TestChoices, self).__init__(args[0]) def __contains__(self, item): return list.__contains__(self, parse_test_module(item)) def parse_args(): parser = argparse.ArgumentParser( description='Run the PyTorch unit test suite', epilog='where TESTS is any of: {}'.format(', '.join(TESTS))) parser.add_argument( '-v', '--verbose', action='count', default=0, help='print verbose information and test-by-test results') parser.add_argument( '--jit', '--jit', action='store_true', help='run all jit tests') parser.add_argument( '-pt', '--pytest', action='store_true', help='If true, use `pytest` to execute the tests. E.g., this runs ' 'TestTorch with pytest in verbose and coverage mode: ' 'python run_test.py -vci torch -pt') parser.add_argument( '-c', '--coverage', action='store_true', help='enable coverage', default=PYTORCH_COLLECT_COVERAGE) parser.add_argument( '-i', '--include', nargs='+', choices=TestChoices(TESTS), default=TESTS, metavar='TESTS', help='select a set of tests to include (defaults to ALL tests).' ' tests can be specified with module name, module.TestClass' ' or module.TestClass.test_method') parser.add_argument( '-x', '--exclude', nargs='+', choices=TESTS, metavar='TESTS', default=[], help='select a set of tests to exclude') parser.add_argument( '-f', '--first', choices=TESTS, metavar='TESTS', help='select the test to start from (excludes previous tests)') parser.add_argument( '-l', '--last', choices=TESTS, metavar='TESTS', help='select the last test to run (excludes following tests)') parser.add_argument( '--bring-to-front', nargs='+', choices=TestChoices(TESTS), default=[], metavar='TESTS', help='select a set of tests to run first. This can be used in situations' ' where you want to run all tests, but care more about some set, ' 'e.g. after making a change to a specific component') parser.add_argument( '--ignore-win-blocklist', action='store_true', help='always run blocklisted windows tests') parser.add_argument( '--determine-from', help='File of affected source filenames to determine which tests to run.') parser.add_argument( '--continue-through-error', action='store_true', help='Runs the full test suite despite one of the tests failing') parser.add_argument( 'additional_unittest_args', nargs='*', help='additional arguments passed through to unittest, e.g., ' 'python run_test.py -i sparse -- TestSparse.test_factory_size_check') parser.add_argument( '--export-past-test-times', nargs='?', type=str, const=TEST_TIMES_FILE, help='dumps test times from previous S3 stats into a file, format JSON', ) parser.add_argument( '--shard', nargs=2, type=int, help='runs a shard of the tests (taking into account other selections), e.g., ' '--shard 2 3 will break up the selected tests into 3 shards and run the tests ' 'in the 2nd shard (the first number should not exceed the second)', ) parser.add_argument( '--exclude-jit-executor', action='store_true', help='exclude tests that are run for a specific jit config' ) return parser.parse_args() def find_test_index(test, selected_tests, find_last_index=False): """Find the index of the first or last occurrence of a given test/test module in the list of selected tests. This function is used to determine the indices when slicing the list of selected tests when ``options.first``(:attr:`find_last_index`=False) and/or ``options.last``(:attr:`find_last_index`=True) are used. :attr:`selected_tests` can be a list that contains multiple consequent occurrences of tests as part of the same test module, e.g.: ``` selected_tests = ['autograd', 'cuda', **'torch.TestTorch.test_acos', 'torch.TestTorch.test_tan', 'torch.TestTorch.test_add'**, 'utils'] ``` If :attr:`test`='torch' and :attr:`find_last_index`=False, result should be **2**. If :attr:`test`='torch' and :attr:`find_last_index`=True, result should be **4**. Args: test (str): Name of test to lookup selected_tests (list): List of tests find_last_index (bool, optional): should we lookup the index of first or last occurrence (first is default) Returns: index of the first or last occurrence of the given test """ idx = 0 found_idx = -1 for t in selected_tests: if t.startswith(test): found_idx = idx if not find_last_index: break idx += 1 return found_idx def exclude_tests(exclude_list, selected_tests, exclude_message=None): for exclude_test in exclude_list: tests_copy = selected_tests[:] for test in tests_copy: if test.startswith(exclude_test): if exclude_message is not None: print_to_stderr('Excluding {} {}'.format(test, exclude_message)) selected_tests.remove(test) return selected_tests def get_selected_tests(options): selected_tests = options.include if options.bring_to_front: to_front = set(options.bring_to_front) selected_tests = options.bring_to_front + list(filter(lambda name: name not in to_front, selected_tests)) if options.first: first_index = find_test_index(options.first, selected_tests) selected_tests = selected_tests[first_index:] if options.last: last_index = find_test_index(options.last, selected_tests, find_last_index=True) selected_tests = selected_tests[:last_index + 1] if options.shard: assert len(options.shard) == 2, "Unexpected shard format" assert min(options.shard) > 0, "Shards must be positive numbers" which_shard, num_shards = options.shard assert which_shard <= num_shards, "Selected shard must be less or equal that total number of shards" assert num_shards <= len(selected_tests), f"Number of shards must be less than {len(selected_tests)}" selected_tests = get_shard(which_shard, num_shards, selected_tests) if options.exclude_jit_executor: options.exclude.extend(JIT_EXECUTOR_TESTS) selected_tests = exclude_tests(options.exclude, selected_tests) if sys.platform == 'win32' and not options.ignore_win_blocklist: target_arch = os.environ.get('VSCMD_ARG_TGT_ARCH') if target_arch != 'x64': WINDOWS_BLOCKLIST.append('cpp_extensions_aot_no_ninja') WINDOWS_BLOCKLIST.append('cpp_extensions_aot_ninja') WINDOWS_BLOCKLIST.append('cpp_extensions_jit') WINDOWS_BLOCKLIST.append('jit') WINDOWS_BLOCKLIST.append('jit_fuser') selected_tests = exclude_tests(WINDOWS_BLOCKLIST, selected_tests, 'on Windows') elif TEST_WITH_ROCM: selected_tests = exclude_tests(ROCM_BLOCKLIST, selected_tests, 'on ROCm') return selected_tests def test_impact_of_file(filename): """Determine what class of impact this file has on test runs. Possible values: TORCH - torch python code CAFFE2 - caffe2 python code TEST - torch test code UNKNOWN - may affect all tests NONE - known to have no effect on test outcome CI - CI configuration files """ parts = filename.split(os.sep) if parts[0] in ['.jenkins', '.circleci']: return 'CI' if parts[0] in ['docs', 'scripts', 'CODEOWNERS', 'README.md']: return 'NONE' elif parts[0] == 'torch': if parts[-1].endswith('.py') or parts[-1].endswith('.pyi'): return 'TORCH' elif parts[0] == 'caffe2': if parts[-1].endswith('.py') or parts[-1].endswith('.pyi'): return 'CAFFE2' elif parts[0] == 'test': if parts[-1].endswith('.py') or parts[-1].endswith('.pyi'): return 'TEST' return 'UNKNOWN' def log_test_reason(file_type, filename, test, options): if options.verbose: print_to_stderr( 'Determination found {} file {} -- running {}'.format( file_type, filename, test, ) ) def get_dep_modules(test): # Cache results in case of repetition if test in _DEP_MODULES_CACHE: return _DEP_MODULES_CACHE[test] repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) test_location = os.path.join(repo_root, 'test', test + '.py') finder = modulefinder.ModuleFinder( # Ideally exclude all third party modules, to speed up calculation. excludes=[ 'scipy', 'numpy', 'numba', 'multiprocessing', 'sklearn', 'setuptools', 'hypothesis', 'llvmlite', 'joblib', 'email', 'importlib', 'unittest', 'urllib', 'json', 'collections', # Modules below are excluded because they are hitting https://bugs.python.org/issue40350 # Trigger AttributeError: 'NoneType' object has no attribute 'is_package' 'mpl_toolkits', 'google', 'onnx', # Triggers RecursionError 'mypy' ], ) # HACK: some platforms default to ascii, so we can't just run_script :( with open(test_location, 'r', encoding='utf-8') as fp: finder.load_module('__main__', fp, test_location, ('', 'r', 1)) dep_modules = set(finder.modules.keys()) _DEP_MODULES_CACHE[test] = dep_modules return dep_modules def determine_target(target_det_list, test, touched_files, options): test = parse_test_module(test) # Some tests are faster to execute than to determine. if test not in target_det_list: if options.verbose: print_to_stderr(f'Running {test} without determination') return True # HACK: "no_ninja" is not a real module if test.endswith('_no_ninja'): test = test[:(-1 * len('_no_ninja'))] if test.endswith('_ninja'): test = test[:(-1 * len('_ninja'))] dep_modules = get_dep_modules(test) for touched_file in touched_files: file_type = test_impact_of_file(touched_file) if file_type == 'NONE': continue elif file_type == 'CI': # Force all tests to run if any change is made to the CI # configurations. log_test_reason(file_type, touched_file, test, options) return True elif file_type == 'UNKNOWN': # Assume uncategorized source files can affect every test. log_test_reason(file_type, touched_file, test, options) return True elif file_type in ['TORCH', 'CAFFE2', 'TEST']: parts = os.path.splitext(touched_file)[0].split(os.sep) touched_module = ".".join(parts) # test/ path does not have a "test." namespace if touched_module.startswith('test.'): touched_module = touched_module.split('test.')[1] if ( touched_module in dep_modules or touched_module == test.replace('/', '.') ): log_test_reason(file_type, touched_file, test, options) return True # If nothing has determined the test has run, don't run the test. if options.verbose: print_to_stderr(f'Determination is skipping {test}') return False def run_test_module(test: str, test_directory: str, options) -> Optional[str]: test_module = parse_test_module(test) # Printing the date here can help diagnose which tests are slow print_to_stderr('Running {} ... [{}]'.format(test, datetime.now())) handler = CUSTOM_HANDLERS.get(test_module, run_test) return_code = handler(test_module, test_directory, options) assert isinstance(return_code, int) and not isinstance( return_code, bool), 'Return code should be an integer' if return_code == 0: return None message = f'{test} failed!' if return_code < 0: # subprocess.Popen returns the child process' exit signal as # return code -N, where N is the signal number. signal_name = SIGNALS_TO_NAMES_DICT[-return_code] message += f' Received signal: {signal_name}' return message def export_S3_test_times(test_times_filename: str, test_times: Dict[str, float]) -> None: if os.path.exists(test_times_filename): print(f'Overwriting existent file: {test_times_filename}') with open(test_times_filename, 'w+') as file: job_times_json = get_job_times_json(test_times) json.dump(job_times_json, file, indent=' ', separators=(',', ': ')) file.write('\n') def query_changed_test_files() -> List[str]: cmd = ["git", "diff", "--name-only", "origin/master", "HEAD"] proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if proc.returncode != 0: raise RuntimeError("Unable to get changed files") lines = proc.stdout.decode().strip().split("\n") lines = [line.strip() for line in lines] return lines def reorder_tests(tests: List[str]) -> List[str]: try: changed_files = query_changed_test_files() except Exception: # If unable to get changed files from git, quit without doing any sorting return tests prefix = f"test{os.path.sep}" changed_tests = [f for f in changed_files if f.startswith(prefix) and f.endswith(".py")] changed_tests = [f[len(prefix):] for f in changed_tests] changed_tests = [f[:-len(".py")] for f in changed_tests] bring_to_front = [] the_rest = [] for test in tests: if test in changed_tests: bring_to_front.append(test) else: the_rest.append(test) sorted_tests = bring_to_front + the_rest if len(sorted_tests) != len(tests): # Something went wrong, bail out without doing any sorting return tests return sorted_tests def main(): options = parse_args() test_times_filename = options.export_past_test_times if test_times_filename: print(f'Exporting past test times from S3 to {test_times_filename}, no tests will be run.') export_S3_test_times(test_times_filename, pull_job_times_from_S3()) return test_directory = os.path.dirname(os.path.abspath(__file__)) selected_tests = get_selected_tests(options) if options.verbose: print_to_stderr('Selected tests: {}'.format(', '.join(selected_tests))) if options.coverage and not PYTORCH_COLLECT_COVERAGE: shell(['coverage', 'erase']) if options.jit: selected_tests = filter(lambda test_name: "jit" in test_name, TESTS) if options.determine_from is not None and os.path.exists(options.determine_from): slow_tests = get_slow_tests_based_on_S3() print('Added the following tests to target_det tests as calculated based on S3:') print(slow_tests) with open(options.determine_from, 'r') as fh: touched_files = [ os.path.normpath(name.strip()) for name in fh.read().split('\n') if len(name.strip()) > 0 ] # HACK: Ensure the 'test' paths can be traversed by Modulefinder sys.path.append('test') selected_tests = [ test for test in selected_tests if determine_target(TARGET_DET_LIST + slow_tests, test, touched_files, options) ] sys.path.remove('test') selected_tests = reorder_tests(selected_tests) has_failed = False failure_messages = [] try: for test in selected_tests: options_clone = copy.deepcopy(options) if test in USE_PYTEST_LIST: options_clone.pytest = True err_message = run_test_module(test, test_directory, options_clone) if err_message is None: continue has_failed = True failure_messages.append(err_message) if not options_clone.continue_through_error: raise RuntimeError(err_message) print_to_stderr(err_message) finally: if options.coverage: from coverage import Coverage test_dir = os.path.dirname(os.path.abspath(__file__)) with set_cwd(test_dir): cov = Coverage() if PYTORCH_COLLECT_COVERAGE: cov.load() cov.combine(strict=False) cov.save() if not PYTORCH_COLLECT_COVERAGE: cov.html_report() if options.continue_through_error and has_failed: for err in failure_messages: print_to_stderr(err) sys.exit(1) if __name__ == '__main__': main()
""" # # 26/08/2018 # Oladotun Rominiyi - Copyright © 2018. all rights reserved. """ __author__ = 'dotun rominiyi' # IMPORTS import ujson import ssl import websockets from base64 import b64decode from zlib import decompress, MAX_WBITS from signalr_aio.transports import Transport as SignalRTransport from signalr_aio import Connection as SignalRConnection from cosine.core.proc_workers import CosineProcEventWorker from cosine.venues.base_venue import AsyncEvents from cosine.venues.bem.types import ( BlockExMarketsAsyncOrder, BlockExMarketsAsyncExecution, BlockExMarketsAsyncCancelOrderResponse, BlockExMarketsAsyncCancelAllResponse ) # MODULE FUNCTIONS setattr(SignalRConnection, 'last_send_id', property(lambda self: self._Connection__send_counter)) # MODULE CLASSES class BlockExMarketsSignalRWorker(CosineProcEventWorker): def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): super().__init__(group, target, name, args, kwargs) self._hub = None self._connection = None self._invoke_handling = {} self.events.OnPlaceOrder = CosineProcEventWorker.EventSlot() self.events.OnExecution = CosineProcEventWorker.EventSlot() self.events.OnCancelOrder = CosineProcEventWorker.EventSlot() self.events.OnCancelAllOrders = CosineProcEventWorker.EventSlot() self.events.OnLatestBids = CosineProcEventWorker.EventSlot() self.events.OnLatestAsks = CosineProcEventWorker.EventSlot() self.events.OnMarketTick = CosineProcEventWorker.EventSlot() self.events.OnError = CosineProcEventWorker.EventSlot() """Worker process websockets setup""" def _setup_websockets_ssl_certs(self): cert_file = self.kwargs["CertFile"] context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) context.load_verify_locations(cert_file) # monkeypatch the transport to let us connect via a custom SSLContext async def socket(this, loop): async with websockets.connect( this._ws_params.socket_url, extra_headers=this._ws_params.headers, loop=loop, ssl=context ) as this.ws: this._connection.started = True await this.handler(this.ws) SignalRTransport.socket = socket """Worker process setup""" def run(self): # setup SSL context construction if required if self.kwargs["CertFile"]: self._setup_websockets_ssl_certs() # setup SignalR connection (w/ authentication) connection = SignalRConnection(f"{self.kwargs["APIDomain"]}/signalr", session=None) connection.qs = {'access_token': self.kwargs['access_token']} hub = connection.register_hub('TradingHub') self._hub = hub self._connection = connection # Set event handlers hub.client.on('MarketTradesRefreshed', lambda x: None) hub.client.on('MarketOrdersRefreshed', self.on_market_tick_received) hub.client.on('tradeCreated', self.on_execution_received) hub.client.on('createTradeOrderResult', self.on_place_order_received) hub.client.on('cancelTradeOrderResult', self.on_cancel_order_received) hub.client.on('cancelAllTradeOrdersResult', self.on_cancel_all_orders_received) connection.received += self.on_raw_msg_received connection.error += self.on_error_received connection.start() pass """Worker process teardown""" def join(self, timeout=None): if self._connection: self._connection.close() """Worker process raw message processors""" @staticmethod def process_compact_raw_msg(raw_msg): deflated_msg = decompress(b64decode(raw_msg), -MAX_WBITS) return ujson.loads(deflated_msg.decode()) @staticmethod def process_raw_msg(raw_msg): return ujson.loads(raw_msg) """Worker process server invocation handling""" def invoke(self, method, *data, callback=None): inv_id = self._connection.last_send_id + 1 self._invoke_handling[inv_id] = {"cb": callback, "a": (method, data)} self._hub.server.invoke(method, *data) return inv_id """Worker process raw message received""" async def on_raw_msg_received(self, **msg): if not ('I' in msg): return inv_id = msg['I'] h = self._invoke_handling.get(inv_id) if h: if 'R' in msg and type(msg['R']) is not bool: msg = BlockExMarketsSignalRWorker.process_raw_msg(msg['R']) h["cb"](msg, h["a"]) """Worker process error received""" async def on_error_received(self, **msg): self.enqueue_event(AsyncEvents.OnError, msg) """Worker process market tick received""" async def on_market_tick_received(self, msg): self.invoke("getBids", self.kwargs['APIID'], msg[0]['instrumentID'], callback=self.on_bids_received) """Worker process market tick received""" async def on_bids_received(self, bids_msg, req): (_, msg) = req bids_msg['instrumentID'] = msg[0]['instrumentID'] self.enqueue_event('OnLatestBids', bids_msg) self.invoke("getAsks", self.kwargs['APIID'], msg[0]['instrumentID'], callback=self.on_asks_received) """Worker process market tick received""" async def on_asks_received(self, asks_msg, req): (_, msg) = req asks_msg['instrumentID'] = msg[0]['instrumentID'] self.enqueue_event('OnLatestAsks', asks_msg) """Worker process place order response received""" async def on_place_order_received(self, msg): self.enqueue_event(AsyncEvents.OnPlaceOrder, BlockExMarketsAsyncOrder(signalr_msg=msg)) """Worker process place order response received""" async def on_execution_received(self, msg): self.enqueue_event(AsyncEvents.OnExecution, BlockExMarketsAsyncExecution(signalr_msg=msg)) """Worker process cancel order response received""" async def on_cancel_order_received(self, msg): self.enqueue_event(AsyncEvents.OnCancelOrder, BlockExMarketsAsyncCancelOrderResponse(signalr_msg=msg)) """Worker process cancel all response received""" async def on_cancel_all_orders_received(self, msg): self.enqueue_event(AsyncEvents.OnCancelAllOrders, BlockExMarketsAsyncCancelAllResponse(signalr_msg=msg))
""" # # 26/08/2018 # Oladotun Rominiyi - Copyright © 2018. all rights reserved. """ __author__ = 'dotun rominiyi' # IMPORTS import ujson import ssl import websockets from base64 import b64decode from zlib import decompress, MAX_WBITS from signalr_aio.transports import Transport as SignalRTransport from signalr_aio import Connection as SignalRConnection from cosine.core.proc_workers import CosineProcEventWorker from cosine.venues.base_venue import AsyncEvents from cosine.venues.bem.types import ( BlockExMarketsAsyncOrder, BlockExMarketsAsyncExecution, BlockExMarketsAsyncCancelOrderResponse, BlockExMarketsAsyncCancelAllResponse ) # MODULE FUNCTIONS setattr(SignalRConnection, 'last_send_id', property(lambda self: self._Connection__send_counter)) # MODULE CLASSES class BlockExMarketsSignalRWorker(CosineProcEventWorker): def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): super().__init__(group, target, name, args, kwargs) self._hub = None self._connection = None self._invoke_handling = {} self.events.OnPlaceOrder = CosineProcEventWorker.EventSlot() self.events.OnExecution = CosineProcEventWorker.EventSlot() self.events.OnCancelOrder = CosineProcEventWorker.EventSlot() self.events.OnCancelAllOrders = CosineProcEventWorker.EventSlot() self.events.OnLatestBids = CosineProcEventWorker.EventSlot() self.events.OnLatestAsks = CosineProcEventWorker.EventSlot() self.events.OnMarketTick = CosineProcEventWorker.EventSlot() self.events.OnError = CosineProcEventWorker.EventSlot() """Worker process websockets setup""" def _setup_websockets_ssl_certs(self): cert_file = self.kwargs["CertFile"] context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) context.load_verify_locations(cert_file) # monkeypatch the transport to let us connect via a custom SSLContext async def socket(this, loop): async with websockets.connect( this._ws_params.socket_url, extra_headers=this._ws_params.headers, loop=loop, ssl=context ) as this.ws: this._connection.started = True await this.handler(this.ws) SignalRTransport.socket = socket """Worker process setup""" def run(self): # setup SSL context construction if required if self.kwargs["CertFile"]: self._setup_websockets_ssl_certs() # setup SignalR connection (w/ authentication) connection = SignalRConnection(f"{self.kwargs['APIDomain']}/signalr", session=None) connection.qs = {'access_token': self.kwargs['access_token']} hub = connection.register_hub('TradingHub') self._hub = hub self._connection = connection # Set event handlers hub.client.on('MarketTradesRefreshed', lambda x: None) hub.client.on('MarketOrdersRefreshed', self.on_market_tick_received) hub.client.on('tradeCreated', self.on_execution_received) hub.client.on('createTradeOrderResult', self.on_place_order_received) hub.client.on('cancelTradeOrderResult', self.on_cancel_order_received) hub.client.on('cancelAllTradeOrdersResult', self.on_cancel_all_orders_received) connection.received += self.on_raw_msg_received connection.error += self.on_error_received connection.start() pass """Worker process teardown""" def join(self, timeout=None): if self._connection: self._connection.close() """Worker process raw message processors""" @staticmethod def process_compact_raw_msg(raw_msg): deflated_msg = decompress(b64decode(raw_msg), -MAX_WBITS) return ujson.loads(deflated_msg.decode()) @staticmethod def process_raw_msg(raw_msg): return ujson.loads(raw_msg) """Worker process server invocation handling""" def invoke(self, method, *data, callback=None): inv_id = self._connection.last_send_id + 1 self._invoke_handling[inv_id] = {"cb": callback, "a": (method, data)} self._hub.server.invoke(method, *data) return inv_id """Worker process raw message received""" async def on_raw_msg_received(self, **msg): if not ('I' in msg): return inv_id = msg['I'] h = self._invoke_handling.get(inv_id) if h: if 'R' in msg and type(msg['R']) is not bool: msg = BlockExMarketsSignalRWorker.process_raw_msg(msg['R']) h["cb"](msg, h["a"]) """Worker process error received""" async def on_error_received(self, **msg): self.enqueue_event(AsyncEvents.OnError, msg) """Worker process market tick received""" async def on_market_tick_received(self, msg): self.invoke("getBids", self.kwargs['APIID'], msg[0]['instrumentID'], callback=self.on_bids_received) """Worker process market tick received""" async def on_bids_received(self, bids_msg, req): (_, msg) = req bids_msg['instrumentID'] = msg[0]['instrumentID'] self.enqueue_event('OnLatestBids', bids_msg) self.invoke("getAsks", self.kwargs['APIID'], msg[0]['instrumentID'], callback=self.on_asks_received) """Worker process market tick received""" async def on_asks_received(self, asks_msg, req): (_, msg) = req asks_msg['instrumentID'] = msg[0]['instrumentID'] self.enqueue_event('OnLatestAsks', asks_msg) """Worker process place order response received""" async def on_place_order_received(self, msg): self.enqueue_event(AsyncEvents.OnPlaceOrder, BlockExMarketsAsyncOrder(signalr_msg=msg)) """Worker process place order response received""" async def on_execution_received(self, msg): self.enqueue_event(AsyncEvents.OnExecution, BlockExMarketsAsyncExecution(signalr_msg=msg)) """Worker process cancel order response received""" async def on_cancel_order_received(self, msg): self.enqueue_event(AsyncEvents.OnCancelOrder, BlockExMarketsAsyncCancelOrderResponse(signalr_msg=msg)) """Worker process cancel all response received""" async def on_cancel_all_orders_received(self, msg): self.enqueue_event(AsyncEvents.OnCancelAllOrders, BlockExMarketsAsyncCancelAllResponse(signalr_msg=msg))
# Copyright (C) 2021 Dino Bollinger, ETH Zürich, Information Security Group # Released under the MIT License """ Using a database of collected cookie + label data, determine potential GDPR violations by checking whether Google Analytics cookie variants (or another known cookie, can be specified) were misclassified. ---------------------------------- Required arguments: <db_path> Path to database to analyze. Optional arguments: <name_pattern>: Specifies the regex pattern for the cookie name. <domain_pattern>: Specifies the regex pattern for the cookie domain. <expected_label>: Expected label for the cookie. --out_path <out_path>: Directory to store the resutls. Usage: method1_wrong_label.py <db_path> [<name_pattern> <domain_pattern> <expected_label> --out_path <out_path>] """ from docopt import docopt import os import sqlite3 import re import logging from utils import (setupLogger, CONSENTDATA_QUERY, write_json, get_violation_details_consent_table, write_vdomains) logger = logging.getLogger("vd") def main(): """ Try to detect potential violations by analyzing the category of specific cookies. @return: exit code, 0 for success """ argv = None cargs = docopt(__doc__, argv=argv) setupLogger(".", logging.INFO) logger.info("Running method 01: Wrong Label for Known Cookie") # Specify name, domain patter and expected label by input, or if cargs["<name_pattern>"]: name_pattern = re.compile(cargs["<name_pattern>"]) domain_pattern = re.compile(cargs["<domain_pattern>"]) expected_label = int(cargs["<expected_label>"]) else: logger.info("Using default GA check:") name_pattern = re.compile("(^_ga$|^_gat$|^_gid$|^_gat_gtag_UA_[0-9]+_[0-9]+|^_gat_UA-[0-9]+-[0-9]+)") domain_pattern = re.compile(".*") expected_label = 2 # Verify that database exists database_path = cargs["<db_path>"] if not os.path.exists(database_path): logger.error("Database file does not exist.") return 1 logger.info(f"Database used: {database_path}") # enable dictionary access by column name, access database conn = sqlite3.connect(database_path) conn.row_factory = sqlite3.Row # some variables to collect violation details with violation_details = dict() violation_domains = set() violation_counts = [0, 0, 0, 0, 0, 0, 0] total_domains = set() total_matching_cookies = 0 logger.info("Extracting info from database...") with conn: cur = conn.cursor() cur.execute(CONSENTDATA_QUERY) for row in cur: # Duplicate check, not necessary anymore #transform = {**row} #if transform.values() in duplicate_reject: # logger.info("Skipped exact duplicate entry") # continue #duplicate_reject.add(transform.values()) if name_pattern.match(row["consent_name"]) and domain_pattern.search(row["consent_domain"]): total_domains.add(row["site_url"]) total_matching_cookies += 1 if row["cat_id"] != expected_label and row["cat_id"] != -1: #logger.info(f"Potential Violation on website: {row["site_url"]} for cookie entry: {row["consent_name"]};{row["consent_domain"]}") #logger.info(f"Entry matches pattern, but given label was {row["cat_id"]}") cat_id = row["cat_id"] if cat_id == 99: cat_id = 5 vdomain = row["site_url"] violation_domains.add(vdomain) violation_counts[cat_id] += 1 if vdomain not in violation_details: violation_details[vdomain] = list() violation_details[vdomain].append(get_violation_details_consent_table(row)) conn.close() logger.info(f"Total matching cookies found: {total_matching_cookies}") logger.info(f"Number of potential violations: {violation_counts}") logger.info(f"Number of sites that have the cookie in total: {len(total_domains)}") logger.info(f"Number of sites with potential violations: {len(violation_domains)}") v_per_cmp = [0, 0, 0] for url, violating_cookies in violation_details.items(): for c in violating_cookies: assert (c["cmp_type"] >= 0) v_per_cmp[c["cmp_type"]] += 1 logger.info(f"Potential Violations per CMP Type: {v_per_cmp}") if cargs["--out_path"]: out_path = cargs["--out_path"] else: out_path = "./violation_stats/" write_json(violation_details, "method1_cookies.json", out_path) write_vdomains(violation_domains, "method1_domains.txt", out_path) return 0 if __name__ == '__main__': exit(main())
# Copyright (C) 2021 Dino Bollinger, ETH Zürich, Information Security Group # Released under the MIT License """ Using a database of collected cookie + label data, determine potential GDPR violations by checking whether Google Analytics cookie variants (or another known cookie, can be specified) were misclassified. ---------------------------------- Required arguments: <db_path> Path to database to analyze. Optional arguments: <name_pattern>: Specifies the regex pattern for the cookie name. <domain_pattern>: Specifies the regex pattern for the cookie domain. <expected_label>: Expected label for the cookie. --out_path <out_path>: Directory to store the resutls. Usage: method1_wrong_label.py <db_path> [<name_pattern> <domain_pattern> <expected_label> --out_path <out_path>] """ from docopt import docopt import os import sqlite3 import re import logging from utils import (setupLogger, CONSENTDATA_QUERY, write_json, get_violation_details_consent_table, write_vdomains) logger = logging.getLogger("vd") def main(): """ Try to detect potential violations by analyzing the category of specific cookies. @return: exit code, 0 for success """ argv = None cargs = docopt(__doc__, argv=argv) setupLogger(".", logging.INFO) logger.info("Running method 01: Wrong Label for Known Cookie") # Specify name, domain patter and expected label by input, or if cargs["<name_pattern>"]: name_pattern = re.compile(cargs["<name_pattern>"]) domain_pattern = re.compile(cargs["<domain_pattern>"]) expected_label = int(cargs["<expected_label>"]) else: logger.info("Using default GA check:") name_pattern = re.compile("(^_ga$|^_gat$|^_gid$|^_gat_gtag_UA_[0-9]+_[0-9]+|^_gat_UA-[0-9]+-[0-9]+)") domain_pattern = re.compile(".*") expected_label = 2 # Verify that database exists database_path = cargs["<db_path>"] if not os.path.exists(database_path): logger.error("Database file does not exist.") return 1 logger.info(f"Database used: {database_path}") # enable dictionary access by column name, access database conn = sqlite3.connect(database_path) conn.row_factory = sqlite3.Row # some variables to collect violation details with violation_details = dict() violation_domains = set() violation_counts = [0, 0, 0, 0, 0, 0, 0] total_domains = set() total_matching_cookies = 0 logger.info("Extracting info from database...") with conn: cur = conn.cursor() cur.execute(CONSENTDATA_QUERY) for row in cur: # Duplicate check, not necessary anymore #transform = {**row} #if transform.values() in duplicate_reject: # logger.info("Skipped exact duplicate entry") # continue #duplicate_reject.add(transform.values()) if name_pattern.match(row["consent_name"]) and domain_pattern.search(row["consent_domain"]): total_domains.add(row["site_url"]) total_matching_cookies += 1 if row["cat_id"] != expected_label and row["cat_id"] != -1: #logger.info(f"Potential Violation on website: {row['site_url']} for cookie entry: {row['consent_name']};{row['consent_domain']}") #logger.info(f"Entry matches pattern, but given label was {row['cat_id']}") cat_id = row["cat_id"] if cat_id == 99: cat_id = 5 vdomain = row["site_url"] violation_domains.add(vdomain) violation_counts[cat_id] += 1 if vdomain not in violation_details: violation_details[vdomain] = list() violation_details[vdomain].append(get_violation_details_consent_table(row)) conn.close() logger.info(f"Total matching cookies found: {total_matching_cookies}") logger.info(f"Number of potential violations: {violation_counts}") logger.info(f"Number of sites that have the cookie in total: {len(total_domains)}") logger.info(f"Number of sites with potential violations: {len(violation_domains)}") v_per_cmp = [0, 0, 0] for url, violating_cookies in violation_details.items(): for c in violating_cookies: assert (c["cmp_type"] >= 0) v_per_cmp[c["cmp_type"]] += 1 logger.info(f"Potential Violations per CMP Type: {v_per_cmp}") if cargs["--out_path"]: out_path = cargs["--out_path"] else: out_path = "./violation_stats/" write_json(violation_details, "method1_cookies.json", out_path) write_vdomains(violation_domains, "method1_domains.txt", out_path) return 0 if __name__ == '__main__': exit(main())
from datetime import ( date, datetime, timedelta, ) from functools import partial from io import BytesIO import os import re import numpy as np import pytest import pandas.util._test_decorators as td import pandas as pd from pandas import ( DataFrame, Index, MultiIndex, get_option, set_option, ) import pandas._testing as tm from pandas.io.excel import ( ExcelFile, ExcelWriter, _OpenpyxlWriter, _XlsxWriter, _XlwtWriter, register_writer, ) @pytest.fixture def path(ext): """ Fixture to open file for use in each test case. """ with tm.ensure_clean(ext) as file_path: yield file_path @pytest.fixture def set_engine(engine, ext): """ Fixture to set engine for use in each test case. Rather than requiring `engine=...` to be provided explicitly as an argument in each test, this fixture sets a global option to dictate which engine should be used to write Excel files. After executing the test it rolls back said change to the global option. """ option_name = f"io.excel.{ext.strip(".")}.writer" prev_engine = get_option(option_name) set_option(option_name, engine) yield set_option(option_name, prev_engine) # Roll back option change @pytest.mark.parametrize( "ext", [ pytest.param(".xlsx", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")]), pytest.param(".xlsm", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")]), pytest.param(".xls", marks=[td.skip_if_no("xlwt"), td.skip_if_no("xlrd")]), pytest.param( ".xlsx", marks=[td.skip_if_no("xlsxwriter"), td.skip_if_no("xlrd")] ), pytest.param(".ods", marks=td.skip_if_no("odf")), ], ) class TestRoundTrip: @pytest.mark.parametrize( "header,expected", [(None, DataFrame([np.nan] * 4)), (0, DataFrame({"Unnamed: 0": [np.nan] * 3}))], ) def test_read_one_empty_col_no_header(self, ext, header, expected): # xref gh-12292 filename = "no_header" df = DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]]) with tm.ensure_clean(ext) as path: df.to_excel(path, filename, index=False, header=False) result = pd.read_excel( path, sheet_name=filename, usecols=[0], header=header ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "header,expected", [(None, DataFrame([0] + [np.nan] * 4)), (0, DataFrame([np.nan] * 4))], ) def test_read_one_empty_col_with_header(self, ext, header, expected): filename = "with_header" df = DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]]) with tm.ensure_clean(ext) as path: df.to_excel(path, "with_header", index=False, header=True) result = pd.read_excel( path, sheet_name=filename, usecols=[0], header=header ) tm.assert_frame_equal(result, expected) def test_set_column_names_in_parameter(self, ext): # GH 12870 : pass down column names associated with # keyword argument names refdf = DataFrame([[1, "foo"], [2, "bar"], [3, "baz"]], columns=["a", "b"]) with tm.ensure_clean(ext) as pth: with ExcelWriter(pth) as writer: refdf.to_excel(writer, "Data_no_head", header=False, index=False) refdf.to_excel(writer, "Data_with_head", index=False) refdf.columns = ["A", "B"] with ExcelFile(pth) as reader: xlsdf_no_head = pd.read_excel( reader, sheet_name="Data_no_head", header=None, names=["A", "B"] ) xlsdf_with_head = pd.read_excel( reader, sheet_name="Data_with_head", index_col=None, names=["A", "B"], ) tm.assert_frame_equal(xlsdf_no_head, refdf) tm.assert_frame_equal(xlsdf_with_head, refdf) def test_creating_and_reading_multiple_sheets(self, ext): # see gh-9450 # # Test reading multiple sheets, from a runtime # created Excel file with multiple sheets. def tdf(col_sheet_name): d, i = [11, 22, 33], [1, 2, 3] return DataFrame(d, i, columns=[col_sheet_name]) sheets = ["AAA", "BBB", "CCC"] dfs = [tdf(s) for s in sheets] dfs = dict(zip(sheets, dfs)) with tm.ensure_clean(ext) as pth: with ExcelWriter(pth) as ew: for sheetname, df in dfs.items(): df.to_excel(ew, sheetname) dfs_returned = pd.read_excel(pth, sheet_name=sheets, index_col=0) for s in sheets: tm.assert_frame_equal(dfs[s], dfs_returned[s]) def test_read_excel_multiindex_empty_level(self, ext): # see gh-12453 with tm.ensure_clean(ext) as path: df = DataFrame( { ("One", "x"): {0: 1}, ("Two", "X"): {0: 3}, ("Two", "Y"): {0: 7}, ("Zero", ""): {0: 0}, } ) expected = DataFrame( { ("One", "x"): {0: 1}, ("Two", "X"): {0: 3}, ("Two", "Y"): {0: 7}, ("Zero", "Unnamed: 4_level_1"): {0: 0}, } ) df.to_excel(path) actual = pd.read_excel(path, header=[0, 1], index_col=0) tm.assert_frame_equal(actual, expected) df = DataFrame( { ("Beg", ""): {0: 0}, ("Middle", "x"): {0: 1}, ("Tail", "X"): {0: 3}, ("Tail", "Y"): {0: 7}, } ) expected = DataFrame( { ("Beg", "Unnamed: 1_level_1"): {0: 0}, ("Middle", "x"): {0: 1}, ("Tail", "X"): {0: 3}, ("Tail", "Y"): {0: 7}, } ) df.to_excel(path) actual = pd.read_excel(path, header=[0, 1], index_col=0) tm.assert_frame_equal(actual, expected) @pytest.mark.parametrize("c_idx_names", [True, False]) @pytest.mark.parametrize("r_idx_names", [True, False]) @pytest.mark.parametrize("c_idx_levels", [1, 3]) @pytest.mark.parametrize("r_idx_levels", [1, 3]) def test_excel_multindex_roundtrip( self, ext, c_idx_names, r_idx_names, c_idx_levels, r_idx_levels, request ): # see gh-4679 with tm.ensure_clean(ext) as pth: if (c_idx_levels == 1 and c_idx_names) and not ( r_idx_levels == 3 and not r_idx_names ): mark = pytest.mark.xfail( reason="Column index name cannot be serialized unless " "it's a MultiIndex" ) request.node.add_marker(mark) # Empty name case current read in as # unnamed levels, not Nones. check_names = r_idx_names or r_idx_levels <= 1 df = tm.makeCustomDataframe( 5, 5, c_idx_names, r_idx_names, c_idx_levels, r_idx_levels ) df.to_excel(pth) act = pd.read_excel( pth, index_col=list(range(r_idx_levels)), header=list(range(c_idx_levels)), ) tm.assert_frame_equal(df, act, check_names=check_names) df.iloc[0, :] = np.nan df.to_excel(pth) act = pd.read_excel( pth, index_col=list(range(r_idx_levels)), header=list(range(c_idx_levels)), ) tm.assert_frame_equal(df, act, check_names=check_names) df.iloc[-1, :] = np.nan df.to_excel(pth) act = pd.read_excel( pth, index_col=list(range(r_idx_levels)), header=list(range(c_idx_levels)), ) tm.assert_frame_equal(df, act, check_names=check_names) def test_read_excel_parse_dates(self, ext): # see gh-11544, gh-12051 df = DataFrame( {"col": [1, 2, 3], "date_strings": pd.date_range("2012-01-01", periods=3)} ) df2 = df.copy() df2["date_strings"] = df2["date_strings"].dt.strftime("%m/%d/%Y") with tm.ensure_clean(ext) as pth: df2.to_excel(pth) res = pd.read_excel(pth, index_col=0) tm.assert_frame_equal(df2, res) res = pd.read_excel(pth, parse_dates=["date_strings"], index_col=0) tm.assert_frame_equal(df, res) date_parser = lambda x: datetime.strptime(x, "%m/%d/%Y") res = pd.read_excel( pth, parse_dates=["date_strings"], date_parser=date_parser, index_col=0 ) tm.assert_frame_equal(df, res) def test_multiindex_interval_datetimes(self, ext): # GH 30986 midx = MultiIndex.from_arrays( [ range(4), pd.interval_range( start=pd.Timestamp("2020-01-01"), periods=4, freq="6M" ), ] ) df = DataFrame(range(4), index=midx) with tm.ensure_clean(ext) as pth: df.to_excel(pth) result = pd.read_excel(pth, index_col=[0, 1]) expected = DataFrame( range(4), MultiIndex.from_arrays( [ range(4), [ "(2020-01-31, 2020-07-31]", "(2020-07-31, 2021-01-31]", "(2021-01-31, 2021-07-31]", "(2021-07-31, 2022-01-31]", ], ] ), ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "engine,ext", [ pytest.param( "openpyxl", ".xlsx", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")], ), pytest.param( "openpyxl", ".xlsm", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")], ), pytest.param( "xlwt", ".xls", marks=[td.skip_if_no("xlwt"), td.skip_if_no("xlrd")] ), pytest.param( "xlsxwriter", ".xlsx", marks=[td.skip_if_no("xlsxwriter"), td.skip_if_no("xlrd")], ), pytest.param("odf", ".ods", marks=td.skip_if_no("odf")), ], ) @pytest.mark.usefixtures("set_engine") class TestExcelWriter: def test_excel_sheet_size(self, path): # GH 26080 breaking_row_count = 2 ** 20 + 1 breaking_col_count = 2 ** 14 + 1 # purposely using two arrays to prevent memory issues while testing row_arr = np.zeros(shape=(breaking_row_count, 1)) col_arr = np.zeros(shape=(1, breaking_col_count)) row_df = DataFrame(row_arr) col_df = DataFrame(col_arr) msg = "sheet is too large" with pytest.raises(ValueError, match=msg): row_df.to_excel(path) with pytest.raises(ValueError, match=msg): col_df.to_excel(path) def test_excel_sheet_by_name_raise(self, path, engine): gt = DataFrame(np.random.randn(10, 2)) gt.to_excel(path) with ExcelFile(path) as xl: df = pd.read_excel(xl, sheet_name=0, index_col=0) tm.assert_frame_equal(gt, df) msg = "Worksheet named '0' not found" with pytest.raises(ValueError, match=msg): pd.read_excel(xl, "0") def test_excel_writer_context_manager(self, frame, path): with ExcelWriter(path) as writer: frame.to_excel(writer, "Data1") frame2 = frame.copy() frame2.columns = frame.columns[::-1] frame2.to_excel(writer, "Data2") with ExcelFile(path) as reader: found_df = pd.read_excel(reader, sheet_name="Data1", index_col=0) found_df2 = pd.read_excel(reader, sheet_name="Data2", index_col=0) tm.assert_frame_equal(found_df, frame) tm.assert_frame_equal(found_df2, frame2) def test_roundtrip(self, frame, path): frame = frame.copy() frame["A"][:5] = np.nan frame.to_excel(path, "test1") frame.to_excel(path, "test1", columns=["A", "B"]) frame.to_excel(path, "test1", header=False) frame.to_excel(path, "test1", index=False) # test roundtrip frame.to_excel(path, "test1") recons = pd.read_excel(path, sheet_name="test1", index_col=0) tm.assert_frame_equal(frame, recons) frame.to_excel(path, "test1", index=False) recons = pd.read_excel(path, sheet_name="test1", index_col=None) recons.index = frame.index tm.assert_frame_equal(frame, recons) frame.to_excel(path, "test1", na_rep="NA") recons = pd.read_excel(path, sheet_name="test1", index_col=0, na_values=["NA"]) tm.assert_frame_equal(frame, recons) # GH 3611 frame.to_excel(path, "test1", na_rep="88") recons = pd.read_excel(path, sheet_name="test1", index_col=0, na_values=["88"]) tm.assert_frame_equal(frame, recons) frame.to_excel(path, "test1", na_rep="88") recons = pd.read_excel( path, sheet_name="test1", index_col=0, na_values=[88, 88.0] ) tm.assert_frame_equal(frame, recons) # GH 6573 frame.to_excel(path, "Sheet1") recons = pd.read_excel(path, index_col=0) tm.assert_frame_equal(frame, recons) frame.to_excel(path, "0") recons = pd.read_excel(path, index_col=0) tm.assert_frame_equal(frame, recons) # GH 8825 Pandas Series should provide to_excel method s = frame["A"] s.to_excel(path) recons = pd.read_excel(path, index_col=0) tm.assert_frame_equal(s.to_frame(), recons) def test_mixed(self, frame, path): mixed_frame = frame.copy() mixed_frame["foo"] = "bar" mixed_frame.to_excel(path, "test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(mixed_frame, recons) def test_ts_frame(self, tsframe, path): df = tsframe # freq doesn't round-trip index = pd.DatetimeIndex(np.asarray(df.index), freq=None) df.index = index df.to_excel(path, "test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(df, recons) def test_basics_with_nan(self, frame, path): frame = frame.copy() frame["A"][:5] = np.nan frame.to_excel(path, "test1") frame.to_excel(path, "test1", columns=["A", "B"]) frame.to_excel(path, "test1", header=False) frame.to_excel(path, "test1", index=False) @pytest.mark.parametrize("np_type", [np.int8, np.int16, np.int32, np.int64]) def test_int_types(self, np_type, path): # Test np.int values read come back as int # (rather than float which is Excel's format). df = DataFrame(np.random.randint(-10, 10, size=(10, 2)), dtype=np_type) df.to_excel(path, "test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) int_frame = df.astype(np.int64) tm.assert_frame_equal(int_frame, recons) recons2 = pd.read_excel(path, sheet_name="test1", index_col=0) tm.assert_frame_equal(int_frame, recons2) # Test with convert_float=False comes back as float. float_frame = df.astype(float) float_frame.columns = float_frame.columns.astype(float) float_frame.index = float_frame.index.astype(float) with tm.assert_produces_warning( FutureWarning, match="convert_float is deprecated" ): recons = pd.read_excel( path, sheet_name="test1", convert_float=False, index_col=0 ) tm.assert_frame_equal(recons, float_frame) @pytest.mark.parametrize("np_type", [np.float16, np.float32, np.float64]) def test_float_types(self, np_type, path): # Test np.float values read come back as float. df = DataFrame(np.random.random_sample(10), dtype=np_type) df.to_excel(path, "test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( np_type ) tm.assert_frame_equal(df, recons) @pytest.mark.parametrize("np_type", [np.bool8, np.bool_]) def test_bool_types(self, np_type, path): # Test np.bool8 and np.bool_ values read come back as float. df = DataFrame([1, 0, True, False], dtype=np_type) df.to_excel(path, "test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( np_type ) tm.assert_frame_equal(df, recons) def test_inf_roundtrip(self, path): df = DataFrame([(1, np.inf), (2, 3), (5, -np.inf)]) df.to_excel(path, "test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(df, recons) def test_sheets(self, frame, tsframe, path): # freq doesn't round-trip index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None) tsframe.index = index frame = frame.copy() frame["A"][:5] = np.nan frame.to_excel(path, "test1") frame.to_excel(path, "test1", columns=["A", "B"]) frame.to_excel(path, "test1", header=False) frame.to_excel(path, "test1", index=False) # Test writing to separate sheets with ExcelWriter(path) as writer: frame.to_excel(writer, "test1") tsframe.to_excel(writer, "test2") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(frame, recons) recons = pd.read_excel(reader, sheet_name="test2", index_col=0) tm.assert_frame_equal(tsframe, recons) assert 2 == len(reader.sheet_names) assert "test1" == reader.sheet_names[0] assert "test2" == reader.sheet_names[1] def test_colaliases(self, frame, path): frame = frame.copy() frame["A"][:5] = np.nan frame.to_excel(path, "test1") frame.to_excel(path, "test1", columns=["A", "B"]) frame.to_excel(path, "test1", header=False) frame.to_excel(path, "test1", index=False) # column aliases col_aliases = Index(["AA", "X", "Y", "Z"]) frame.to_excel(path, "test1", header=col_aliases) with ExcelFile(path) as reader: rs = pd.read_excel(reader, sheet_name="test1", index_col=0) xp = frame.copy() xp.columns = col_aliases tm.assert_frame_equal(xp, rs) def test_roundtrip_indexlabels(self, merge_cells, frame, path): frame = frame.copy() frame["A"][:5] = np.nan frame.to_excel(path, "test1") frame.to_excel(path, "test1", columns=["A", "B"]) frame.to_excel(path, "test1", header=False) frame.to_excel(path, "test1", index=False) # test index_label df = DataFrame(np.random.randn(10, 2)) >= 0 df.to_excel(path, "test1", index_label=["test"], merge_cells=merge_cells) with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( np.int64 ) df.index.names = ["test"] assert df.index.names == recons.index.names df = DataFrame(np.random.randn(10, 2)) >= 0 df.to_excel( path, "test1", index_label=["test", "dummy", "dummy2"], merge_cells=merge_cells, ) with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( np.int64 ) df.index.names = ["test"] assert df.index.names == recons.index.names df = DataFrame(np.random.randn(10, 2)) >= 0 df.to_excel(path, "test1", index_label="test", merge_cells=merge_cells) with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( np.int64 ) df.index.names = ["test"] tm.assert_frame_equal(df, recons.astype(bool)) frame.to_excel( path, "test1", columns=["A", "B", "C", "D"], index=False, merge_cells=merge_cells, ) # take 'A' and 'B' as indexes (same row as cols 'C', 'D') df = frame.copy() df = df.set_index(["A", "B"]) with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1]) tm.assert_frame_equal(df, recons) def test_excel_roundtrip_indexname(self, merge_cells, path): df = DataFrame(np.random.randn(10, 4)) df.index.name = "foo" df.to_excel(path, merge_cells=merge_cells) with ExcelFile(path) as xf: result = pd.read_excel(xf, sheet_name=xf.sheet_names[0], index_col=0) tm.assert_frame_equal(result, df) assert result.index.name == "foo" def test_excel_roundtrip_datetime(self, merge_cells, tsframe, path): # datetime.date, not sure what to test here exactly # freq does not round-trip index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None) tsframe.index = index tsf = tsframe.copy() tsf.index = [x.date() for x in tsframe.index] tsf.to_excel(path, "test1", merge_cells=merge_cells) with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(tsframe, recons) def test_excel_date_datetime_format(self, engine, ext, path): # see gh-4133 # # Excel output format strings df = DataFrame( [ [date(2014, 1, 31), date(1999, 9, 24)], [datetime(1998, 5, 26, 23, 33, 4), datetime(2014, 2, 28, 13, 5, 13)], ], index=["DATE", "DATETIME"], columns=["X", "Y"], ) df_expected = DataFrame( [ [datetime(2014, 1, 31), datetime(1999, 9, 24)], [datetime(1998, 5, 26, 23, 33, 4), datetime(2014, 2, 28, 13, 5, 13)], ], index=["DATE", "DATETIME"], columns=["X", "Y"], ) with tm.ensure_clean(ext) as filename2: with ExcelWriter(path) as writer1: df.to_excel(writer1, "test1") with ExcelWriter( filename2, date_format="DD.MM.YYYY", datetime_format="DD.MM.YYYY HH-MM-SS", ) as writer2: df.to_excel(writer2, "test1") with ExcelFile(path) as reader1: rs1 = pd.read_excel(reader1, sheet_name="test1", index_col=0) with ExcelFile(filename2) as reader2: rs2 = pd.read_excel(reader2, sheet_name="test1", index_col=0) tm.assert_frame_equal(rs1, rs2) # Since the reader returns a datetime object for dates, # we need to use df_expected to check the result. tm.assert_frame_equal(rs2, df_expected) def test_to_excel_interval_no_labels(self, path): # see gh-19242 # # Test writing Interval without labels. df = DataFrame(np.random.randint(-10, 10, size=(20, 1)), dtype=np.int64) expected = df.copy() df["new"] = pd.cut(df[0], 10) expected["new"] = pd.cut(expected[0], 10).astype(str) df.to_excel(path, "test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(expected, recons) def test_to_excel_interval_labels(self, path): # see gh-19242 # # Test writing Interval with labels. df = DataFrame(np.random.randint(-10, 10, size=(20, 1)), dtype=np.int64) expected = df.copy() intervals = pd.cut( df[0], 10, labels=["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] ) df["new"] = intervals expected["new"] = pd.Series(list(intervals)) df.to_excel(path, "test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(expected, recons) def test_to_excel_timedelta(self, path): # see gh-19242, gh-9155 # # Test writing timedelta to xls. df = DataFrame( np.random.randint(-10, 10, size=(20, 1)), columns=["A"], dtype=np.int64 ) expected = df.copy() df["new"] = df["A"].apply(lambda x: timedelta(seconds=x)) expected["new"] = expected["A"].apply( lambda x: timedelta(seconds=x).total_seconds() / 86400 ) df.to_excel(path, "test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(expected, recons) def test_to_excel_periodindex(self, tsframe, path): xp = tsframe.resample("M", kind="period").mean() xp.to_excel(path, "sht1") with ExcelFile(path) as reader: rs = pd.read_excel(reader, sheet_name="sht1", index_col=0) tm.assert_frame_equal(xp, rs.to_period("M")) def test_to_excel_multiindex(self, merge_cells, frame, path): arrays = np.arange(len(frame.index) * 2).reshape(2, -1) new_index = MultiIndex.from_arrays(arrays, names=["first", "second"]) frame.index = new_index frame.to_excel(path, "test1", header=False) frame.to_excel(path, "test1", columns=["A", "B"]) # round trip frame.to_excel(path, "test1", merge_cells=merge_cells) with ExcelFile(path) as reader: df = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1]) tm.assert_frame_equal(frame, df) # GH13511 def test_to_excel_multiindex_nan_label(self, merge_cells, path): df = DataFrame({"A": [None, 2, 3], "B": [10, 20, 30], "C": np.random.sample(3)}) df = df.set_index(["A", "B"]) df.to_excel(path, merge_cells=merge_cells) df1 = pd.read_excel(path, index_col=[0, 1]) tm.assert_frame_equal(df, df1) # Test for Issue 11328. If column indices are integers, make # sure they are handled correctly for either setting of # merge_cells def test_to_excel_multiindex_cols(self, merge_cells, frame, path): arrays = np.arange(len(frame.index) * 2).reshape(2, -1) new_index = MultiIndex.from_arrays(arrays, names=["first", "second"]) frame.index = new_index new_cols_index = MultiIndex.from_tuples([(40, 1), (40, 2), (50, 1), (50, 2)]) frame.columns = new_cols_index header = [0, 1] if not merge_cells: header = 0 # round trip frame.to_excel(path, "test1", merge_cells=merge_cells) with ExcelFile(path) as reader: df = pd.read_excel( reader, sheet_name="test1", header=header, index_col=[0, 1] ) if not merge_cells: fm = frame.columns.format(sparsify=False, adjoin=False, names=False) frame.columns = [".".join(map(str, q)) for q in zip(*fm)] tm.assert_frame_equal(frame, df) def test_to_excel_multiindex_dates(self, merge_cells, tsframe, path): # try multiindex with dates new_index = [tsframe.index, np.arange(len(tsframe.index))] tsframe.index = MultiIndex.from_arrays(new_index) tsframe.index.names = ["time", "foo"] tsframe.to_excel(path, "test1", merge_cells=merge_cells) with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1]) tm.assert_frame_equal(tsframe, recons) assert recons.index.names == ("time", "foo") def test_to_excel_multiindex_no_write_index(self, path): # Test writing and re-reading a MI without the index. GH 5616. # Initial non-MI frame. frame1 = DataFrame({"a": [10, 20], "b": [30, 40], "c": [50, 60]}) # Add a MI. frame2 = frame1.copy() multi_index = MultiIndex.from_tuples([(70, 80), (90, 100)]) frame2.index = multi_index # Write out to Excel without the index. frame2.to_excel(path, "test1", index=False) # Read it back in. with ExcelFile(path) as reader: frame3 = pd.read_excel(reader, sheet_name="test1") # Test that it is the same as the initial frame. tm.assert_frame_equal(frame1, frame3) def test_to_excel_float_format(self, path): df = DataFrame( [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], index=["A", "B"], columns=["X", "Y", "Z"], ) df.to_excel(path, "test1", float_format="%.2f") with ExcelFile(path) as reader: result = pd.read_excel(reader, sheet_name="test1", index_col=0) expected = DataFrame( [[0.12, 0.23, 0.57], [12.32, 123123.20, 321321.20]], index=["A", "B"], columns=["X", "Y", "Z"], ) tm.assert_frame_equal(result, expected) def test_to_excel_output_encoding(self, ext): # Avoid mixed inferred_type. df = DataFrame( [["\u0192", "\u0193", "\u0194"], ["\u0195", "\u0196", "\u0197"]], index=["A\u0192", "B"], columns=["X\u0193", "Y", "Z"], ) with tm.ensure_clean("__tmp_to_excel_float_format__." + ext) as filename: df.to_excel(filename, sheet_name="TestSheet", encoding="utf8") result = pd.read_excel(filename, sheet_name="TestSheet", index_col=0) tm.assert_frame_equal(result, df) def test_to_excel_unicode_filename(self, ext, path): with tm.ensure_clean("\u0192u." + ext) as filename: try: f = open(filename, "wb") except UnicodeEncodeError: pytest.skip("No unicode file names on this system") finally: f.close() df = DataFrame( [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], index=["A", "B"], columns=["X", "Y", "Z"], ) df.to_excel(filename, "test1", float_format="%.2f") with ExcelFile(filename) as reader: result = pd.read_excel(reader, sheet_name="test1", index_col=0) expected = DataFrame( [[0.12, 0.23, 0.57], [12.32, 123123.20, 321321.20]], index=["A", "B"], columns=["X", "Y", "Z"], ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("use_headers", [True, False]) @pytest.mark.parametrize("r_idx_nlevels", [1, 2, 3]) @pytest.mark.parametrize("c_idx_nlevels", [1, 2, 3]) def test_excel_010_hemstring( self, merge_cells, c_idx_nlevels, r_idx_nlevels, use_headers, path ): def roundtrip(data, header=True, parser_hdr=0, index=True): data.to_excel(path, header=header, merge_cells=merge_cells, index=index) with ExcelFile(path) as xf: return pd.read_excel( xf, sheet_name=xf.sheet_names[0], header=parser_hdr ) # Basic test. parser_header = 0 if use_headers else None res = roundtrip(DataFrame([0]), use_headers, parser_header) assert res.shape == (1, 2) assert res.iloc[0, 0] is not np.nan # More complex tests with multi-index. nrows = 5 ncols = 3 # ensure limited functionality in 0.10 # override of gh-2370 until sorted out in 0.11 df = tm.makeCustomDataframe( nrows, ncols, r_idx_nlevels=r_idx_nlevels, c_idx_nlevels=c_idx_nlevels ) # This if will be removed once multi-column Excel writing # is implemented. For now fixing gh-9794. if c_idx_nlevels > 1: msg = ( "Writing to Excel with MultiIndex columns and no index " "\\('index'=False\\) is not yet implemented." ) with pytest.raises(NotImplementedError, match=msg): roundtrip(df, use_headers, index=False) else: res = roundtrip(df, use_headers) if use_headers: assert res.shape == (nrows, ncols + r_idx_nlevels) else: # First row taken as columns. assert res.shape == (nrows - 1, ncols + r_idx_nlevels) # No NaNs. for r in range(len(res.index)): for c in range(len(res.columns)): assert res.iloc[r, c] is not np.nan def test_duplicated_columns(self, path): # see gh-5235 df = DataFrame([[1, 2, 3], [1, 2, 3], [1, 2, 3]], columns=["A", "B", "B"]) df.to_excel(path, "test1") expected = DataFrame( [[1, 2, 3], [1, 2, 3], [1, 2, 3]], columns=["A", "B", "B.1"] ) # By default, we mangle. result = pd.read_excel(path, sheet_name="test1", index_col=0) tm.assert_frame_equal(result, expected) # Explicitly, we pass in the parameter. result = pd.read_excel( path, sheet_name="test1", index_col=0, mangle_dupe_cols=True ) tm.assert_frame_equal(result, expected) # see gh-11007, gh-10970 df = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "A", "B"]) df.to_excel(path, "test1") result = pd.read_excel(path, sheet_name="test1", index_col=0) expected = DataFrame( [[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "A.1", "B.1"] ) tm.assert_frame_equal(result, expected) # see gh-10982 df.to_excel(path, "test1", index=False, header=False) result = pd.read_excel(path, sheet_name="test1", header=None) expected = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]]) tm.assert_frame_equal(result, expected) msg = "Setting mangle_dupe_cols=False is not supported yet" with pytest.raises(ValueError, match=msg): pd.read_excel(path, sheet_name="test1", header=None, mangle_dupe_cols=False) def test_swapped_columns(self, path): # Test for issue #5427. write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2]}) write_frame.to_excel(path, "test1", columns=["B", "A"]) read_frame = pd.read_excel(path, sheet_name="test1", header=0) tm.assert_series_equal(write_frame["A"], read_frame["A"]) tm.assert_series_equal(write_frame["B"], read_frame["B"]) def test_invalid_columns(self, path): # see gh-10982 write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2]}) with pytest.raises(KeyError, match="Not all names specified"): write_frame.to_excel(path, "test1", columns=["B", "C"]) with pytest.raises( KeyError, match="'passes columns are not ALL present dataframe'" ): write_frame.to_excel(path, "test1", columns=["C", "D"]) @pytest.mark.parametrize( "to_excel_index,read_excel_index_col", [ (True, 0), # Include index in write to file (False, None), # Dont include index in write to file ], ) def test_write_subset_columns(self, path, to_excel_index, read_excel_index_col): # GH 31677 write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2], "C": [3, 3, 3]}) write_frame.to_excel( path, "col_subset_bug", columns=["A", "B"], index=to_excel_index ) expected = write_frame[["A", "B"]] read_frame = pd.read_excel( path, sheet_name="col_subset_bug", index_col=read_excel_index_col ) tm.assert_frame_equal(expected, read_frame) def test_comment_arg(self, path): # see gh-18735 # # Test the comment argument functionality to pd.read_excel. # Create file to read in. df = DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]}) df.to_excel(path, "test_c") # Read file without comment arg. result1 = pd.read_excel(path, sheet_name="test_c", index_col=0) result1.iloc[1, 0] = None result1.iloc[1, 1] = None result1.iloc[2, 1] = None result2 = pd.read_excel(path, sheet_name="test_c", comment="#", index_col=0) tm.assert_frame_equal(result1, result2) def test_comment_default(self, path): # Re issue #18735 # Test the comment argument default to pd.read_excel # Create file to read in df = DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]}) df.to_excel(path, "test_c") # Read file with default and explicit comment=None result1 = pd.read_excel(path, sheet_name="test_c") result2 = pd.read_excel(path, sheet_name="test_c", comment=None) tm.assert_frame_equal(result1, result2) def test_comment_used(self, path): # see gh-18735 # # Test the comment argument is working as expected when used. # Create file to read in. df = DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]}) df.to_excel(path, "test_c") # Test read_frame_comment against manually produced expected output. expected = DataFrame({"A": ["one", None, "one"], "B": ["two", None, None]}) result = pd.read_excel(path, sheet_name="test_c", comment="#", index_col=0) tm.assert_frame_equal(result, expected) def test_comment_empty_line(self, path): # Re issue #18735 # Test that pd.read_excel ignores commented lines at the end of file df = DataFrame({"a": ["1", "#2"], "b": ["2", "3"]}) df.to_excel(path, index=False) # Test that all-comment lines at EoF are ignored expected = DataFrame({"a": [1], "b": [2]}) result = pd.read_excel(path, comment="#") tm.assert_frame_equal(result, expected) def test_datetimes(self, path): # Test writing and reading datetimes. For issue #9139. (xref #9185) datetimes = [ datetime(2013, 1, 13, 1, 2, 3), datetime(2013, 1, 13, 2, 45, 56), datetime(2013, 1, 13, 4, 29, 49), datetime(2013, 1, 13, 6, 13, 42), datetime(2013, 1, 13, 7, 57, 35), datetime(2013, 1, 13, 9, 41, 28), datetime(2013, 1, 13, 11, 25, 21), datetime(2013, 1, 13, 13, 9, 14), datetime(2013, 1, 13, 14, 53, 7), datetime(2013, 1, 13, 16, 37, 0), datetime(2013, 1, 13, 18, 20, 52), ] write_frame = DataFrame({"A": datetimes}) write_frame.to_excel(path, "Sheet1") if path.endswith("xlsx") or path.endswith("xlsm"): pytest.skip( "Defaults to openpyxl and fails with floating point error on " "datetimes; may be fixed on newer versions of openpyxl - GH #38644" ) read_frame = pd.read_excel(path, sheet_name="Sheet1", header=0) tm.assert_series_equal(write_frame["A"], read_frame["A"]) def test_bytes_io(self, engine): # see gh-7074 with BytesIO() as bio: df = DataFrame(np.random.randn(10, 2)) # Pass engine explicitly, as there is no file path to infer from. with ExcelWriter(bio, engine=engine) as writer: df.to_excel(writer) bio.seek(0) reread_df = pd.read_excel(bio, index_col=0) tm.assert_frame_equal(df, reread_df) def test_write_lists_dict(self, path): # see gh-8188. df = DataFrame( { "mixed": ["a", ["b", "c"], {"d": "e", "f": 2}], "numeric": [1, 2, 3.0], "str": ["apple", "banana", "cherry"], } ) df.to_excel(path, "Sheet1") read = pd.read_excel(path, sheet_name="Sheet1", header=0, index_col=0) expected = df.copy() expected.mixed = expected.mixed.apply(str) expected.numeric = expected.numeric.astype("int64") tm.assert_frame_equal(read, expected) def test_render_as_column_name(self, path): # see gh-34331 df = DataFrame({"render": [1, 2], "data": [3, 4]}) df.to_excel(path, "Sheet1") read = pd.read_excel(path, "Sheet1", index_col=0) expected = df tm.assert_frame_equal(read, expected) def test_true_and_false_value_options(self, path): # see gh-13347 df = DataFrame([["foo", "bar"]], columns=["col1", "col2"]) expected = df.replace({"foo": True, "bar": False}) df.to_excel(path) read_frame = pd.read_excel( path, true_values=["foo"], false_values=["bar"], index_col=0 ) tm.assert_frame_equal(read_frame, expected) def test_freeze_panes(self, path): # see gh-15160 expected = DataFrame([[1, 2], [3, 4]], columns=["col1", "col2"]) expected.to_excel(path, "Sheet1", freeze_panes=(1, 1)) result = pd.read_excel(path, index_col=0) tm.assert_frame_equal(result, expected) def test_path_path_lib(self, engine, ext): df = tm.makeDataFrame() writer = partial(df.to_excel, engine=engine) reader = partial(pd.read_excel, index_col=0) result = tm.round_trip_pathlib(writer, reader, path=f"foo{ext}") tm.assert_frame_equal(result, df) def test_path_local_path(self, engine, ext): df = tm.makeDataFrame() writer = partial(df.to_excel, engine=engine) reader = partial(pd.read_excel, index_col=0) result = tm.round_trip_localpath(writer, reader, path=f"foo{ext}") tm.assert_frame_equal(result, df) def test_merged_cell_custom_objects(self, merge_cells, path): # see GH-27006 mi = MultiIndex.from_tuples( [ (pd.Period("2018"), pd.Period("2018Q1")), (pd.Period("2018"), pd.Period("2018Q2")), ] ) expected = DataFrame(np.ones((2, 2)), columns=mi) expected.to_excel(path) with tm.assert_produces_warning( FutureWarning, match="convert_float is deprecated" ): result = pd.read_excel( path, header=[0, 1], index_col=0, convert_float=False ) # need to convert PeriodIndexes to standard Indexes for assert equal expected.columns = expected.columns.set_levels( [[str(i) for i in mi.levels[0]], [str(i) for i in mi.levels[1]]], level=[0, 1], ) expected.index = expected.index.astype(np.float64) tm.assert_frame_equal(expected, result) @pytest.mark.parametrize("dtype", [None, object]) def test_raise_when_saving_timezones(self, dtype, tz_aware_fixture, path): # GH 27008, GH 7056 tz = tz_aware_fixture data = pd.Timestamp("2019", tz=tz) df = DataFrame([data], dtype=dtype) with pytest.raises(ValueError, match="Excel does not support"): df.to_excel(path) data = data.to_pydatetime() df = DataFrame([data], dtype=dtype) with pytest.raises(ValueError, match="Excel does not support"): df.to_excel(path) def test_excel_duplicate_columns_with_names(self, path): # GH#39695 df = DataFrame({"A": [0, 1], "B": [10, 11]}) df.to_excel(path, columns=["A", "B", "A"], index=False) result = pd.read_excel(path) expected = DataFrame([[0, 10, 0], [1, 11, 1]], columns=["A", "B", "A.1"]) tm.assert_frame_equal(result, expected) def test_if_sheet_exists_raises(self, ext): # GH 40230 msg = "if_sheet_exists is only valid in append mode (mode='a')" with tm.ensure_clean(ext) as f: with pytest.raises(ValueError, match=re.escape(msg)): ExcelWriter(f, if_sheet_exists="replace") class TestExcelWriterEngineTests: @pytest.mark.parametrize( "klass,ext", [ pytest.param(_XlsxWriter, ".xlsx", marks=td.skip_if_no("xlsxwriter")), pytest.param(_OpenpyxlWriter, ".xlsx", marks=td.skip_if_no("openpyxl")), pytest.param(_XlwtWriter, ".xls", marks=td.skip_if_no("xlwt")), ], ) def test_ExcelWriter_dispatch(self, klass, ext): with tm.ensure_clean(ext) as path: with ExcelWriter(path) as writer: if ext == ".xlsx" and td.safe_import("xlsxwriter"): # xlsxwriter has preference over openpyxl if both installed assert isinstance(writer, _XlsxWriter) else: assert isinstance(writer, klass) def test_ExcelWriter_dispatch_raises(self): with pytest.raises(ValueError, match="No engine"): ExcelWriter("nothing") def test_register_writer(self): # some awkward mocking to test out dispatch and such actually works called_save = [] called_write_cells = [] class DummyClass(ExcelWriter): called_save = False called_write_cells = False supported_extensions = ["xlsx", "xls"] engine = "dummy" def save(self): called_save.append(True) def write_cells(self, *args, **kwargs): called_write_cells.append(True) def check_called(func): func() assert len(called_save) >= 1 assert len(called_write_cells) >= 1 del called_save[:] del called_write_cells[:] with pd.option_context("io.excel.xlsx.writer", "dummy"): path = "something.xlsx" with tm.ensure_clean(path) as filepath: register_writer(DummyClass) with ExcelWriter(filepath) as writer: assert isinstance(writer, DummyClass) df = tm.makeCustomDataframe(1, 1) check_called(lambda: df.to_excel(filepath)) with tm.ensure_clean("something.xls") as filepath: check_called(lambda: df.to_excel(filepath, engine="dummy")) @pytest.mark.parametrize( "ext", [ pytest.param(".xlsx", marks=td.skip_if_no("xlsxwriter")), pytest.param(".xlsx", marks=td.skip_if_no("openpyxl")), pytest.param(".ods", marks=td.skip_if_no("odf")), ], ) def test_engine_kwargs_and_kwargs_raises(self, ext): # GH 40430 msg = re.escape("Cannot use both engine_kwargs and **kwargs") with pytest.raises(ValueError, match=msg): with ExcelWriter("", engine_kwargs={"a": 1}, b=2): pass @td.skip_if_no("xlrd") @td.skip_if_no("openpyxl") class TestFSPath: def test_excelfile_fspath(self): with tm.ensure_clean("foo.xlsx") as path: df = DataFrame({"A": [1, 2]}) df.to_excel(path) with ExcelFile(path) as xl: result = os.fspath(xl) assert result == path def test_excelwriter_fspath(self): with tm.ensure_clean("foo.xlsx") as path: with ExcelWriter(path) as writer: assert os.fspath(writer) == str(path)
from datetime import ( date, datetime, timedelta, ) from functools import partial from io import BytesIO import os import re import numpy as np import pytest import pandas.util._test_decorators as td import pandas as pd from pandas import ( DataFrame, Index, MultiIndex, get_option, set_option, ) import pandas._testing as tm from pandas.io.excel import ( ExcelFile, ExcelWriter, _OpenpyxlWriter, _XlsxWriter, _XlwtWriter, register_writer, ) @pytest.fixture def path(ext): """ Fixture to open file for use in each test case. """ with tm.ensure_clean(ext) as file_path: yield file_path @pytest.fixture def set_engine(engine, ext): """ Fixture to set engine for use in each test case. Rather than requiring `engine=...` to be provided explicitly as an argument in each test, this fixture sets a global option to dictate which engine should be used to write Excel files. After executing the test it rolls back said change to the global option. """ option_name = f"io.excel.{ext.strip('.')}.writer" prev_engine = get_option(option_name) set_option(option_name, engine) yield set_option(option_name, prev_engine) # Roll back option change @pytest.mark.parametrize( "ext", [ pytest.param(".xlsx", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")]), pytest.param(".xlsm", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")]), pytest.param(".xls", marks=[td.skip_if_no("xlwt"), td.skip_if_no("xlrd")]), pytest.param( ".xlsx", marks=[td.skip_if_no("xlsxwriter"), td.skip_if_no("xlrd")] ), pytest.param(".ods", marks=td.skip_if_no("odf")), ], ) class TestRoundTrip: @pytest.mark.parametrize( "header,expected", [(None, DataFrame([np.nan] * 4)), (0, DataFrame({"Unnamed: 0": [np.nan] * 3}))], ) def test_read_one_empty_col_no_header(self, ext, header, expected): # xref gh-12292 filename = "no_header" df = DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]]) with tm.ensure_clean(ext) as path: df.to_excel(path, filename, index=False, header=False) result = pd.read_excel( path, sheet_name=filename, usecols=[0], header=header ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "header,expected", [(None, DataFrame([0] + [np.nan] * 4)), (0, DataFrame([np.nan] * 4))], ) def test_read_one_empty_col_with_header(self, ext, header, expected): filename = "with_header" df = DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]]) with tm.ensure_clean(ext) as path: df.to_excel(path, "with_header", index=False, header=True) result = pd.read_excel( path, sheet_name=filename, usecols=[0], header=header ) tm.assert_frame_equal(result, expected) def test_set_column_names_in_parameter(self, ext): # GH 12870 : pass down column names associated with # keyword argument names refdf = DataFrame([[1, "foo"], [2, "bar"], [3, "baz"]], columns=["a", "b"]) with tm.ensure_clean(ext) as pth: with ExcelWriter(pth) as writer: refdf.to_excel(writer, "Data_no_head", header=False, index=False) refdf.to_excel(writer, "Data_with_head", index=False) refdf.columns = ["A", "B"] with ExcelFile(pth) as reader: xlsdf_no_head = pd.read_excel( reader, sheet_name="Data_no_head", header=None, names=["A", "B"] ) xlsdf_with_head = pd.read_excel( reader, sheet_name="Data_with_head", index_col=None, names=["A", "B"], ) tm.assert_frame_equal(xlsdf_no_head, refdf) tm.assert_frame_equal(xlsdf_with_head, refdf) def test_creating_and_reading_multiple_sheets(self, ext): # see gh-9450 # # Test reading multiple sheets, from a runtime # created Excel file with multiple sheets. def tdf(col_sheet_name): d, i = [11, 22, 33], [1, 2, 3] return DataFrame(d, i, columns=[col_sheet_name]) sheets = ["AAA", "BBB", "CCC"] dfs = [tdf(s) for s in sheets] dfs = dict(zip(sheets, dfs)) with tm.ensure_clean(ext) as pth: with ExcelWriter(pth) as ew: for sheetname, df in dfs.items(): df.to_excel(ew, sheetname) dfs_returned = pd.read_excel(pth, sheet_name=sheets, index_col=0) for s in sheets: tm.assert_frame_equal(dfs[s], dfs_returned[s]) def test_read_excel_multiindex_empty_level(self, ext): # see gh-12453 with tm.ensure_clean(ext) as path: df = DataFrame( { ("One", "x"): {0: 1}, ("Two", "X"): {0: 3}, ("Two", "Y"): {0: 7}, ("Zero", ""): {0: 0}, } ) expected = DataFrame( { ("One", "x"): {0: 1}, ("Two", "X"): {0: 3}, ("Two", "Y"): {0: 7}, ("Zero", "Unnamed: 4_level_1"): {0: 0}, } ) df.to_excel(path) actual = pd.read_excel(path, header=[0, 1], index_col=0) tm.assert_frame_equal(actual, expected) df = DataFrame( { ("Beg", ""): {0: 0}, ("Middle", "x"): {0: 1}, ("Tail", "X"): {0: 3}, ("Tail", "Y"): {0: 7}, } ) expected = DataFrame( { ("Beg", "Unnamed: 1_level_1"): {0: 0}, ("Middle", "x"): {0: 1}, ("Tail", "X"): {0: 3}, ("Tail", "Y"): {0: 7}, } ) df.to_excel(path) actual = pd.read_excel(path, header=[0, 1], index_col=0) tm.assert_frame_equal(actual, expected) @pytest.mark.parametrize("c_idx_names", [True, False]) @pytest.mark.parametrize("r_idx_names", [True, False]) @pytest.mark.parametrize("c_idx_levels", [1, 3]) @pytest.mark.parametrize("r_idx_levels", [1, 3]) def test_excel_multindex_roundtrip( self, ext, c_idx_names, r_idx_names, c_idx_levels, r_idx_levels, request ): # see gh-4679 with tm.ensure_clean(ext) as pth: if (c_idx_levels == 1 and c_idx_names) and not ( r_idx_levels == 3 and not r_idx_names ): mark = pytest.mark.xfail( reason="Column index name cannot be serialized unless " "it's a MultiIndex" ) request.node.add_marker(mark) # Empty name case current read in as # unnamed levels, not Nones. check_names = r_idx_names or r_idx_levels <= 1 df = tm.makeCustomDataframe( 5, 5, c_idx_names, r_idx_names, c_idx_levels, r_idx_levels ) df.to_excel(pth) act = pd.read_excel( pth, index_col=list(range(r_idx_levels)), header=list(range(c_idx_levels)), ) tm.assert_frame_equal(df, act, check_names=check_names) df.iloc[0, :] = np.nan df.to_excel(pth) act = pd.read_excel( pth, index_col=list(range(r_idx_levels)), header=list(range(c_idx_levels)), ) tm.assert_frame_equal(df, act, check_names=check_names) df.iloc[-1, :] = np.nan df.to_excel(pth) act = pd.read_excel( pth, index_col=list(range(r_idx_levels)), header=list(range(c_idx_levels)), ) tm.assert_frame_equal(df, act, check_names=check_names) def test_read_excel_parse_dates(self, ext): # see gh-11544, gh-12051 df = DataFrame( {"col": [1, 2, 3], "date_strings": pd.date_range("2012-01-01", periods=3)} ) df2 = df.copy() df2["date_strings"] = df2["date_strings"].dt.strftime("%m/%d/%Y") with tm.ensure_clean(ext) as pth: df2.to_excel(pth) res = pd.read_excel(pth, index_col=0) tm.assert_frame_equal(df2, res) res = pd.read_excel(pth, parse_dates=["date_strings"], index_col=0) tm.assert_frame_equal(df, res) date_parser = lambda x: datetime.strptime(x, "%m/%d/%Y") res = pd.read_excel( pth, parse_dates=["date_strings"], date_parser=date_parser, index_col=0 ) tm.assert_frame_equal(df, res) def test_multiindex_interval_datetimes(self, ext): # GH 30986 midx = MultiIndex.from_arrays( [ range(4), pd.interval_range( start=pd.Timestamp("2020-01-01"), periods=4, freq="6M" ), ] ) df = DataFrame(range(4), index=midx) with tm.ensure_clean(ext) as pth: df.to_excel(pth) result = pd.read_excel(pth, index_col=[0, 1]) expected = DataFrame( range(4), MultiIndex.from_arrays( [ range(4), [ "(2020-01-31, 2020-07-31]", "(2020-07-31, 2021-01-31]", "(2021-01-31, 2021-07-31]", "(2021-07-31, 2022-01-31]", ], ] ), ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "engine,ext", [ pytest.param( "openpyxl", ".xlsx", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")], ), pytest.param( "openpyxl", ".xlsm", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")], ), pytest.param( "xlwt", ".xls", marks=[td.skip_if_no("xlwt"), td.skip_if_no("xlrd")] ), pytest.param( "xlsxwriter", ".xlsx", marks=[td.skip_if_no("xlsxwriter"), td.skip_if_no("xlrd")], ), pytest.param("odf", ".ods", marks=td.skip_if_no("odf")), ], ) @pytest.mark.usefixtures("set_engine") class TestExcelWriter: def test_excel_sheet_size(self, path): # GH 26080 breaking_row_count = 2 ** 20 + 1 breaking_col_count = 2 ** 14 + 1 # purposely using two arrays to prevent memory issues while testing row_arr = np.zeros(shape=(breaking_row_count, 1)) col_arr = np.zeros(shape=(1, breaking_col_count)) row_df = DataFrame(row_arr) col_df = DataFrame(col_arr) msg = "sheet is too large" with pytest.raises(ValueError, match=msg): row_df.to_excel(path) with pytest.raises(ValueError, match=msg): col_df.to_excel(path) def test_excel_sheet_by_name_raise(self, path, engine): gt = DataFrame(np.random.randn(10, 2)) gt.to_excel(path) with ExcelFile(path) as xl: df = pd.read_excel(xl, sheet_name=0, index_col=0) tm.assert_frame_equal(gt, df) msg = "Worksheet named '0' not found" with pytest.raises(ValueError, match=msg): pd.read_excel(xl, "0") def test_excel_writer_context_manager(self, frame, path): with ExcelWriter(path) as writer: frame.to_excel(writer, "Data1") frame2 = frame.copy() frame2.columns = frame.columns[::-1] frame2.to_excel(writer, "Data2") with ExcelFile(path) as reader: found_df = pd.read_excel(reader, sheet_name="Data1", index_col=0) found_df2 = pd.read_excel(reader, sheet_name="Data2", index_col=0) tm.assert_frame_equal(found_df, frame) tm.assert_frame_equal(found_df2, frame2) def test_roundtrip(self, frame, path): frame = frame.copy() frame["A"][:5] = np.nan frame.to_excel(path, "test1") frame.to_excel(path, "test1", columns=["A", "B"]) frame.to_excel(path, "test1", header=False) frame.to_excel(path, "test1", index=False) # test roundtrip frame.to_excel(path, "test1") recons = pd.read_excel(path, sheet_name="test1", index_col=0) tm.assert_frame_equal(frame, recons) frame.to_excel(path, "test1", index=False) recons = pd.read_excel(path, sheet_name="test1", index_col=None) recons.index = frame.index tm.assert_frame_equal(frame, recons) frame.to_excel(path, "test1", na_rep="NA") recons = pd.read_excel(path, sheet_name="test1", index_col=0, na_values=["NA"]) tm.assert_frame_equal(frame, recons) # GH 3611 frame.to_excel(path, "test1", na_rep="88") recons = pd.read_excel(path, sheet_name="test1", index_col=0, na_values=["88"]) tm.assert_frame_equal(frame, recons) frame.to_excel(path, "test1", na_rep="88") recons = pd.read_excel( path, sheet_name="test1", index_col=0, na_values=[88, 88.0] ) tm.assert_frame_equal(frame, recons) # GH 6573 frame.to_excel(path, "Sheet1") recons = pd.read_excel(path, index_col=0) tm.assert_frame_equal(frame, recons) frame.to_excel(path, "0") recons = pd.read_excel(path, index_col=0) tm.assert_frame_equal(frame, recons) # GH 8825 Pandas Series should provide to_excel method s = frame["A"] s.to_excel(path) recons = pd.read_excel(path, index_col=0) tm.assert_frame_equal(s.to_frame(), recons) def test_mixed(self, frame, path): mixed_frame = frame.copy() mixed_frame["foo"] = "bar" mixed_frame.to_excel(path, "test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(mixed_frame, recons) def test_ts_frame(self, tsframe, path): df = tsframe # freq doesn't round-trip index = pd.DatetimeIndex(np.asarray(df.index), freq=None) df.index = index df.to_excel(path, "test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(df, recons) def test_basics_with_nan(self, frame, path): frame = frame.copy() frame["A"][:5] = np.nan frame.to_excel(path, "test1") frame.to_excel(path, "test1", columns=["A", "B"]) frame.to_excel(path, "test1", header=False) frame.to_excel(path, "test1", index=False) @pytest.mark.parametrize("np_type", [np.int8, np.int16, np.int32, np.int64]) def test_int_types(self, np_type, path): # Test np.int values read come back as int # (rather than float which is Excel's format). df = DataFrame(np.random.randint(-10, 10, size=(10, 2)), dtype=np_type) df.to_excel(path, "test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) int_frame = df.astype(np.int64) tm.assert_frame_equal(int_frame, recons) recons2 = pd.read_excel(path, sheet_name="test1", index_col=0) tm.assert_frame_equal(int_frame, recons2) # Test with convert_float=False comes back as float. float_frame = df.astype(float) float_frame.columns = float_frame.columns.astype(float) float_frame.index = float_frame.index.astype(float) with tm.assert_produces_warning( FutureWarning, match="convert_float is deprecated" ): recons = pd.read_excel( path, sheet_name="test1", convert_float=False, index_col=0 ) tm.assert_frame_equal(recons, float_frame) @pytest.mark.parametrize("np_type", [np.float16, np.float32, np.float64]) def test_float_types(self, np_type, path): # Test np.float values read come back as float. df = DataFrame(np.random.random_sample(10), dtype=np_type) df.to_excel(path, "test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( np_type ) tm.assert_frame_equal(df, recons) @pytest.mark.parametrize("np_type", [np.bool8, np.bool_]) def test_bool_types(self, np_type, path): # Test np.bool8 and np.bool_ values read come back as float. df = DataFrame([1, 0, True, False], dtype=np_type) df.to_excel(path, "test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( np_type ) tm.assert_frame_equal(df, recons) def test_inf_roundtrip(self, path): df = DataFrame([(1, np.inf), (2, 3), (5, -np.inf)]) df.to_excel(path, "test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(df, recons) def test_sheets(self, frame, tsframe, path): # freq doesn't round-trip index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None) tsframe.index = index frame = frame.copy() frame["A"][:5] = np.nan frame.to_excel(path, "test1") frame.to_excel(path, "test1", columns=["A", "B"]) frame.to_excel(path, "test1", header=False) frame.to_excel(path, "test1", index=False) # Test writing to separate sheets with ExcelWriter(path) as writer: frame.to_excel(writer, "test1") tsframe.to_excel(writer, "test2") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(frame, recons) recons = pd.read_excel(reader, sheet_name="test2", index_col=0) tm.assert_frame_equal(tsframe, recons) assert 2 == len(reader.sheet_names) assert "test1" == reader.sheet_names[0] assert "test2" == reader.sheet_names[1] def test_colaliases(self, frame, path): frame = frame.copy() frame["A"][:5] = np.nan frame.to_excel(path, "test1") frame.to_excel(path, "test1", columns=["A", "B"]) frame.to_excel(path, "test1", header=False) frame.to_excel(path, "test1", index=False) # column aliases col_aliases = Index(["AA", "X", "Y", "Z"]) frame.to_excel(path, "test1", header=col_aliases) with ExcelFile(path) as reader: rs = pd.read_excel(reader, sheet_name="test1", index_col=0) xp = frame.copy() xp.columns = col_aliases tm.assert_frame_equal(xp, rs) def test_roundtrip_indexlabels(self, merge_cells, frame, path): frame = frame.copy() frame["A"][:5] = np.nan frame.to_excel(path, "test1") frame.to_excel(path, "test1", columns=["A", "B"]) frame.to_excel(path, "test1", header=False) frame.to_excel(path, "test1", index=False) # test index_label df = DataFrame(np.random.randn(10, 2)) >= 0 df.to_excel(path, "test1", index_label=["test"], merge_cells=merge_cells) with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( np.int64 ) df.index.names = ["test"] assert df.index.names == recons.index.names df = DataFrame(np.random.randn(10, 2)) >= 0 df.to_excel( path, "test1", index_label=["test", "dummy", "dummy2"], merge_cells=merge_cells, ) with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( np.int64 ) df.index.names = ["test"] assert df.index.names == recons.index.names df = DataFrame(np.random.randn(10, 2)) >= 0 df.to_excel(path, "test1", index_label="test", merge_cells=merge_cells) with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( np.int64 ) df.index.names = ["test"] tm.assert_frame_equal(df, recons.astype(bool)) frame.to_excel( path, "test1", columns=["A", "B", "C", "D"], index=False, merge_cells=merge_cells, ) # take 'A' and 'B' as indexes (same row as cols 'C', 'D') df = frame.copy() df = df.set_index(["A", "B"]) with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1]) tm.assert_frame_equal(df, recons) def test_excel_roundtrip_indexname(self, merge_cells, path): df = DataFrame(np.random.randn(10, 4)) df.index.name = "foo" df.to_excel(path, merge_cells=merge_cells) with ExcelFile(path) as xf: result = pd.read_excel(xf, sheet_name=xf.sheet_names[0], index_col=0) tm.assert_frame_equal(result, df) assert result.index.name == "foo" def test_excel_roundtrip_datetime(self, merge_cells, tsframe, path): # datetime.date, not sure what to test here exactly # freq does not round-trip index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None) tsframe.index = index tsf = tsframe.copy() tsf.index = [x.date() for x in tsframe.index] tsf.to_excel(path, "test1", merge_cells=merge_cells) with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(tsframe, recons) def test_excel_date_datetime_format(self, engine, ext, path): # see gh-4133 # # Excel output format strings df = DataFrame( [ [date(2014, 1, 31), date(1999, 9, 24)], [datetime(1998, 5, 26, 23, 33, 4), datetime(2014, 2, 28, 13, 5, 13)], ], index=["DATE", "DATETIME"], columns=["X", "Y"], ) df_expected = DataFrame( [ [datetime(2014, 1, 31), datetime(1999, 9, 24)], [datetime(1998, 5, 26, 23, 33, 4), datetime(2014, 2, 28, 13, 5, 13)], ], index=["DATE", "DATETIME"], columns=["X", "Y"], ) with tm.ensure_clean(ext) as filename2: with ExcelWriter(path) as writer1: df.to_excel(writer1, "test1") with ExcelWriter( filename2, date_format="DD.MM.YYYY", datetime_format="DD.MM.YYYY HH-MM-SS", ) as writer2: df.to_excel(writer2, "test1") with ExcelFile(path) as reader1: rs1 = pd.read_excel(reader1, sheet_name="test1", index_col=0) with ExcelFile(filename2) as reader2: rs2 = pd.read_excel(reader2, sheet_name="test1", index_col=0) tm.assert_frame_equal(rs1, rs2) # Since the reader returns a datetime object for dates, # we need to use df_expected to check the result. tm.assert_frame_equal(rs2, df_expected) def test_to_excel_interval_no_labels(self, path): # see gh-19242 # # Test writing Interval without labels. df = DataFrame(np.random.randint(-10, 10, size=(20, 1)), dtype=np.int64) expected = df.copy() df["new"] = pd.cut(df[0], 10) expected["new"] = pd.cut(expected[0], 10).astype(str) df.to_excel(path, "test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(expected, recons) def test_to_excel_interval_labels(self, path): # see gh-19242 # # Test writing Interval with labels. df = DataFrame(np.random.randint(-10, 10, size=(20, 1)), dtype=np.int64) expected = df.copy() intervals = pd.cut( df[0], 10, labels=["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] ) df["new"] = intervals expected["new"] = pd.Series(list(intervals)) df.to_excel(path, "test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(expected, recons) def test_to_excel_timedelta(self, path): # see gh-19242, gh-9155 # # Test writing timedelta to xls. df = DataFrame( np.random.randint(-10, 10, size=(20, 1)), columns=["A"], dtype=np.int64 ) expected = df.copy() df["new"] = df["A"].apply(lambda x: timedelta(seconds=x)) expected["new"] = expected["A"].apply( lambda x: timedelta(seconds=x).total_seconds() / 86400 ) df.to_excel(path, "test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(expected, recons) def test_to_excel_periodindex(self, tsframe, path): xp = tsframe.resample("M", kind="period").mean() xp.to_excel(path, "sht1") with ExcelFile(path) as reader: rs = pd.read_excel(reader, sheet_name="sht1", index_col=0) tm.assert_frame_equal(xp, rs.to_period("M")) def test_to_excel_multiindex(self, merge_cells, frame, path): arrays = np.arange(len(frame.index) * 2).reshape(2, -1) new_index = MultiIndex.from_arrays(arrays, names=["first", "second"]) frame.index = new_index frame.to_excel(path, "test1", header=False) frame.to_excel(path, "test1", columns=["A", "B"]) # round trip frame.to_excel(path, "test1", merge_cells=merge_cells) with ExcelFile(path) as reader: df = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1]) tm.assert_frame_equal(frame, df) # GH13511 def test_to_excel_multiindex_nan_label(self, merge_cells, path): df = DataFrame({"A": [None, 2, 3], "B": [10, 20, 30], "C": np.random.sample(3)}) df = df.set_index(["A", "B"]) df.to_excel(path, merge_cells=merge_cells) df1 = pd.read_excel(path, index_col=[0, 1]) tm.assert_frame_equal(df, df1) # Test for Issue 11328. If column indices are integers, make # sure they are handled correctly for either setting of # merge_cells def test_to_excel_multiindex_cols(self, merge_cells, frame, path): arrays = np.arange(len(frame.index) * 2).reshape(2, -1) new_index = MultiIndex.from_arrays(arrays, names=["first", "second"]) frame.index = new_index new_cols_index = MultiIndex.from_tuples([(40, 1), (40, 2), (50, 1), (50, 2)]) frame.columns = new_cols_index header = [0, 1] if not merge_cells: header = 0 # round trip frame.to_excel(path, "test1", merge_cells=merge_cells) with ExcelFile(path) as reader: df = pd.read_excel( reader, sheet_name="test1", header=header, index_col=[0, 1] ) if not merge_cells: fm = frame.columns.format(sparsify=False, adjoin=False, names=False) frame.columns = [".".join(map(str, q)) for q in zip(*fm)] tm.assert_frame_equal(frame, df) def test_to_excel_multiindex_dates(self, merge_cells, tsframe, path): # try multiindex with dates new_index = [tsframe.index, np.arange(len(tsframe.index))] tsframe.index = MultiIndex.from_arrays(new_index) tsframe.index.names = ["time", "foo"] tsframe.to_excel(path, "test1", merge_cells=merge_cells) with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1]) tm.assert_frame_equal(tsframe, recons) assert recons.index.names == ("time", "foo") def test_to_excel_multiindex_no_write_index(self, path): # Test writing and re-reading a MI without the index. GH 5616. # Initial non-MI frame. frame1 = DataFrame({"a": [10, 20], "b": [30, 40], "c": [50, 60]}) # Add a MI. frame2 = frame1.copy() multi_index = MultiIndex.from_tuples([(70, 80), (90, 100)]) frame2.index = multi_index # Write out to Excel without the index. frame2.to_excel(path, "test1", index=False) # Read it back in. with ExcelFile(path) as reader: frame3 = pd.read_excel(reader, sheet_name="test1") # Test that it is the same as the initial frame. tm.assert_frame_equal(frame1, frame3) def test_to_excel_float_format(self, path): df = DataFrame( [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], index=["A", "B"], columns=["X", "Y", "Z"], ) df.to_excel(path, "test1", float_format="%.2f") with ExcelFile(path) as reader: result = pd.read_excel(reader, sheet_name="test1", index_col=0) expected = DataFrame( [[0.12, 0.23, 0.57], [12.32, 123123.20, 321321.20]], index=["A", "B"], columns=["X", "Y", "Z"], ) tm.assert_frame_equal(result, expected) def test_to_excel_output_encoding(self, ext): # Avoid mixed inferred_type. df = DataFrame( [["\u0192", "\u0193", "\u0194"], ["\u0195", "\u0196", "\u0197"]], index=["A\u0192", "B"], columns=["X\u0193", "Y", "Z"], ) with tm.ensure_clean("__tmp_to_excel_float_format__." + ext) as filename: df.to_excel(filename, sheet_name="TestSheet", encoding="utf8") result = pd.read_excel(filename, sheet_name="TestSheet", index_col=0) tm.assert_frame_equal(result, df) def test_to_excel_unicode_filename(self, ext, path): with tm.ensure_clean("\u0192u." + ext) as filename: try: f = open(filename, "wb") except UnicodeEncodeError: pytest.skip("No unicode file names on this system") finally: f.close() df = DataFrame( [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], index=["A", "B"], columns=["X", "Y", "Z"], ) df.to_excel(filename, "test1", float_format="%.2f") with ExcelFile(filename) as reader: result = pd.read_excel(reader, sheet_name="test1", index_col=0) expected = DataFrame( [[0.12, 0.23, 0.57], [12.32, 123123.20, 321321.20]], index=["A", "B"], columns=["X", "Y", "Z"], ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("use_headers", [True, False]) @pytest.mark.parametrize("r_idx_nlevels", [1, 2, 3]) @pytest.mark.parametrize("c_idx_nlevels", [1, 2, 3]) def test_excel_010_hemstring( self, merge_cells, c_idx_nlevels, r_idx_nlevels, use_headers, path ): def roundtrip(data, header=True, parser_hdr=0, index=True): data.to_excel(path, header=header, merge_cells=merge_cells, index=index) with ExcelFile(path) as xf: return pd.read_excel( xf, sheet_name=xf.sheet_names[0], header=parser_hdr ) # Basic test. parser_header = 0 if use_headers else None res = roundtrip(DataFrame([0]), use_headers, parser_header) assert res.shape == (1, 2) assert res.iloc[0, 0] is not np.nan # More complex tests with multi-index. nrows = 5 ncols = 3 # ensure limited functionality in 0.10 # override of gh-2370 until sorted out in 0.11 df = tm.makeCustomDataframe( nrows, ncols, r_idx_nlevels=r_idx_nlevels, c_idx_nlevels=c_idx_nlevels ) # This if will be removed once multi-column Excel writing # is implemented. For now fixing gh-9794. if c_idx_nlevels > 1: msg = ( "Writing to Excel with MultiIndex columns and no index " "\\('index'=False\\) is not yet implemented." ) with pytest.raises(NotImplementedError, match=msg): roundtrip(df, use_headers, index=False) else: res = roundtrip(df, use_headers) if use_headers: assert res.shape == (nrows, ncols + r_idx_nlevels) else: # First row taken as columns. assert res.shape == (nrows - 1, ncols + r_idx_nlevels) # No NaNs. for r in range(len(res.index)): for c in range(len(res.columns)): assert res.iloc[r, c] is not np.nan def test_duplicated_columns(self, path): # see gh-5235 df = DataFrame([[1, 2, 3], [1, 2, 3], [1, 2, 3]], columns=["A", "B", "B"]) df.to_excel(path, "test1") expected = DataFrame( [[1, 2, 3], [1, 2, 3], [1, 2, 3]], columns=["A", "B", "B.1"] ) # By default, we mangle. result = pd.read_excel(path, sheet_name="test1", index_col=0) tm.assert_frame_equal(result, expected) # Explicitly, we pass in the parameter. result = pd.read_excel( path, sheet_name="test1", index_col=0, mangle_dupe_cols=True ) tm.assert_frame_equal(result, expected) # see gh-11007, gh-10970 df = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "A", "B"]) df.to_excel(path, "test1") result = pd.read_excel(path, sheet_name="test1", index_col=0) expected = DataFrame( [[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "A.1", "B.1"] ) tm.assert_frame_equal(result, expected) # see gh-10982 df.to_excel(path, "test1", index=False, header=False) result = pd.read_excel(path, sheet_name="test1", header=None) expected = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]]) tm.assert_frame_equal(result, expected) msg = "Setting mangle_dupe_cols=False is not supported yet" with pytest.raises(ValueError, match=msg): pd.read_excel(path, sheet_name="test1", header=None, mangle_dupe_cols=False) def test_swapped_columns(self, path): # Test for issue #5427. write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2]}) write_frame.to_excel(path, "test1", columns=["B", "A"]) read_frame = pd.read_excel(path, sheet_name="test1", header=0) tm.assert_series_equal(write_frame["A"], read_frame["A"]) tm.assert_series_equal(write_frame["B"], read_frame["B"]) def test_invalid_columns(self, path): # see gh-10982 write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2]}) with pytest.raises(KeyError, match="Not all names specified"): write_frame.to_excel(path, "test1", columns=["B", "C"]) with pytest.raises( KeyError, match="'passes columns are not ALL present dataframe'" ): write_frame.to_excel(path, "test1", columns=["C", "D"]) @pytest.mark.parametrize( "to_excel_index,read_excel_index_col", [ (True, 0), # Include index in write to file (False, None), # Dont include index in write to file ], ) def test_write_subset_columns(self, path, to_excel_index, read_excel_index_col): # GH 31677 write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2], "C": [3, 3, 3]}) write_frame.to_excel( path, "col_subset_bug", columns=["A", "B"], index=to_excel_index ) expected = write_frame[["A", "B"]] read_frame = pd.read_excel( path, sheet_name="col_subset_bug", index_col=read_excel_index_col ) tm.assert_frame_equal(expected, read_frame) def test_comment_arg(self, path): # see gh-18735 # # Test the comment argument functionality to pd.read_excel. # Create file to read in. df = DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]}) df.to_excel(path, "test_c") # Read file without comment arg. result1 = pd.read_excel(path, sheet_name="test_c", index_col=0) result1.iloc[1, 0] = None result1.iloc[1, 1] = None result1.iloc[2, 1] = None result2 = pd.read_excel(path, sheet_name="test_c", comment="#", index_col=0) tm.assert_frame_equal(result1, result2) def test_comment_default(self, path): # Re issue #18735 # Test the comment argument default to pd.read_excel # Create file to read in df = DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]}) df.to_excel(path, "test_c") # Read file with default and explicit comment=None result1 = pd.read_excel(path, sheet_name="test_c") result2 = pd.read_excel(path, sheet_name="test_c", comment=None) tm.assert_frame_equal(result1, result2) def test_comment_used(self, path): # see gh-18735 # # Test the comment argument is working as expected when used. # Create file to read in. df = DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]}) df.to_excel(path, "test_c") # Test read_frame_comment against manually produced expected output. expected = DataFrame({"A": ["one", None, "one"], "B": ["two", None, None]}) result = pd.read_excel(path, sheet_name="test_c", comment="#", index_col=0) tm.assert_frame_equal(result, expected) def test_comment_empty_line(self, path): # Re issue #18735 # Test that pd.read_excel ignores commented lines at the end of file df = DataFrame({"a": ["1", "#2"], "b": ["2", "3"]}) df.to_excel(path, index=False) # Test that all-comment lines at EoF are ignored expected = DataFrame({"a": [1], "b": [2]}) result = pd.read_excel(path, comment="#") tm.assert_frame_equal(result, expected) def test_datetimes(self, path): # Test writing and reading datetimes. For issue #9139. (xref #9185) datetimes = [ datetime(2013, 1, 13, 1, 2, 3), datetime(2013, 1, 13, 2, 45, 56), datetime(2013, 1, 13, 4, 29, 49), datetime(2013, 1, 13, 6, 13, 42), datetime(2013, 1, 13, 7, 57, 35), datetime(2013, 1, 13, 9, 41, 28), datetime(2013, 1, 13, 11, 25, 21), datetime(2013, 1, 13, 13, 9, 14), datetime(2013, 1, 13, 14, 53, 7), datetime(2013, 1, 13, 16, 37, 0), datetime(2013, 1, 13, 18, 20, 52), ] write_frame = DataFrame({"A": datetimes}) write_frame.to_excel(path, "Sheet1") if path.endswith("xlsx") or path.endswith("xlsm"): pytest.skip( "Defaults to openpyxl and fails with floating point error on " "datetimes; may be fixed on newer versions of openpyxl - GH #38644" ) read_frame = pd.read_excel(path, sheet_name="Sheet1", header=0) tm.assert_series_equal(write_frame["A"], read_frame["A"]) def test_bytes_io(self, engine): # see gh-7074 with BytesIO() as bio: df = DataFrame(np.random.randn(10, 2)) # Pass engine explicitly, as there is no file path to infer from. with ExcelWriter(bio, engine=engine) as writer: df.to_excel(writer) bio.seek(0) reread_df = pd.read_excel(bio, index_col=0) tm.assert_frame_equal(df, reread_df) def test_write_lists_dict(self, path): # see gh-8188. df = DataFrame( { "mixed": ["a", ["b", "c"], {"d": "e", "f": 2}], "numeric": [1, 2, 3.0], "str": ["apple", "banana", "cherry"], } ) df.to_excel(path, "Sheet1") read = pd.read_excel(path, sheet_name="Sheet1", header=0, index_col=0) expected = df.copy() expected.mixed = expected.mixed.apply(str) expected.numeric = expected.numeric.astype("int64") tm.assert_frame_equal(read, expected) def test_render_as_column_name(self, path): # see gh-34331 df = DataFrame({"render": [1, 2], "data": [3, 4]}) df.to_excel(path, "Sheet1") read = pd.read_excel(path, "Sheet1", index_col=0) expected = df tm.assert_frame_equal(read, expected) def test_true_and_false_value_options(self, path): # see gh-13347 df = DataFrame([["foo", "bar"]], columns=["col1", "col2"]) expected = df.replace({"foo": True, "bar": False}) df.to_excel(path) read_frame = pd.read_excel( path, true_values=["foo"], false_values=["bar"], index_col=0 ) tm.assert_frame_equal(read_frame, expected) def test_freeze_panes(self, path): # see gh-15160 expected = DataFrame([[1, 2], [3, 4]], columns=["col1", "col2"]) expected.to_excel(path, "Sheet1", freeze_panes=(1, 1)) result = pd.read_excel(path, index_col=0) tm.assert_frame_equal(result, expected) def test_path_path_lib(self, engine, ext): df = tm.makeDataFrame() writer = partial(df.to_excel, engine=engine) reader = partial(pd.read_excel, index_col=0) result = tm.round_trip_pathlib(writer, reader, path=f"foo{ext}") tm.assert_frame_equal(result, df) def test_path_local_path(self, engine, ext): df = tm.makeDataFrame() writer = partial(df.to_excel, engine=engine) reader = partial(pd.read_excel, index_col=0) result = tm.round_trip_localpath(writer, reader, path=f"foo{ext}") tm.assert_frame_equal(result, df) def test_merged_cell_custom_objects(self, merge_cells, path): # see GH-27006 mi = MultiIndex.from_tuples( [ (pd.Period("2018"), pd.Period("2018Q1")), (pd.Period("2018"), pd.Period("2018Q2")), ] ) expected = DataFrame(np.ones((2, 2)), columns=mi) expected.to_excel(path) with tm.assert_produces_warning( FutureWarning, match="convert_float is deprecated" ): result = pd.read_excel( path, header=[0, 1], index_col=0, convert_float=False ) # need to convert PeriodIndexes to standard Indexes for assert equal expected.columns = expected.columns.set_levels( [[str(i) for i in mi.levels[0]], [str(i) for i in mi.levels[1]]], level=[0, 1], ) expected.index = expected.index.astype(np.float64) tm.assert_frame_equal(expected, result) @pytest.mark.parametrize("dtype", [None, object]) def test_raise_when_saving_timezones(self, dtype, tz_aware_fixture, path): # GH 27008, GH 7056 tz = tz_aware_fixture data = pd.Timestamp("2019", tz=tz) df = DataFrame([data], dtype=dtype) with pytest.raises(ValueError, match="Excel does not support"): df.to_excel(path) data = data.to_pydatetime() df = DataFrame([data], dtype=dtype) with pytest.raises(ValueError, match="Excel does not support"): df.to_excel(path) def test_excel_duplicate_columns_with_names(self, path): # GH#39695 df = DataFrame({"A": [0, 1], "B": [10, 11]}) df.to_excel(path, columns=["A", "B", "A"], index=False) result = pd.read_excel(path) expected = DataFrame([[0, 10, 0], [1, 11, 1]], columns=["A", "B", "A.1"]) tm.assert_frame_equal(result, expected) def test_if_sheet_exists_raises(self, ext): # GH 40230 msg = "if_sheet_exists is only valid in append mode (mode='a')" with tm.ensure_clean(ext) as f: with pytest.raises(ValueError, match=re.escape(msg)): ExcelWriter(f, if_sheet_exists="replace") class TestExcelWriterEngineTests: @pytest.mark.parametrize( "klass,ext", [ pytest.param(_XlsxWriter, ".xlsx", marks=td.skip_if_no("xlsxwriter")), pytest.param(_OpenpyxlWriter, ".xlsx", marks=td.skip_if_no("openpyxl")), pytest.param(_XlwtWriter, ".xls", marks=td.skip_if_no("xlwt")), ], ) def test_ExcelWriter_dispatch(self, klass, ext): with tm.ensure_clean(ext) as path: with ExcelWriter(path) as writer: if ext == ".xlsx" and td.safe_import("xlsxwriter"): # xlsxwriter has preference over openpyxl if both installed assert isinstance(writer, _XlsxWriter) else: assert isinstance(writer, klass) def test_ExcelWriter_dispatch_raises(self): with pytest.raises(ValueError, match="No engine"): ExcelWriter("nothing") def test_register_writer(self): # some awkward mocking to test out dispatch and such actually works called_save = [] called_write_cells = [] class DummyClass(ExcelWriter): called_save = False called_write_cells = False supported_extensions = ["xlsx", "xls"] engine = "dummy" def save(self): called_save.append(True) def write_cells(self, *args, **kwargs): called_write_cells.append(True) def check_called(func): func() assert len(called_save) >= 1 assert len(called_write_cells) >= 1 del called_save[:] del called_write_cells[:] with pd.option_context("io.excel.xlsx.writer", "dummy"): path = "something.xlsx" with tm.ensure_clean(path) as filepath: register_writer(DummyClass) with ExcelWriter(filepath) as writer: assert isinstance(writer, DummyClass) df = tm.makeCustomDataframe(1, 1) check_called(lambda: df.to_excel(filepath)) with tm.ensure_clean("something.xls") as filepath: check_called(lambda: df.to_excel(filepath, engine="dummy")) @pytest.mark.parametrize( "ext", [ pytest.param(".xlsx", marks=td.skip_if_no("xlsxwriter")), pytest.param(".xlsx", marks=td.skip_if_no("openpyxl")), pytest.param(".ods", marks=td.skip_if_no("odf")), ], ) def test_engine_kwargs_and_kwargs_raises(self, ext): # GH 40430 msg = re.escape("Cannot use both engine_kwargs and **kwargs") with pytest.raises(ValueError, match=msg): with ExcelWriter("", engine_kwargs={"a": 1}, b=2): pass @td.skip_if_no("xlrd") @td.skip_if_no("openpyxl") class TestFSPath: def test_excelfile_fspath(self): with tm.ensure_clean("foo.xlsx") as path: df = DataFrame({"A": [1, 2]}) df.to_excel(path) with ExcelFile(path) as xl: result = os.fspath(xl) assert result == path def test_excelwriter_fspath(self): with tm.ensure_clean("foo.xlsx") as path: with ExcelWriter(path) as writer: assert os.fspath(writer) == str(path)
from typing import Tuple import pygame from pygame_gui import UIManager import pygame_gui from pygame_gui.elements.ui_window import UIWindow from pygame_gui.elements.ui_text_box import UITextBox from talktown.person.person import Person from talktown.place import Building class CharacterInfoWindow(UIWindow): """ Wraps a pygame_ui panel to display information about a given character """ __slots__ = 'character', 'ui_manager', 'panel' def __init__(self, character: 'Person', position: Tuple[int, int], ui_manager: 'UIManager') -> None: super().__init__( pygame.Rect(position, (320, 240)), ui_manager, window_display_title=character.name, object_id=f'{character.id}') self.character = character self.ui_manager = ui_manager self.text = UITextBox( f"name: {character.name}<br>" f"age: {round(character.age)}<br>" f"gender: {character.gender}<br>" f"occupation: {character.occupation if character.occupation else "None"}<br>", pygame.Rect(0, 0, 320, 240), manager=ui_manager, container=self, parent_element=self, ) def process_event(self, event: pygame.event.Event) -> bool: handled = super().process_event(event) if ( event.type == pygame.USEREVENT and event.user_type == pygame_gui.UI_BUTTON_PRESSED and event.ui_object_id == "#character_window.#title_bar" and event.ui_element == self.title_bar ): handled = True event_data = { 'user_type': 'character_window_selected', 'ui_element': self, 'ui_object_id': self.most_specific_combined_id } window_selected_event = pygame.event.Event( pygame.USEREVENT, event_data) pygame.event.post(window_selected_event) return handled class BuildingInfoWindow(UIWindow): """ Wraps a pygame_ui panel to display information about a given building """ def __init__(self, building: 'Building', ui_manager: 'UIManager') -> None: super().__init__( pygame.Rect((10, 10), (320, 240)), ui_manager, window_display_title=building.building_type, object_id=f'building_win') # # class BusinessInfoWindow(UIWindow): # """ # Wraps a pygame_ui panel to display information # about a given business # """ # # def __init__(self, business: 'Business', sim: 'Simulation') -> None: # pass # # # class ResidenceInfoWindow(UIWindow): # """ # Wraps a pygame_ui panel to display information # about a given residence # """ # # def __init__(self, residence: 'Residence') -> None: # pass def show_building_window(building: 'Building', ui_manager: UIManager) -> UIWindow: """Creates a UIWindow for the given building""" return BuildingInfoWindow(building, ui_manager)
from typing import Tuple import pygame from pygame_gui import UIManager import pygame_gui from pygame_gui.elements.ui_window import UIWindow from pygame_gui.elements.ui_text_box import UITextBox from talktown.person.person import Person from talktown.place import Building class CharacterInfoWindow(UIWindow): """ Wraps a pygame_ui panel to display information about a given character """ __slots__ = 'character', 'ui_manager', 'panel' def __init__(self, character: 'Person', position: Tuple[int, int], ui_manager: 'UIManager') -> None: super().__init__( pygame.Rect(position, (320, 240)), ui_manager, window_display_title=character.name, object_id=f'{character.id}') self.character = character self.ui_manager = ui_manager self.text = UITextBox( f"name: {character.name}<br>" f"age: {round(character.age)}<br>" f"gender: {character.gender}<br>" f"occupation: {character.occupation if character.occupation else 'None'}<br>", pygame.Rect(0, 0, 320, 240), manager=ui_manager, container=self, parent_element=self, ) def process_event(self, event: pygame.event.Event) -> bool: handled = super().process_event(event) if ( event.type == pygame.USEREVENT and event.user_type == pygame_gui.UI_BUTTON_PRESSED and event.ui_object_id == "#character_window.#title_bar" and event.ui_element == self.title_bar ): handled = True event_data = { 'user_type': 'character_window_selected', 'ui_element': self, 'ui_object_id': self.most_specific_combined_id } window_selected_event = pygame.event.Event( pygame.USEREVENT, event_data) pygame.event.post(window_selected_event) return handled class BuildingInfoWindow(UIWindow): """ Wraps a pygame_ui panel to display information about a given building """ def __init__(self, building: 'Building', ui_manager: 'UIManager') -> None: super().__init__( pygame.Rect((10, 10), (320, 240)), ui_manager, window_display_title=building.building_type, object_id=f'building_win') # # class BusinessInfoWindow(UIWindow): # """ # Wraps a pygame_ui panel to display information # about a given business # """ # # def __init__(self, business: 'Business', sim: 'Simulation') -> None: # pass # # # class ResidenceInfoWindow(UIWindow): # """ # Wraps a pygame_ui panel to display information # about a given residence # """ # # def __init__(self, residence: 'Residence') -> None: # pass def show_building_window(building: 'Building', ui_manager: UIManager) -> UIWindow: """Creates a UIWindow for the given building""" return BuildingInfoWindow(building, ui_manager)