Full text
UNIVERSITY OF COLORADO BOULDER BACHELOR THESIS Big Data Analytics on Container-Orchestrated Systems Author: Gerard Casas Saez Supervisor: Kenneth M. Anderson A thesis submitted in fulfillment of the requirements for Bachelor’s degree in Informatics Engineering in Facultat d’Informàtica de Barcelona Universitat Politècnica de Catalunya July 13, 2017
iii University of Colorado Boulder Abstract Big Data Analytics on Container-Orchestrated Systems by Gerard Casas Saez Container-orchestration systems offer new possibilites to software architects seeking to make their software systems more scalable and reliable. In the past, these systems have been used to implement transactional software systems but, more recently, they have been applied to other areas including big data analytics. To understand the advantages and limitations such systems impose on software architects, I migrated an existing big data analytics infrastructure from a software architecture that required lots of work from its developers to deploy and maintain to the new software architecture provided by container-orchestration systems. My results show that scalability is increased, maintenance costs are reduced, and reliability is easier to achieve.
v Acknowledgements I would first like to thank my thesis advisor, Prof. Kenneth M. Anderson. Thanks to his support I had the opportunity to come to Boulder and work on this thesis. This thesis work would not have been completed without his support and patience. Also, I would like to thank all the Project EPIC members I worked with—Mazin Hakeem, Reem Albaghli, Jennings Anderson, Afnan Meshal and Rsha Mirza—for welcoming me in the group and supporting me through my thesis. I would like to thank the directors of Project EPIC, Prof. Leysia Palen and Prof. Kenneth M. Anderson, who have provided me with this amazing opportunity to conduct my research in their group. I would like to thank my family for their support and encouragement on moving to the United States to work on this thesis. My college friends back in Barcelona for sharing with me probably the best four years of my life. And to my friends here in Boulder, for helping me integrate into this new environment and supporting me through this last six months.
vii Contents Abstract iii Acknowledgements v 1 Introduction 1 2 Background 3 2.1 ProjectEPIC .................................. 3 2.2 Containerization................................ 4 2.3 Container Orchestration Technologies . . . . . . . . . . . . . . . . . . . 4 2.4 Microservices Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . 5 2.4.1 Coreography ............................. 6 2.4.2 Orchestration ............................. 6 2.5 Messagingsystems .............................. 6 2.6 Big Data Storage Systems . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3 Problem Statement 9 4 Approach 11 4.1 CustomComponents............................. 12 5 Implementation 15 5.1 DeployingtheSystem ............................ 16 5.2 Front-EndComponents ........................... 16 6 Evaluation 19 6.1 Reliability ................................... 19 6.1.1 Current infrastructure . . . . . . . . . . . . . . . . . . . . . . . . 19 6.1.2 SystemPrototype........................... 20 6.2 Scalability ................................... 21 6.2.1 Current infrastructure . . . . . . . . . . . . . . . . . . . . . . . . 22 6.2.2 SystemPrototype........................... 22 6.3 Performance.................................. 23 6.4 Software development and maintenance . . . . . . . . . . . . . . . . . . 25 6.4.1 Current infrastructure . . . . . . . . . . . . . . . . . . . . . . . . 25 6.4.2 SystemPrototype........................... 25 7 Results 27 8 Related Work 29 9 Future Work 31 10 Conclusions 33
viii A Microservices code 35 A.1 TwitterTracker ................................ 35 A.1.1 twitter_tracker.go . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 A.2 TwitterNormalizer .............................. 38 A.2.1 model.py................................ 38 A.2.2 tweetparser.py ............................ 41 A.3 Infrastructure Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 A.3.1 start.py................................. 43 A.3.2 k8scontroller.py............................ 45 B Deploying microservices in Kubernetes 47 B.1 Dockerimage ................................. 47 B.2 Kubernetes deployment YAML file . . . . . . . . . . . . . . . . . . . . . 48
ix List of Figures 2.1 Project EPIC Software Infrastructure . . . . . . . . . . . . . . . . . . . . 4 4.1 Systemarchitecture.............................. 13 5.1 EventManagerUI............................... 17 5.2 Zeppelin visualization example . . . . . . . . . . . . . . . . . . . . . . . 18 6.1 Kubernets restarts in eleven days . . . . . . . . . . . . . . . . . . . . . . 21 6.2 Wordcounttimeplot ............................. 24
2Chapter 1. Introduction Systems can be split into small microservices and deployed across a cluster of machines; there is no need to merge components into a big monolithic application. Furthermore, cloud providers are adding support for container-orchestrated systems, making it straightforward to deploy complex infrastructures. Due to the similarities between different cloud offerings, one can design this new style of software system independent of a specific provider. One benefit to container-orchestrated systems is that it provides a means for finding new ways to solve problems associated with making use of parallelism and scaling a software system to handle ever increasing amounts of data. If properly designed, surges in demand can be met by spinning up additional copies of core system services balanced across the cluster of machines reserved from a cloud provider. The goal of my thesis is to explore how this new style of software architecture can be used to deploy software infrastructures that are used to perform big data analytics. As part of my thesis work, I migrate an existing big data infrastructure to make use of the techniques and technologies offered by container-orchestrated systems and compare the new version of the system with its previous incarnation along a number of dimensions.
3 2 Background Before digging into my specific project, I provide background information that will help to understand my problem domain. Here, I present information on three different topics: the first provides information on the big data software infrastructure that I use in my work; this infrastructure was developed by Project EPIC [2,16,3] to support research into an area known as crisis informatics [15,17]. I also present more information on container-orchestration technologies and then discuss microservice architectures in more depth. 2.1 Project EPIC Project EPIC (Empowering the Public with Information in Crisis) is a project at the University of Colorado Boulder. It conducts research on crisis informatics, an area of study that examines how members of the public make use of social media during times of mass emergency to make sense of a crisis event as well as to coordinate/- collaborate around the event. Project EPIC has a long history of performing software engineering research. Since 2009, Project EPIC has been investigating the software architectures, tools, and techniques needed to produce reliable and scalable data-intensive software systems, an area known as big data software engineering [1]. When large amounts of data are being collected, software engineers need to focus on structuring this data so it is easy to perform analysis and they must work to ensure that this data is easily accessible to analysts. Project EPIC’s big data software engineering research has explored these issues in depth during the creation of the Project EPIC software infrastructure that consists of two major components: EPIC Collect and EPIC Analyze. EPIC Collect is a 24/7 data collection system that connects to the Twitter Streaming API to collect tweets from various crisis events that need to be monitored in real time. Since 2012, this software has been collecting tweets with an uptime of 99% and has collected over two billion tweets across hundreds of crisis events. EPIC Collect’s storage layer makes use of Cassandra. This NoSQL database is focused on writes and provides high throughput. EPIC Analyze is a web-based system that makes use of a variety of software frameworks (e.g., Hadoop, Solr, and Redis) to provide various analysis and annotation services for analysts on the large data sets being collected by EPIC Collect. In addition, Project EPIC maintains one machine—known as EPIC Analytics—with a large amount of physical memory to allow analysts to run memory-intensive processes over the collected data. The software architecture of EPIC Collect and EPIC Analyze is shown in Figure 2.1. Note, this is a logical architecture that does not show how these systems are deployed. For instance, Cassandra is deployed on four machines that run separately from the machines that host the EPIC Collect software, Postgres, Redis, and the
4Chapter 2. Background DataStax Enterprise EPIC Event Editor EPIC Analyze Application Layer Service Layer Storage Layer Twitter Redis PostgreSQL Cassandra SolrPig Hadoop EPIC Collect FIGURE 2.1: Project EPIC Software Infrastructure Ruby-on-Rails code that makes up EPIC Analyze. In all, the existing Project EPIC infrastructure is distributed across seven machines in a single data center maintained at the University of Colorado Boulder. 2.2 Containerization Containerization is a technique that provides operating-system-level virtualization. This technology allows programs to be run inside a system container; these containers are isolated from each other as well as from the host machine that is being used to execute them. Containerization works like traditional virtual machines from the point of view of a program, but makes more efficient use of the system resources on the host machine instead of simulating a full-powered operating system. There are many containerization platforms available; however, the most widely adopted project is Docker; I will make use of Docker as part of the prototype I built for testing my thesis work. Docker originated as an internal tool for a PaaS (Platform as a Service) company and was later made available as open source. Thanks to many contributions from different companies, this project has grown to become the most used containerization software. It is able to run on almost any machine and many software packages have been made available as Docker containers, providing a wide range of integration opportunities. Finally, almost all existing container orchestration systems support Docker containers. 2.3 Container Orchestration Technologies As containerization technologies became more widely adopted—spurred by a recent migration to designing systems via microservices—large companies needed a way to manage their containers in a more friendly way. Interconnecting containers, managing their deployment, and scaling them to meet demand, were all possible, but were difficult to achieve. As a result, container orchestration systems were born.
2.4. Microservices Architecture 5 To manage containers, these systems add an abstraction layer over containerisation technologies, making such tasks easier to perform. There are a few container orchestration systems available at the moment. The most popular ones are Kubernetes and Apache Mesos.1In this project, I will make use of Kubernetes. The main reason for this is that—thanks to the open source community— it is easier to find tutorials and courses for Kubernetes. In addition, there are a lot of big companies backing this project and contributing to it; this activity provides evidence that this project will be supported well into the future. Google Cloud seems like the best fit to host Kubernetes as it has a managed cluster option that makes it straightforward to install and connect system components. In addition, thanks to Google being part of the maintenance team for Kubernetes, there is a great support for the Google Cloud infrastructure within Kubernetes. 2.4 Microservices Architecture Microservices is an approach to distributed systems that promote the use of small services with specific responsibilities that collaborate between them, rather than making use of big components with a lot of responsibilities that make interaction more difficult. They are thus more cohesive units of software with minimal dependencies between them. A system designed with loosely-coupled, highly-cohesive software components has always been a highly-desirable goal in software design [4] and microservices help to achieve that goal with distributed software systems. In addition, thanks to new technologies like containers and container-orchestrated systems, microservices are quickly becoming a standard tool in the design of large software systems. This type of software architecture has been adopted by many companies as it makes maintenance of these systems more straightforward. Another key advantage of the microservices approach is that it makes it easier to adopt different technologies for each component of your software system. In addition to containerization, it decouples different parts of a system. This separation allows for a better optimization of technology depending on the feature that each microservice needs to provide. For example, a microservice that needs to store highlyrelated data can make use of a graph database. At the same time, a separate microservice that needs to store and index large documents can use a document store underneath, allowing for a better fit with its needs while allowing both microservices to be deployed as part of a single software system. Having small microservices do specific tasks makes development cycles faster and more independent. It also makes incremental deployment much easier and less dangerous. Finally, microservices make it easier to scale software systems since one can individually scale parts of the system depending on their usage [6]. Microservices avoid problems associated with previous approaches to service-oriented architectures by focusing solely on the overall software architecture and letting the architect decide how services are to be deployed or what messaging system is used to communicate between them. In addition, a microservices architecture provides improved reliability and resilience, as each microservice is independent. If one fails, the rest are unaffected. This feature is a perfect match with container-orchestration 1https://kubernetes.io/ and http://mesos.apache.org/
6Chapter 2. Background systems that can easily perform health checks on microservices and redeploy any that have failed. In terms of designing a microservice architecture, there are two approaches that are equally used at the moment: choreography and orchestration [14]. 2.4.1 Coreography Choreography centers all interactions around a publish-subscribe communication model. Events are propagated through the system in an asynchronous manner. When something happens in a microservice, a message gets published on a public queue. Other microservices can subscribe to this queue and respond when they receive that message. This approach makes a system more flexible, removing the responsibility of knowing how to send messages to other microservices. One can add more components easily without having to modify existing ones. However, we need extra components to make sure that all tasks are performed once an event is published. We can accomplish this by installing and maintaining a monitoring solution. 2.4.2 Orchestration Orchestration imposes request/response interactions on microservices. Each microservice makes requests directly on other microservices. For this approach to work, one needs a service discovery mechanism. In addition, if a service is down, we need to make sure that microservices are architected to retry failed attempts and to fail gently if a required microservice is unavailable. The benefit to this approach is that, due to the synchronous nature of these interactions, we know that all steps of an activity have been completed when the original call returns. The limitation is that one non-responsive microservice can bring down an entire set of actions. A more modern approach to orchestration has been developed with service meshes [13]. A service mesh has the responsibility of providing service discovery while also balancing requests across multiple instances of a microservice; they also guard against having an activity fail by retrying requests. A service mesh works by adding a sidecar to all microservices allowing it to act as a proxy between a microservice and the outside network. Unfortunately, service meshes are still new technologies that are rapidly evolving; they often lack features found in other approaches such as the extensibility capabilities found in choreography-based systems. As a result, I do not make use of them in my thesis work. 2.5 Messaging systems Messaging systems organize queues of messages produced by microservices and notify subscribed components when they arrive. Their main objective is to decouple components and to serve as a cache if consumers cannot process all of the incoming messages. This allows for more reliable systems as a system does not depend on the mutual availability of a sender and a receiver to pass messages as they would if they used other messaging systems, such as HTTP.
2.6. Big Data Storage Systems 7 There are many options available in this space, with the most popular being Apache Kafka and RabbitMQ. Kafka is a decentralized, high-availability messaging system that allows one to publish messages organized by topics. It allows for high parallelizability thanks to the partitions on topics, which lets one read and write at a higher rate. Each partition can have one consumer associated with it providing faster reads. Another benefit of Kafka is its persistence system. Thanks to a strong integration with the kernel of the host operating system, it persists data faster than other systems. This is due to the fact that it gives the responsibility of flushing messages to disk to the kernel, taking advantage of optimizations like disk page caching and memory caching implemented in modern operating systems. In addition, Kafka is one of the most used messaging systems in the industry. Many companies use it in production to decouple their systems. Kafka has a strong community behind it as well, and large organizations (e.g. LinkedIn) take an active role in maintaining it. Messaging systems are needed for choreography microservice architectures as they serve as the communication layer between microservices. 2.6 Big Data Storage Systems For my thesis work, I will be collecting data from Twitter via the Streaming API. This API is limited to provide 1% of the total tweets generated in Twitter every minute. Based on a report from 2013, I know that rate is approximately 5700 tweets per second on average [11]. As a result, I can calculate the total number of tweets per second that I estimate will flow through my system prototype per second and that is approximately 57 tweets per second on average as a minimum bound. Since that corresponds to ˜ 4.9M tweets/day, I need a data storage technology that scales to handle large datasets. As previously studied in Project EPIC [16], I need to use a NoSQL database instead of a relational database to support the high volume of tweets that come from this API, making my system more scalable. On the other hand I also need a system that allows analytical and operational queries to happen at the same time. I would like to be able to analyze my data in real time without having to stop my data collection process. Given that some analysis tasks may take a few minutes due to the high number of tweets, I need to have a system that supports high throughput for both parts (collection and analsyis). In this case, Cassandra is an excellent option as the number of operations it can perform per second scales better compared to other NoSQL alternatives, especially with operational and analytical workloads.[7] To store tweets, I base my table structure on the current EPIC Analyze column family structure in Cassandra as described by the CQL code in Listing 2.1. I have added an index on the event_name attribute so that I can access events faster. I need this index as many queries are performed per event.
8Chapter 2. Background CREATE TABLE twitter_analytics .tweet ( id uuid , t_id text , event_kw text , event_name text , hashtags l i s t <text > , media_url text , t_coordinates text , t_cr eate d_at timestamp , t_fav o rite_c ount int , t_favorited boolean , t_geo text , t_is_a_retweet boolean , t_lang text , t_retweet_count int , t_retweeted boolean , t _ t e x t text , u_created_at timestamp , u_description text , u_favourites_count int , u_followers_count int , u_friends_count int , u_geo_enabled boolean , u_id text , u_lang text , u_listed_count int , u_location text , u_name text , u_screen_name text , u_statuses_count int , u_time_zone text , u_url text , u_utc_offset int , um_id text , um_name text , um_screen_name text , urls l i s t <text > , PRIMARY KEY ( id , t_ i d ) ) Listing 2.1 Tweets CQL table script
9 3 Problem Statement The goal of my thesis is to explore the benefits and limitations in using containerorchestration systems to build and deploy software systems that engage in big data analytics. To perform this exploration, I will be redesigning the Project EPIC software infrastructure as a set of microservices—each inside a separate Docker container— that are deployed on a cluster of cloud-based machines via a container-orchestration system. The current infrastructure was manually deployed on a set of physical machines in a local data center and was not developed using microservices or containerization. My hypothesis is that I’ll be able to achieve greater scalability and reliability with the new architecture with significantly reduced maintenance costs. I will also explore whether I am able to achieve greater query flexibility and overall performance using this new style of software infrastructure. My specific research questions are: 1. What advantages and/or limitations will the new Project EPIC infrastructure have with respect to its predecessor? (a) Is it more reliable? If so, why? (b) Is it more scalable? If so, why? 2. Does the new infrastructure have lower maintenance costs than the existing infrastructure? (a) Is it easier to deploy? (b) Is it easier to upgrade? (c) Is it more resilient to failures? If so, how?
11 4 Approach In this section, I present the design of my replacement for the Project EPIC infrastructure. The primary features of this infrastructure are: •Event management (creation/deletion/modification of events with specific keywords) •Real-time collection of streaming Twitter data •Real-time classification of incoming tweets (assigning tweets to active events) •Data Analysis (performing queries on collected tweets using batch processing) My goal is to recreate these features with less code and which is easier to deploy and update and is more flexible, scalable, and reliable than the existing infrastructure. As mentioned above, my design will rely on a choreography-based microservices approach that is deployed on a cloud-based infrastructure making use of Docker and Kubernetes. My microservices will rely on Kafka to pass messages to one another via message queues (topics) that are created in response to requests to collect on crisis events. One goal I have in my design is to make as many of my system components to be stateless. That is, these components will be designed to receive an incoming message from a Kafka queue that contains all the state they need to perform their operation. They will, in turn, generate messages that contain all the state that is needed for downstream components to process them. This design approach will pay dividends as it will allow the underlying container orchestration system to easily replace services that have crashed and to instantiate multiple copies of a particular service when there is a surge in demand for its services. Not all of my components will be microservices. I will rely on Cassandra to persist the tweets that are collected; the reasons for using Cassandra have already been well documented in Project EPIC’s prior work [2,16,3]. Furthermore, I will be making use of Apache Spark to perform data analytics in my prototype and will provide a web-based notebook user interface for the analysts to easily submit their queries and view the results. Examples of tools that provide notebook user interfaces for data analysis are Zeppelin and Project Jupyter.1These platforms integrate directly with Apache Spark and provide advanced features for viewing the results of Spark queries as tables and charts. The use of Apache Spark in my infrastructure was driven by the fact that it comes with a specialized Cassandra Connector that allows it to perform queries on a cluster of Cassandra nodes efficiently. For instance, the Cassandra connector is smart enough to “take the query to the data” and perform a particular query distributed on the data stored in each Cassandra node rather than requiring data to be transferred between nodes before the query is performed. This 1https://zeppelin.apache.org/ and http://jupyter.org/
18 Chapter 5. Implementation FIGURE 5.2: Zeppelin server with some visualization from the dataset
19 6 Evaluation In order to evaluate my work, I compare the architecture and implementation of my prototype with the existing Project EPIC infrastructure along the dimensions of reliability, scalability, performance, and real time delivery. 6.1 Reliability In order to evaluate my work, I compare the architecture and implementation of my prototype with the existing Project EPIC infrastructure along the dimensions of reliability, scalability, performance, and real-time delivery. 6.1.1 Current infrastructure Reliability of the existing EPIC infrastructure needs to be studied separately across EPIC Collect and EPIC Analyze. EPIC Collect is designed to be highly available. It is implemented as a multi-threaded Java application; some threads are used to read the incoming tweet stream, some are used to classify tweets, and some are used to monitor the other threads. If the monitoring threads detect that one of the readers is no longer producing tweets for the classifiers, it can issue a command that causes the current connection to the Twitter Streaming API to be dropped and all of these threads to be deactivated. This action, in turn, causes another thread to detect that the Twitter connection is down and it then restarts the connection which causes readers, classifiers, and monitors to once again be instantiated. This approach can ensure reliable performance for many days; however, sometimes errors occur that cause all threads to lock up. To handle this situation, EPIC Collect makes use of a cron job that wakes up once per minute to examine the current length of the EPIC Collect log file. Each reader and classifier will send information to the log file and when data collection is proceeding smoothly, the log file is always increasing in size. As a result, if the cron job wakes up and discovers that the log file has not increased in size over the past minute, it assumes that the collection software has locked up. It will invoke a command to kill the previously running process and it then invokes the collection system, notes the size of the log file, and goes back to sleep. With these techniques, EPIC Collect has achieved 99% uptime since the summer of 2012. The only problem that these techniques cannot account for is if the data center loses its network connection. When that happens, the cron job will be stuck in a cycle of terminating and restarting the software until the network connection is restored. Fortunately, complete loss of the data center’s connection to the Internet is a very rare event, happening only once in a four year period.
20 Chapter 6. Evaluation EPIC Analyze does not have the same level of reliability.In order for the web application to function, it requires that Redis and Solr be up and running. If these systems are not available, then the web application is non-functional. Compounding this situation is the fact that EPIC Analyze is deployed manually by its developers; there is no automated way to deploy it and there is no monitoring system detecting for system failure. As a result, there is also no automated recovery procedure. All aspects of the system deployment for EPIC Analyze require manual intervention by developers. 6.1.2 System Prototype In the case of my system prototype, overall reliability is high, due to the use of a container-orchestration system. Kubernetes provides two components to increase the reliability of our system. The first Kubernetes-provided component is the controller manager that runs on the master node of our cluster. This component is responsible for keeping track of all containers running on our cluster. It also follows the requests made by the infrastructure controller to ensure that the right number of replicas are created for the components that need them. For instance, in my prototype, I specify that there should be two replicas of a Kafka broker available at all times. If any of those replicas go down, Kubernetes will detect that and launch a new one. This functionality extends to all of our containers; if any container stops running, the controller manager detects it and schedules a new instance of that container to run on an available node. This check is performed when the infrastructure controller makes new requests or when an existing node informs the controller manager that one of its containers went down. The second Kubernetes-provided component is the scheduler. This component makes sure that new containers are scheduled on the best node possible. Kubernetes allows an engineer to configure the amount of memory and cpu permitted by a container; this information allows the scheduler to find the best fit for each deployment request. With these two components, Kubernetes automates the deployment of containers on a cluster of machines and handles any failures automatically. Its services are significantly more advanced than the existing reliability measures put into place by the Project EPIC developers, who were more interested (at the time) in system functionality and not in automated failure recovery mechanisms beyond what was done to ensure reliable data collection. Kubernetes provides one additional reliability-related feature and that is related to upgrading containers to provide new versions of the microservice within—this feature is called a rolling update. When performing an upgrade, the controller manager first deploys the new version of the component and ensures that it is up and running. It then removes the container containing the previous version of the component. I make use of this functionality with the Twitter Tracker component. When a new change to data collection is announced by the Event Manager, the infrastructure controller arranges to have a new instance of the Twitter Tracker component deployed with the new state. It starts to collect tweets using the newly updated keyword list while the previous instance is still collecting data on the prior set of keywords. This approach ensures that no tweets are missed when the transition occurs. Twitter applications can only have one standing connection. When the new
6.2. Scalability 21 FIGURE 6.1: Number of automated restarts by Kubernetes of the system prototype over a period of eleven days. instance establishes a connection, Twitter will close the old connection ensuring that there will not be any duplicated tweets stored in the transition. Figure 6.1 displays a typical report for the number of times the containers in our system prototype were restarted automatically by Kubernetes over a period of eleven days with no interaction from the user. The first thing to note is that all components remained active for the entire time period; that is data collection proceeded uninterrupted during those eleven days. However, due to system demands, Kubernetes may have found itself needing to, for instance, delete a container on an overloaded node and move it to a node that had more resources available. Given that my code is now fairly stable, if we increased the amount of memory on each node and added a few more nodes to our cluster, the total number of restarts would go down. But, given the limited resources I had during development, the more important issue is that despite limited resources, the system continued to run 24/7 with no interventions required by the developer. Note: that in Figure 6.1, some instances are listed as only existing for two days; this discrepancy is due to the fact that Kubernetes will restart a container’s count if it needs to do a hard restart of the container. This occurs when Kubernetes issues a request for the container to shut down and it stays active, ignoring the request. This might occur due to the contained microservice crashing inside and thus unable to exit gracefully. As a result, Kubernetes is forced to kill the container without a graceful shutdown. 6.2 Scalability The second dimension I am using for my evaluation is scalability. I am interested in how well both infrastructures deal with the ability to scale to large amounts of data. I want to avoid wasting system resources unnecessarily while having the capacity to scale and I want to understand how scaling impacts overall system performance.
22 Chapter 6. Evaluation 6.2.1 Current infrastructure Scalability with the existing infrastructure is not a straightforward process. With respect to throughput capacity, EPIC Collect would need a developer to manually launch a new instance with new Twitter credentials and set-up a second cron job to monitor the second instance’s log files. That work is feasible but not straightforward and would have to be performed anew if more capacity was needed and a third instance was required. This situation is one reason why EPIC Collect does not perform data normalization; it simply classifies tweets with respect to the current set of events and then it stores them in Cassandra. If data normalization was added to the existing EPIC Collect then it would struggle to handle spikes in incoming traffic as it would not be able to automatically scale its capacity to handle demand. With respect to storage capacity, EPIC Collect is in a better situation since it stores tweets to a four-node Cassandra cluster with terabytes of disk space available. If additional capacity is needed, a developer just needs to configure a new node and add it to the existing cluster. As with the discussion above concerning throughput capacity, while this works, it is hardly an automated approach to scaling the infrastructure on demand. With respect to EPIC Analyze, the only component that is a target for scaling, apart from storage, is the frontend module that is currently written in Ruby on Rails. To do that, multiple instances of the application would need to be launched and a load balancer put in front of those instances. To make this work, the existing web application would need to be refactored such that session state can be made consistent across all of the instances. That is a straightforward engineering task but not simple by any means. Furthermore, maintaining a load balancer is a complex process when done manually and, as discussed above, all maintenance on EPIC Analyze has to be performed manually. I conclude that the existing Project EPIC infrastructure is not easy to scale. 6.2.2 System Prototype Scaling my system prototype is much easier given the functionality gained from Kubernetes. When deploying a microservice via a container, I can specify how many replicas of that service I would like to deploy alongside it. The controller manager will try to schedule the requested number of replicas as long as there are enough system resources available across the cluster. Our ability to deploy multiple replicas is helped by the fact that most of our services were designed to be stateless. All of the state that a service needs to perform its task is contained in the messages that it receives. As a result, it does not matter which replica handles a given input message. Replicas can also be automatically triggered based on CPU usage. If a container hits 90% CPU utilization because it has experienced a spike in the number of input messages, Kubernetes can automatically spin up new replicas until the utilization goes down, due to the fact that the new replicas can help the existing component handle the spike in messages. While these services are largely automatic, a developer can always interact with Kubernetes directly to manually deploy additional components to help with scalability. The developer can issue these commands using the kubectl command line tool or via Kubernetes’s web interface.
6.3. Performance 23 val table =sc . cassandraTable ( " t w i t t e r _ a n a l y t i c s " , " tweet " ) val words =ta bl e . s e l e c t ( " t _ t e x t " ) . flatMap ( l => l . ge tSt ri ng ( " t _ t e x t " ) . s p l i t ( " " ) ) .map(word => (word . toLowerCase , 1 ) ) . reduceByKey ( _ + _ ) .map( _ . swap) . sortByKey( false ,1) Listing 6.1 WordCount Spark script Due to the features of container orchestration systems, my system prototype is much easier to scale than the existing Project EPIC infrastructure. 6.3 Performance I am unable to provide a comparison between the two infrastructures with respect to performance. Both systems have similar performance with respect to data collection but detailed tests and comparisons are not possible since EPIC Collect is a production system that other members of the Project EPIC team depend on for their research. As such, in this section, I provide insight into the performance my system prototype achieves on my small four-node cluster. As a reminder, each node in the cluster has access to one virtual CPU and four gigabytes of RAM. My test involves executing a Spark-based job on the cluster to count the number of words contained in all collected tweets. Each time I ran the query for the evaluation, the total number of tweets collected was different, increasing each time. I selected this particular test since word count is a highly parallelizable operation. It also demonstrates the integration of Spark into my system prototype. The code entered into Zeppelin is shown in Listing 6.1. The first line establishes a connection to Cassandra and creates a Spark Context object by which queries can be invoked. The second line expresses a series of transformations that Spark will apply to count all of the words of all tweets contained in Cassandra. It starts by selecting the text of the tweet, splitting the text into words, mapping each word into a pair (word, 1) and then reducing all such pairs by adding up the integers for each matching key. Thus all pairs like (cat, 1) would eventually turn into a single pair (cat, 1000) where 1000 represents the number of times that cat appears in the collected tweets. Finally, the pairs are inverted, e.g. (1000, cat), and then sorted in descending order. The power of Spark is that all of these transformations are applied to every tweet in parallel and, furthermore, as much of the transformations are applied locally on every node before any data is sent to the master node for the final combination of pairs across nodes. Spark provides a mechanism to reveal how it will execute a query known as the debug string. Each indentation in the debug string is a map stage, and each ‘+’ is a shuffle phase. As we can see in Listing 6.2, Spark delays shuffling data until it is time to execute the reduceByKey step. This makes sense since it can generate word pairs on each node without having to transfer data across nodes. However, once it needs to count the total number of words, it has to send data across nodes to a master node to create
24 Chapter 6. Evaluation ( 1 ) ShuffledRDD [1 12 ] at sortByKey at <console >: 31 [ ] +−(176) MapPartitionsRDD [ 1 11] at map at <console >: 31 [ ] | ShuffledRDD [110] at reduceByKey at <console >: 31 [ ] +−(176) MapPartitionsRDD [1 09] at map at <console >: 31 [ ] | MapPartitionsRDD [1 08] at flatMap at <console >: 31 [ ] | CassandraTableScanRDD [ 107] at RDD at CassandraRDD . sc a la :15 [ ] Listing 6.2 Debug string rdd FIGURE 6.2: Plot on wordcount time for dataset size the final counts. It then performs one more shuffle when it sorts the final key-value pairs after swapping them from this format (cat, 1000) to this format (1000, cat). As we can see in Figure 6.2, the word count performance is linear but with a flat slope at the beginning indicating that performance improved with larger numbers of tweets to analyze (see the increase in tweets processed per second in Table 6.1) and then increasing as the total size of the data set went past 2M tweets. The likely reason for this performance curve is that there is a certain amount of overhead that is incurred each time to stage the job and perform the shuffle steps at the end, counting up the pairs and sorting them. However, as the number of tweets increases, each individual node can do more work uninterrupted and can execute as quickly as possible without the need for coordination messages. As a result, the performance per tweet increases as the datasets get larger and this keeps performance acceptable.
6.4. Software development and maintenance 25 Number of tweets Time (s) Tweets/sec 490199 238 2060 1400884 469 2987 21680851 1107 19585 27199614 1500 18133 54395957 4228 12866 TABLE 6.1: Number of tweets in dataset and performance metrics 6.4 Software development and maintenance One of my goals was to develop a system that was easier to maintain. I accomplished this primarily through the use of microservices. The code associated with a microservice is small, making it easier for new developers to understand and maintain it. Furthermore, as was the case with several of our components, we wanted to make it straightforward for a developer to reimplement one of our components if there was a compelling reason to do so, such as poor performance. 6.4.1 Current infrastructure Currently the code for this infrastructure is split at a high-level into two separate, large and complex projects. This presents challenges to new developers on the Project EPIC team in terms of getting to know the code to a point where they feel confident they can contribute to it. The Ruby-on-Rails portion of EPIC Analyze has 5086 lines of code and is maintained in a git repository on GitHub. It is thus easy for multiple developers to work on it but it takes a lot of work to understand it. It relies heavily on Ruby-on-Rails conventions and that adds an extra layer of difficulty for developers unfamiliar with that framework. In addition, EPIC Analyze relies on the use of solr and redis, two middleware services that both have significant learning curves. EPIC Collect is likewise a large system, consisting of thousands of lines of Java code that rely heavily on the Spring Framework.1Learning that codebase is difficult, even for experienced developers, and requires a sophisticated understanding of a wide range of Java infrastructure: maven, jenkins, Tomcat, and more. Finally, it is difficult to debug changes to both systems: EPIC Analyze requires deploying multiple servers on multiple machines as does EPIC Collect and the latter has additional monitoring software that must be configured and maintained as well. The result is that the current Project EPIC infrastructure is difficult to maintain. 6.4.2 System Prototype My system prototype is divided into two main parts. The first part consists of the code for the various components, written in both Python and Go. The second part 1https://spring.io
26 Chapter 6. Evaluation consists of declarative configuration documents written in YAML that specify how to deploy the infrastructure into Kubernetes.2 •Twitter tracker (Go): 108 lines •Kubernetes controller (Python): 145 lines •Event manager (Python/Django): 2090 lines •Tweet normalizer (Python): 209 lines The largest component is the Event manager but that is not surprising as it requires all the code that is normally associated with a fully functioning web application. Otherwise, the code is fairly equally distributed among the various microservices. Each service is small and easy to understand. Different developers can work on each microservice and then those services can be linked via Kubernetes and Kafka. Furthermore, due to the use of Kafka, each microservice can be written in a different technology stack allowing us to choose the tools and languages best suited to each task. As long as the technologies that we select can be containerized, then the resulting microsevice can easily be deployed by Kubernetes. The YAML files consist of 3345 lines of declarations that knit all of the components together. Kubernetes currently requires developers to manually write and review each YAML file but developers are working on new tools that will reduce the need to generate them by hand. As a result, my system prototype has significantly reduced maintenance costs. It is straightforward to develop simple microservices and then the use of Docker, Google Cloud, and Kubernetes makes it much easier to deploy those services into a production environment that can be scaled on demand. 2Yet Another Markup Language
27 7 Results After comparing both the existing Project EPIC infrastructure and my system prototype, I am now going to reflect on possible answers to the questions proposed in chapter 3. My work suggests that Project EPIC should invest the effort to migrate its existing infrastructure to the new software architecture enabled by container-orchestration systems. While my prototype does not recreate all of the functionality of EPIC Collect and EPIC Analyze, I have been able to reconstruct the core aspects of these systems in approximately one semester of effort, using less code, and exceeding the existing infrastructure in terms of scalabilty, reliability, ease of configuration and deployment, and maintainability—all because of the benefits provided by containerization, container-orchestration systems, and microservices. Kubernetes provides many features that makes my prototype more scalable and reliable. Rather than having to rely on ad hoc monitoring approaches, system monitoring is built into Kubernetes and provides for a wide range of features: replicas, rolling updates, auto-scaling, etc. None of those features are available in the current Project EPIC infrastructure and would require significant refactoring to add. Furthermore, my approach to using stateless microservices provides me with flexiblity and scalability that Project EPIC’s current infrastructure cannot match. Lastly, by making use of Google Cloud, I am able to create clusters with a flexiblity that just is not possible with Project EPIC’s fixed set of machines in a traditional data center. Regarding mantainability, my prototype has several advantages. First, my use of microservices separates responsabilities into different components that are smaller in size than the stateful components found in the existing infrastructure. This size difference makes it easier for developers to engage in the maintenance of individual microservices without having to understand the whole system at once. This design, in turn, means that we do not need experts for the whole system; each microservice can be mantained independently. In addition, Kubernetes offers a platform to deploy microservices that provides a better separation between deployment infrastructure and application development. Developers do not need a system administrator to deploy their code; they just need to understand how containerization works. Once they have wrapped their microservice into a container, it can easily be deployed and plugged into all of the reliablity and scalability features that Kubernetes provides. Furthermore, Kubernetes is a platform that allows developers to build their own tools on top of it. Thanks to its open source community, some tools are already built and can be added into existing Kubernetes clusters with ease. For example, with respect to reliability, we can add monitoring tools into Kubernetes clusters in a straightforward way. The API exposes resource usage information allowing one to configure alerts if needed and the community has built packages of configuration files that help to deploy monitoring solutions with ease.
35 A Microservices code Attached here is a version of the code developed for some of the custom microservices discussed in chapter 4. The event manager UI is not included due to the extensivity of the codebase. A.1 Twitter Tracker A.1.1 twitter_tracker.go package main / / OAuth1 import ( " github . com/dghubble/oauth1 " " os " " bufio " "strings" " net/url " " gopkg . in/Shopify/sarama . v1 " " log " ) / / Line s e p a r a t o r fu nct io n , d e t e c t s new l i n e s func scanLines ( data [ ] byte , atEOF bool ) (advance int , token [ ] byte , err error ) { i f atEOF && len( data ) == 0 { return 0 , nil ,nil } i f i := s t ri n g s . Index ( string ( data ) , "\r\n" ) ; i >= 0 { / / We have a f u l l ’\ r\n ’ t e rm in at ed l i n e . return i + 2 , data [ 0 : i ] , nil } / / I f we ’ re at EOF, we have a f i n a l , non−te rm in at ed l i n e . Return i t . i f atEOF { return len ( data ) , dropCR( data ) , nil } / / Request more data . return 0 , nil ,nil } func dropCR ( data [ ] byte) [ ] byte { i f len ( data ) > 0 && data [ len( data ) −1] == ’\n ’ { return data [ 0 : len( data ) −1] } return data }
36 Appendix A. Microservices code func main ( ) { / / Get environment v a r i a b l e s var access_token = os . Getenv ( "ACCESS_TOKEN" ) var token_secret = os . Getenv ( "ACCESS_TOKEN_SECRET" ) var consumer_key = os . Getenv ( "CONSUMER_KEY" ) var consumer_secret = os . Getenv ( "CONSUMER_SECRET" ) var tokens = os . Getenv ( "TOKENS" ) var kafka_servers = s tr i ng s . S p l i t ( os . Getenv ( "KAFKA_SERVERS" ) , " , " ) / / Prepa re OAuth1 c l i e n t conf := oauth1 . NewConfig ( consumer_key , consumer_secret ) token := oauth1 . NewToken( access_token , t ok en _secre t ) c l i e n t := conf . Client ( oauth1 . NoContext , token ) v := url . Values { } v . Set ( " track " , tokens ) / / Get u rl f o r stream stream_url := " h tt ps :// stream . t w i t t e r . com/1.1/ s t a tu s e s/ f i l t e r . json ? " + v . Encode ( ) / / Connect to URL with POST resp , err := c l i e n t . Post ( stream_url , " a pplicatio n/json " , nil) i f err != nil { log . F a t a l f ( " Error while connecting to t w i t t e r : %s " , e rr ) panic ( err ) return } i f resp . StatusCode != 200 { log . F a t a l f ( " Error while connecting to tw itte r , st at us code returned : %d" , resp . StatusCode ) panic ( err ) return } / / C r ea te b u f f e r s ca nn er f o r r e q u e s t and s p l i t by custom f u n c t i o n scanner := bufio . NewScanner ( resp . Body ) scanner . S p l i t ( scanLines ) / / S t a r t asy nc ron ous k a f k a p ro du ce r producer , err := sarama . NewAsyncProducer ( kafka_servers , nil ) / / C los e produc er b e f o r e e x i t i n g program defer func ( ) { i f err := producer . Close ( ) ; err != nil { log . Fa ta ll n ( err ) } } ( ) i f err != nil { log . F a t a l f ( " Error while bootstrap ing Kafka producer : %s " , e rr ) panic ( err ) return } / / S ta r t s e p a r a t e t hr ead to t r a c k Kafka produced e r r o r s go func ( ) { for err := range producer . Errors ( ) { log . F a t a l f ( " Kafka e rror : %s " , er r ) / / Exit a p p l i c a t i o n i f any e r r or from Kafka / / F or ce Kubernetes t o r e c o v e r
A.1. Twitter Tracker 37 os . E xit ( 2 ) } } ( ) / / Main lo o p t o scan r e q u e s t . Only b r e a k s i f e r r o r from K afka . for scanner . Scan ( ) { tweet := scanner . Bytes ( ) i f len ( token ) == 0 { / / empty keep−alive continue } / / Send tweet to prod ucer producer . Input ( ) <−&sarama . ProducerMessage { Topic : " raw_tweets " , Key : nil , Value : sarama . StringEncoder ( tweet ) } log . Printf ( " Tweet received " ) } log . Pr intf ( "Closing" ) }
38 Appendix A. Microservices code A.2 Twitter Normalizer A.2.1 model.py #−∗− coding : utf −8−∗− from __future__ import unicode_literals import logging import os import socket import uuid from datetime import datetime import ujson from cassandra . c l u s t e r import Cluster from cassandra . cqlengine import columns , connection from cassandra . cqlengine . management import sync_table from cassandra . cqlengine . models import Model CASSANDRA_IPS = l i s t ( map( socket . gethostbyname , os . environ . get ( ’CASSANDRA_NODES’ , ’ 1 2 7 . 0 . 0 . 1 ’ ) . replace ( ’ ’ , ’ ’ ) . s p l i t ( ’ , ’ ) ) ) KEYSPACE = ’twitter_analytics ’ # Tweet model d e f i n i t i o n as Python C lass class Tweet ( Model ) : id = columns .UUID( primary_key=True , default=uuid . uuid4 ) event_name = columns . Text ( index=True ) t_id = columns . Text ( primary_key=True , clustering_order="DESC" ) event_kw = columns . Text ( ) t_cr eate d_at = columns . DateTime ( ) t _ t e x t = columns . Text ( ) t_retweet_count = columns . Integer ( ) t_fav o rite_c ount = columns . Integer ( ) t_geo = columns . Text ( ) t_coordinates = columns . Text ( ) t_ fa v or it ed = columns . Boolean ( ) t_retweeted = columns . Boolean ( ) t_is_a_re tweet = columns . Boolean ( ) t_lang = columns . Text ( ) u_id = columns . Text ( ) u_name = columns . Text ( ) u_screen_name = columns . Text ( ) u_location = columns . Text ( ) u_url = columns . Text ( ) u_lang = columns . Text ( ) u_description = columns . Text ( ) u_time_zone = columns . Text ( ) u_geo_enabled = columns . Boolean ( ) media_url = columns . Text ( ) um_screen_name = columns . Text ( ) um_name = columns . Text ( ) um_id = columns . Text ( ) u_followers_count = columns . Integer ( ) u_friends_count = columns . Integer ( ) u_listed_count = columns . Integer ( ) u_favourites_count = columns . Integer ( ) u_utc_ offset = columns . Integer ( ) u_statuses_count = columns . Integer ( ) u_created_at = columns . DateTime ( ) hashtags = columns . Li s t ( value_type=columns . Text )
A.2. Twitter Normalizer 39 urls = columns . L i s t ( value_type=columns . Text ) logging . info ( ’ Connecting to cassandra . . . ’ ) c l u s t e r = Clus ter (CASSANDRA_IPS) with c l u s t e r . connect ( ) as se ssio n : logging . info ( ’ Creating keyspace . . . ’ ) # Keyspace c r e a t i o n session . execute ( """ CREATE KEYSPACE IF NOT EXISTS %s WITH r e p l i c a t i o n = { ’ c l a s s ’ : ’ Si mp le St ra te gy ’ , ’ replication_factor ’: ’1’ } """ % KEYSPACE) # E s t a b l i s h co nn ec ti on with Cassandra c l u s t e r connection . setup (CASSANDRA_IPS, KEYSPACE, protocol_version =3) # Tab l e c r e a t i o n logging . info ( ’ Creating t a bl e . . . ’ ) sync_table ( Tweet ) def cr e a te _ d ic t ( event_key , event_kw , tweet ) : return { ’ id ’ : s t r ( uuid . uuid1 ( ) ) , ’ t_id ’ : tweet [ ’ i d _ st r ’ ] , ’ event_kw ’ : ’ , ’ . jo i n ( event_kw ) , ’ event_name ’ : event_key , ’ t _ cre ated _at ’ : datetime . strptime ( tweet [ ’ created_at ’ ] , ’%a %b % d %H:%M:%S +0000 %Y ’ ) . isoformat ( ) , ’ t _ t e x t ’ : tweet [ ’ t e xt ’ ] , ’ t_retweet_count ’ : tweet [ ’ retweet_count ’ ] , ’ t_ f avorit e_coun t ’ : tweet [ ’ favorite_count ’ ] , ’ t_geo ’ : s t r ( tweet [ ’ geo ’ ] ) , ’t_coordinates ’ : s t r ( tweet [ ’ coordinates ’ ] ) , ’ t _f av or it ed ’ : tweet [ ’ favorit e d ’ ] , ’ t_retweeted ’ : tweet [ ’ retweeted ’ ] , ’ t_ i s_a_retwee t ’ : ’ retweeted_status ’ in tweet , ’ t_lang ’ : tweet [ ’ lang ’ ] , ’ u_id ’ : tweet [ ’ user ’ ] [ ’ id _s tr ’ ] , ’u_name ’ : tweet [ ’ user ’ ] [ ’name ’ ] , ’ u_screen_name ’ : tweet [ ’ user ’ ] [ ’ screen_name ’ ] , ’ u_location ’ : tweet [ ’ user ’ ] [ ’ lo cat ion ’ ] , ’ u_url ’ : tweet [ ’ user ’ ] [ ’ url ’ ] , ’ u_lang ’ : tweet [ ’ user ’ ] [ ’ lang ’ ] , ’ u_description ’ : tweet [ ’ user ’ ] [ ’ description ’ ] , ’ u_time_zone ’ : tweet [ ’ user ’ ] [ ’ time_zone ’ ] , ’u_geo_enabled ’ : bool ( tweet [ ’ user ’ ] [ ’ geo_enabled ’ ] ) , ’ u_followers_count ’ : tweet [ ’ user ’ ] [ ’ followers_count ’ ] , ’ u_friends_count ’ : tweet [ ’ user ’ ] [ ’ friends_count ’ ] , ’ u_favourites_count ’ : tweet [ ’ user ’ ] [ ’ favourites_count ’ ] , ’ u_statuses_count ’ : tweet [ ’ user ’ ] [ ’ statuses_count ’ ] , ’ u_created_at ’ : datetime . strptime ( tweet [ ’ user ’ ] [ ’ created_at ’ ] , ’%a %b %d %H:%M:%S +0000 %Y ’ ) . isoformat ( ) , ’ hashtags ’ : l i s t (map(lambda h : h[ ’ te xt ’ ] , tweet [ ’ e n t i t i e s ’ ] [ ’ hashtags ’ ] ) ) , ’ urls ’ : l i s t (map(lambda url : url [ ’ url ’ ] , tweet [ ’ e n t i t i e s ’ ] [ ’ urls ’ ] ) ) , # Concat names with a sp ace s e p a r a t i o n ’ um_screen_name ’ : ’ ’ . j o i n (map(lambda um: s t r (um[ ’screen_name ’ ] ) , tweet [ ’ e n t i t i e s ’ ] [ ’ user_mentions ’ ] ) ) ,
40 Appendix A. Microservices code ’um_name ’ : ’ ’ . jo i n (map(lambda um: s t r (um[ ’name ’ ] ) , tweet [ ’ e n t i t i e s ’ ] [ ’ user_mentions ’ ] ) ) , ’um_id ’ : ’ ’ . j o in (map(lambda um: s t r (um[ ’ id _ s t r ’ ] ) , tweet [ ’ e n t i t i e s ’ ] [ ’ user_mentions ’ ] ) ) , ’ media_url ’ : ’ ’ . j o in (map(lambda m: s t r (m[ ’ media_url_https ’ ] ) , tweet [ ’ e n t i t i e s ’ ] [ ’ media ’ ] ) ) i f ’media ’ in tweet [ ’ e n t i t i e s ’ ] else None , } session = connection . session prep_query = session . prepare ( "INSERT INTO %s . tweet JSON ? " % KEYSPACE) def save_tweet ( tweet , event_key , event_kw ) : session . execute_async ( prep_query , [ ujson .dumps( cr e a te _ d ic t ( event_key , event_kw , tweet ) ) , ] )
A.2. Twitter Normalizer 41 A.2.2 tweetparser.py import logging import os import sys import ujson from confluent_kafka import Consumer , KafkaError , KafkaException EVENT_KEY = os . environ . get ( ’EVENT_KEY ’ , ’ ’ ) as se rt EVENT_KEY, ’ Event key must be sp ec if ie d as environment vari a ble ’ TOKENS = l i s t (filter(None, os . environ . get ( ’TOKENS’ , ’ ’ ) . s p l i t ( ’ , ’ ) ) ) a s se r t TOKENS, ’ Tokens can \ ’ t be empty ’ KAFKA_SERVER = os . environ . get ( ’KAFKA_SERVERS ’ , ’ loc al ho st :9092 ’ ) def main ( save ) : conf = { ’ bootstrap . servers ’ : KAFKA_SERVER, ’ group . id ’ : EVENT_KEY, ’ session . timeout . ms ’ : 6000 , ’ defaul t . topic . config ’ : { ’ auto . o f f s e t . r es et ’ : ’ smallest ’ } } # Cre at e Kafka consumer with s p e c i f i e d c o n f i g u r a t i o n c = Consumer(∗ ∗ conf) # Custom f u n c t i o n f o r a ssi gn me nt p r i n t i n g def print_assignment ( consumer , p a r t i t i o n s ) : logging . i nfo ( ’ Assignment : %s ’ % p a r t i t i o n s ) # S u bs cr ib e to t o p i c s c . subscribe ( [ ’ raw_tweets ’ , ] , on_assign=print_assignment ) msg_count = 0 while True : msg = c . poll ( ) i f msg is None : continue i f msg . er ro r ( ) : # Error or even t i f msg . error ( ) . code ( ) == KafkaError . _PARTITION_EOF : # End o f p a r t i t i o n even t logging . info ( ’%% %s [%d] reached end at o f f s e t %d ’ % ( msg . t op ic ( ) , msg . p a r t i t i o n ( ) , msg . o f f s e t ( ) ) ) elif msg . e rror ( ) : # Error raise KafkaException (msg . error ( ) ) else : tweet = None try : tweet = ujson . loads (msg . value ( ) ) except TypeError : logging . e rror ( " Message not json : %s " % msg . value ( ) ) continue except ValueError : logging . e rror ( " Message not json : %s " % msg . value ( ) ) continue # T wi tt er i n t e r n a l mess ages a r e d i s c a r d e d h e re i f ’ te x t ’ not in tweet : logging . info ( ’ I n t e rn al message : %s ’ % tweet )
42 Appendix A. Microservices code continue msg_count += 1 # Check i f tw ee t s hould be s t o r e d i f any (token in tweet [ ’ t e xt ’ ] for token in TOKENS) : logging . i nf o ( ’ Tweet accepted : %s:%d:%d : key=%s tweet_id =%s ’ % (msg . to pi c ( ) , msg . p a r t i t i o n ( ) , msg . o f f s e t ( ) , s t r (msg . key ( ) ) , tweet [ ’ id ’ ] ) ) save ( tweet , EVENT_KEY, TOKENS) # Read ines s w r it e on f i r s t message ( used by Kuber n e te s ) i f msg_count == 1: open ( ’/tmp/healthy ’ , ’ a ’ ) . c lo se ( ) i f __name__ == " __main__ " : logging . basicConfig ( format= ’%(asctime ) s .%( msecs ) s%(levelname ) s :%(message ) s ’ , l e v e l=logging . INFO ) import model logging . info ( ’ Event : %s ’ % EVENT_KEY) logging . info ( ’ Tracking keywords : %s ’ % ’ , ’ . jo i n (TOKENS) ) logging . info ( ’ Kafka servers : %s ’ % KAFKA_SERVER) logging . info ( ’ Connecting to Cassandra . . . ’ ) logging . i nf o ( ’ S t a r t stream tr ac k ’ ) i f not TOKENS: logging . e rr or ( ’ Tokens can \ ’ t be empty ’ ) main ( model . save_tweet )
A.3. Infrastructure Controller 43 A.3 Infrastructure Controller There’s also YAML templates to generate the deployments that are sent to Kubernetes. I don’t include them here. To check some sample YAML file see Appendix B A.3.1 start.py import json import logging import os from kafka import KafkaConsumer import k8scontroller bootstrap_servers = os . environ . get ( ’KAFKA_SERVERS ’ , ’ loc al ho st :9092 ’ ) . s p l i t ( ’ , ’ ) topic = os . environ . get ( ’KAFKA_TOPIC ’ , ’ events ’ ) TEST_TYPE = ’ t e s t ’ EVENT_TYPE = ’ event ’ QUERIES_TYPE = ’ queries ’ UPDATE_ACTION = ’ update ’ REFRESH_ACTION = ’ r efre sh ’ IGNORE_ACTION = ’ ignore ’ def main ( ) : consumer = KafkaConsumer ( topic , group_id= ’ k8scon troller −eventparser ’ , bootstrap_servers=bootstrap_servers , va lue _d es eri al iz er=lambda m: json . loads (m. decode ( ’ utf −8 ’ ) ) ) for message in consumer : value = message . value type_ = value [ ’ type ’ ] action = value [ ’ action ’ ] i f ( action == UPDATE_ACTION or action == REFRESH_ACTION) and type_ == EVENT_TYPE: data = value [ ’ data ’ ] try : i f data [ ’ tracking ’ ] and data [ ’ tokens ’ ] . replace ( ’ ’ , ’ ’ ) . replace ( ’ , ’ , ’ ’ ) : k8 sc on tr ol l e r . apply_eventparser ( data [ ’ code ’ ] , data [ ’ tokens ’ ] ) logging . info ( ’ Created event partser for event : %s ’ % data [ ’ code ’ ] ) except KeyError : logging . i nfo ( ’ Message received was not formatted c o r r e c t l y . Message :\n %s ’ % data ) elif ( action == UPDATE_ACTION or action == REFRESH_ACTION) and type_ == QUERIES_TYPE : tokens = value [ ’ data ’ ] try : k8 sc on tr ol l e r . update_queries ( tokens ) logging . i nf o ( ’ Updated t w i t t e r streaming with qu eries : % s ’ % tokens )
51 Bibliography [1] Kenneth M. Anderson. “Embrace the Challenges: Software Engineering in a Big Data World”. In: 1st International Workshop on Big Data Software Engineering, part of the 2015 International Conference on Software Engineering. 2015, pp. 19–25. [2] Kenneth M. Anderson and Aaron Schram. “Design and Implementation of a Data Analytics Infrastructure in Support of Crisis Informatics Research (NIER Track)”. In: Proceedings of the 33rd International Conference on Software Engineering. ICSE ’11. Waikiki, HI, USA: ACM, 2011, pp. 844–847. ISBN: 978-1-4503- 0445-0. DOI:10.1145/1985793.1985920.URL:http://doi.acm.org/ 10.1145/1985793.1985920. [3] Kenneth M. Anderson et al. “Design Challenges/Solutions for Environments Supporting the Analysis of Social Media Data in Crisis Informatics Research”. In: Proceedings of the 2015 48th Hawaii International Conference on System Sciences. HICSS ’15. Washington, DC, USA: IEEE Computer Society, 2015, pp. 163–172. ISBN: 978-1-4799-7367-5. DOI:10.1109/HICSS.2015.29.URL:http:// dx.doi.org/10.1109/HICSS.2015.29. [4] Grady Booch. Object-Oriented Analysis and Design with Applications (3rd Edition). Redwood City, CA, USA: Addison Wesley Longman Publishing Co., Inc., 2004. ISBN: 020189551X. [5] Cisco. Cisco Visual Networking Index: Forecast and Cisco Visual Networking Cisco Visual Networking Index: Forecast and Methodology, 2016–2021. Tech. rep. Cisco, 2017. URL:http://www.cisco.com/c/en/us/solutions/collateral/ serviceprovider / visualnetworking- index - vni /completewhite-paper-c11-481360.pdf. [6] N. Dragoni et al. “Microservices: How To Make Your Application Scale”. In: ArXiv e-prints (Feb. 2017). arXiv: 1702.07149 [cs.SE]. [7] EndPoint. Benchmarking Top NoSQL Databases: Apache Cassandra, Couchbase, HBase, and MongoDB. Tech. rep. EndPoint, 2015. [8] Raul Estrada and Isaac Ruiz. Big Data SMACK: A Guide to Apache Spark, Mesos, Akka, Cassandra, and Kafka. Apress, 2016. [9] Zirije Hasani, Margita Kon-Popovska, and Goran Velinov. “Lambda architecture for real time big data analytic”. In: ICT Innovations (2014). [10] Han Hu et al. “Toward scalable systems for big data analytics: A technology tutorial”. In: IEEE access 2 (2014), pp. 652–687. [11] Raffi Krikorian. New Tweets per Second Record, and How! URL:https://blog. twitter . com / engineering / en _ us / a / 2013 / new - tweets - per - second-record-and-how.html. [12] A MadhaviLatha and G Vijaya Kumar. “Streaming Data Analysis using Apache Cassandra and Zeppelin”. In: (). [13] William Morgan. What’s a service mesh? And why do I need one? | Buoyant | The Service Mesh Company. 2017. URL:https://buoyant.io/2017/04/25/ whats-a-service-mesh-and-why-do-i-need-one/.
52 BIBLIOGRAPHY [14] Sam Newman. Building Microservices. 1st. O’Reilly Media, Inc., 2015. ISBN: 1491950358, 9781491950357. [15] Leysia Palen et al. “Crisis in a Networked World”. In: Soc. Sci. Comput. Rev. 27.4 (Nov. 2009), pp. 467–480. ISSN: 0894-4393. DOI:10.1177/0894439309332302. URL:http://dx.doi.org/10.1177/0894439309332302. [16] Aaron Schram and Kenneth M. Anderson. “MySQL to NoSQL: Data Modeling Challenges in Supporting Scalability”. In: Proceedings of the 3rd Annual Conference on Systems, Programming, and Applications: Software for Humanity. SPLASH ’12. Tucson, Arizona, USA: ACM, 2012, pp. 191–202. ISBN: 978-1-4503-1563-0. DOI:10. 1145/2384716.2384773.URL:http://doi .acm.org/10. 1145/2384716.2384773. [17] Sarah Vieweg et al. “Microblogging During Two Natural Hazards Events: What Twitter May Contribute to Situational Awareness”. In: Proceedings of the SIGCHI Conference on Human Factors in Computing Systems. CHI ’10. Atlanta, Georgia, USA: ACM, 2010, pp. 1079–1088. ISBN: 978-1-60558-929-9. DOI:10 . 1145 / 1753326.1753486.URL:http://doi.acm.org/10.1145/1753326. 1753486.