|
|
Posted on: August 27, 2010
At dealnews we have three tiers of servers. First is our development servers, then staging and finally production. The complexity of the environment increases at each level. On a development server, everything runs on the localhost: mysql, memcached, etc. At the staging level, there is a dedicated MySQL server. In production, it gets quite wild with redundant services and two data centers.
One of the challenges of this is where and how to store the connection information for all these services. We have done several things in the past. The most common thing is to store this information in a PHP file. It may be per server or there could be one big file like:
if(DEV){
; ; ; ;$server = "localhost";
} else {
; ; ; ;$server = "10.1.1.25";
}
?>
This gets messy quickly. Option two is to deploy a single file that has the settings in a PHP array. And that is a good option. But, we have taken that one step further using some PHP ini trickeration. We use ini files that are loaded at PHP's startup and therefore the information is kept in PHP's memory at all times.
When compiling PHP, you can specify the --with-config-file-scan-dir to tell PHP to look in that directory for additional ini files. Any it finds will be parsed when PHP starts up. Some distros (Gentoo I know) use this for enabling/disabling PHP extensions via configuration. For our uses we put our custom configuration files in this directory. FWIW, you could just put the above settings into php.ini, but that is quite messy, IMO.
To get to this information, you can't use ini_get() as you might think. ; No, you have to use get_cfg_var() instead. get_cfg_var returns you the setting, in php.ini or any other .ini file when PHP was started. ini_get will only return values that are registered by an extension or the PHP core. Likewise, you can't use ini_set on these variables. Also, get_cfg_var will always reflect the initial value from the ini file and not anything changed with ini_set.
So, lets look at an example.
; ;db.ini
[myconfig]
myconfig.db.mydb.db ; ; ; ; ;= ;mydb
myconfig.db.mydb.user ; ; ;= ;user
myconfig.db.mydb.pass ; ; ;= ;pass
myconfig.db.mydb.server ;= ;host
This is our ini file. the group in the braces is just for looks. It has no impact on our usage. Because this is parsed along with the rest of our php.ini, it needs a unique namespace within the ini scope. That is what myconfig is for. We could have used a DSN style here, but it would have required more parsing in our PHP code.
/**
;* ;Creates ;a ;MySQLi ;instance ;using ;the ;settings ;from ;ini ;files
;*
;* ;@author ; ; ; ; ;Brian ;Moon ;
;* ;@copyright ; ;1997-Present ;dealnews.com, ;Inc.
;*
;*/
class ;MyDB ;{
; ; ; ;/**
; ; ; ; ;* ;Namespace ;for ;my ;settings ;in ;the ;ini ;file
; ; ; ; ;*/
; ; ; ;const ;INI_NAMESPACE ;= ;"dealnews";
; ; ; ;/**
; ; ; ; ;* ;Creates ;a ;MySQLi ;instance ;using ;the ;settings ;from ;ini ;files
; ; ; ; ;*
; ; ; ; ;* ;@param ; ; ;string ; ;$group ; ;The ;group ;of ;settings ;to ;load.
; ; ; ; ;* ;@return ; ;object
; ; ; ; ;*
; ; ; ; ;*/
; ; ; ;public ;static ;function ;init($group) ;{
; ; ; ; ; ; ; ;static ;$dbs ;= ;array();
; ; ; ; ; ; ; ;if(!is_string($group)) ;{
; ; ; ; ; ; ; ; ; ; ; ;throw ;new ;Exception("Invalid ;group ;requested");
; ; ; ; ; ; ; ;}
; ; ; ; ; ; ; ;if(empty($dbs["group"])){
; ; ; ; ; ; ; ; ; ; ; ;$prefix ;= ;MyDB::INI_NAMESPACE.".db.$group";
; ; ; ; ; ; ; ; ; ; ; ;$db ; ; ;= ;get_cfg_var("$prefix.db");
; ; ; ; ; ; ; ; ; ; ; ;$host ;= ;get_cfg_var("$prefix.server");
; ; ; ; ; ; ; ; ; ; ; ;$user ;= ;get_cfg_var("$prefix.user");
; ; ; ; ; ; ; ; ; ; ; ;$pass ;= ;get_cfg_var("$prefix.pass");
; ; ; ; ; ; ; ; ; ; ; ;$port ;= ;get_cfg_var("$prefix.port");
; ; ; ; ; ; ; ; ; ; ; ;if(empty($port)){
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;$port ;= ;null;
; ; ; ; ; ; ; ; ; ; ; ;}
; ; ; ; ; ; ; ; ; ; ; ;$sock ;= ;get_cfg_var("$prefix.socket");
; ; ; ; ; ; ; ; ; ; ; ;if(empty($sock)){
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;$sock ;= ;null;
; ; ; ; ; ; ; ; ; ; ; ;}
; ; ; ; ; ; ; ; ; ; ; ;$dbs[$group] ;= ;new ;MySQLi($host, ;$user, ;$pass, ;$db, ;$port, ;$sock);
; ; ; ; ; ; ; ; ; ; ; ;if(!$dbs[$group] ;|| ;$dbs[$group]->connect_errno){
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;throw ;new ;Exception("Invalid ;MySQL ;parameters ;for ;$group");
; ; ; ; ; ; ; ; ; ; ; ;}
; ; ; ; ; ; ; ;}
; ; ; ; ; ; ; ;return ;$dbs[$group];
; ; ; ;}
}
?>
We can now call DB::init("myconfig") and get a mysqli object that is connected to the database we want. No file IO was needed to load these settings except when the PHP process started initially. ; They are truly constant and will not change while this process is running.
Once this was working, we created separate ini files for our different datacenters. That is now simply configuration information just like routing or networking configuration. No more worrying in code about where we are.
We extended this to all our services like memcached, gearman or whatever. We keep all our configuration in one file rather than having lots of them. It just makes administration easier. For us it is not an issue as each location has a unique setting, but every server in that location will have the same configuration.
Here is a more real example of how we set up our files.
[myconfig.db]
myconfig.db.db1.db ; ; ; ; ; ; ; ; ;= ;db1
myconfig.db.db1.server ; ; ; ; ;= ;db1hostname
myconfig.db.db1.user ; ; ; ; ; ; ;= ;db1username
myconfig.db.db1.pass ; ; ; ; ; ; ;= ;db1password
myconfig.db.db2.db ; ; ; ; ; ; ; ; ;= ;db2
myconfig.db.db2.server ; ; ; ; ;= ;db2hostname
myconfig.db.db2.user ; ; ; ; ; ; ;= ;db2username
myconfig.db.db2.pass ; ; ; ; ; ; ;= ;db2password
[myconfig.memcache]
myconfig.memcache.app.servers ; ; ; ;= ;10.1.20.1,10.1.20.2,10.1.20.3
myconfig.memcache.proxy.servers ; ;= ;10.1.20.4,10.1.20.5,10.1.20.6
[myconfig.gearman]
myconfig.gearman.workload1.servers ;= ;10.1.20.20
myconfig.gearman.workload2.servers ;= ;10.1.20.21
http://brian.moonspot.net/using-ini-files-for-php-application-settings
Post Link
|
|
|
Posted on: August 18, 2010
I am back home from a good week at the 2010 O'Reilly MySQL Conference & Expo. I had a great time and got to see some old friends I had not seen in a while.
Oracle gave the opening keynote and it went pretty much like I thought it would. Oracle said they will keep MySQL alive. They talked about the new 5.5 release. It was pretty much the same keynote Sun gave last year. Time will tell what Oracle does with MySQL.
The expo hall was sparse. Really sparse. There were a fraction of the booths compared to the past. I don't know why the vendors did not come. Maybe because they don't want to compete with Oracle/Sun? In the past you would see HP or Intel have a booth at the conference. But, with Oracle/Sun owning MySQL, why even try. Or maybe they are not allowed? I don't know. It was just sad.
I did stop by the Maatkit booth and was embarrassed to tell Baron (its creator) I was not already using it. I had heard people talk about it in the past, but never stopped to see what it does. It would have only saved me hours and hours of work over the last few years. Needless to say it is now being installed on our servers. If you use MySQL, just go install Maatkit now and start using it. Don't be like me. Don't wait for years, writing the same code over and over to do simple maintenance tasks.
Gearman had a good deal of coverage at the conference. There were three talks and a BoF. All were well attended. Some people seemed to have an AHA! moment where they saw how Gearman could help their architecture. I also got to sit down with the PECL/gearman maintainers and discuss the recent bug I found that is keeping me from using it.
I spoke about Memcached as did others. Again, there was a BoF. It was well attended and people had good questions about it. There seemed to be some FUD going around that memcached is somehow inefficient or not keeping up with technology. However, I have yet to see numbers or anything that proves any of this. They are just wild claims by people that have something to sell. Everyone wants to be the caching company since there is no "Memcached, Inc.". There is no company in charge. That is a good thing, IMO.
That brings me to my favorite topic for the conference, Drizzle. I wrote about Drizzle here on this blog when it was first announced. At the time MySQL looked like it was moving forward at a good pace. So, I had said that it would only replace MySQL in one part of our stack. However, after what, in my opinion, has been a lack of real change in MySQL, I think I may have changed my mind. Brian Aker echoed this sentiment in his keynote address about Drizzle. He talked about how MySQL AB and later Sun had stopped focusing on the things that made MySQL popular and started trying to be a cheap version of Oracle. That is my interpretation of what he said, not his words.
Why is Drizzle different? Like Memcached and Gearman, there is no "Drizzle, Inc.". It is an Open Source project that is supported by the community. It is being supported by companies like Rackspace who hired five developers to work on it. The code is kept on Launchpad and is completely open. Anyone can create a branch and work on the code. If your patches are good, they will be merged into the main branch. But, you can keep your own branch going if you want to. Unlike the other forks, Drizzle has started over in both the code and the community. I personally see it as the only way forward. It is not ready today, but my money is on Drizzle five or ten years from now.
http://brian.moonspot.net/mysql-conference-review
Post Link
|
|
|
Posted on: August 17, 2010
My coworker Rob ran into an issue building the PECL/memcache
extension on his Mac. ; He did
find the solution however. ; You can read and leave
comments on his blog.
http://brian.moonspot.net/pecl-memcache-mac-osx
Post Link
|
|
|
Posted on: August 12, 2010
First there was LAMP. ;
But are you using GLAMMP? ; You have probably not heard of it
because we just coined the term while chatting at work. ; You
know LAMP (Linux, Apache, MySQL and PHP or Perl and sometimes
Python). So, what are the extra letters for?
The G is for Gearman - Gearman is a system to farm out work
to other machines, dispatching function calls to machines that are
better suited to do work, to do work in parallel, to load balance
lots of function calls, or to call functions between languages.
The extra M is for Memcached - memcached is a
high-performance, distributed memory object caching system, generic
in nature, but intended for use in speeding up dynamic web
applications by alleviating database load.
More and more these days, you can't run a web site on just
LAMP. ; You need these extra tools (or ones like them) to do
all the cool things you want to do. ; What other tools do we
need to work into the acronym? ; PostgreSQL replaces MySQL in lots
of stacks to form LAPP. ; I guess Drizzle may replace MySQL in some stacks
soon. ; For us, it will likely be added to the
stack. ; Will that make it GLAMMPD? ; We need more
vowels! ; If you are starting the next must use tool for
running web sites on open source software, please use a vowel for
the first letter.
http://brian.moonspot.net/using-the-glammp-stack
Post Link
|
|
|
Posted on: August 09, 2010
I was reading a post by Dathan Vance Pattishall titled "Cassandra is my NoSQL solution but..". In the post, Dathan explains that he uses Cassandra to store clicks because it can write a lot faster than MySQL. However, he runs into problems with the read speed when he needs to get a range of data back from Cassandra. This is the number one problem I have with NoSQL solutions.
SQL is really good at retrieving a set of data based on a key or range of keys. Whereas NoSQL products are really good at writing things and retrieving one item from storage. When looking at redoing our architecture a few years ago to be more scalable, I had to consider these two issues. For what it is worth, the NoSQL market was not nearly as mature as it is now. So, my choices were much more limited. In the end, we decided to stick with MySQL. It turns out that a primary or unique key lookup on a MySQL/InnoDB table is really fast. It is sort of like having a key/value storage system. And, I can still do range based queries against it.
But, back to Dathan's problem: clicks. We store clicks at dealnews. Lots of clicks. We also store views. We store more views than we do clicks. So, lots of views and lots of clicks. (Sorry for the vague numbers, company secrets and all. We are a top 1,000 Compete.com site during peak shopping season.) And we do it all in MySQL. And we do it all with one server. I should disclose we are deploying a
second server, but it is more for high availability than processing
power. Like Dathan, we only use about the last 24 hours of data at any given time. There are three keys for us doing logging like this in MySQL.
Use MyISAM
MyISAM supports concurrent inserts. Concurrent inserts means that inserts can add rows to the end of a table while selects are being performed on other parts of the data set. This is exactly the use case for our logging. There are caveats with range queries as pointed out by the MySQL Performance Blog.
Rotating tables
MySQL (and InnoDB in particular) really sucks at deleting rows. Like, really sucks. Deleting causes locks. Bleh. So, we never delete rows from our logging tables. Instead, nightly we rotate the tables. RENAME TABLE is an (near) atomic process in MySQL. So, we just create a new table.
create table clicks_new like clicks; rename table clicks to clicks_2010032500001, clicks_new to clicks;
Tada! We now have an empty table for today's clicks. We now drop any table with a date stamp that is longer than x days old. Drops are fast, we like drops.
For querying these tables, we use UNION. It works really well. We just issue a SHOW TABLES LIKE 'clicks%' and union the query across all the tables. Works like a charm.
Gearman
So, I get a lot of flack at work for my outright lust for Gearman. It is my new duct tape. When you have a scalability problem, there is a good chance you can solve it with Gearman. So, how does this help with logging to MySQL? Well, sometimes, MySQL can become backed up with inserts. It happens to the best of us. So, instead of letting that pile up in our web requests, we let it pile up in Gearman. Instead of having our web scripts write to MySQL directly, we have them fire Gearman background jobs with the logging data in them. The Gearman workers can then write to the MySQL server when it is available. Under normal operating procedure, that is in near real time. But, if the MySQL server does get backed up, the jobs just queue up in Gearman and are processed when the MySQL server is available.
BONUS! Insert Delayed
This is our old trick before we used Gearman. MySQL (MyISAM) has a neat feature where you can have inserts delayed until the table is available. The query is sent to the MySQL server and it answers with success immediately to the client. This means your web script can continue on and not get blocked waiting for the insert. But, MySQL will only queue up so many before it starts erroring out. So, it is not as fool proof as a job processing system like Gearman.
Summary
To log with MySQL:
- Use MyISAM with concurrent inserts
- Rotate tables daily and use UNION to query
- Use delayed inserts with MySQL or a job processing agent like Gearman
Happy logging!
PS: You may be asking, "Brian, what about Partitioned Tables?" I asked myself that before deploying this solution. More importantly, in IRC I asked Brian Aker about MySQL partitioned tables. I am paraphrasing, but he said that if I ever think I might alter that table, I would not trust it with the partitions in MySQL. So, that kind of turned me off of them.
http://brian.moonspot.net/logging-with-mysql
Post Link
|
|
|
Posted on: August 06, 2010
I have started seriously using PHP 5.3 recently due to it finally making it into Portage. (Gentoo really isn't full of bleeding edge packages people.) I have used mysqlnd a little here and there in the past, but until it was really coming to my servers I did not put too much time into it.
What is mysqlnd?
mysqlnd is short for MySQL Native Driver. In short, it is a driver for MySQL for PHP that uses internal functions of the PHP engine rather than using the externally linked libmysqlclient that has been used in the past. There are two reasons for this. The first reason is licensing. MySQL is a GPL project. The GPL and the PHP License don't play well together. The second is better memory management and hopefully more performance. Being a performance junky, this is what peaked my interests. Enabling mysqlnd means it is used by the older MySQL extension, the newer MySQLi extension and the MySQL PDO driver.
New Key Feature - fetch_all
One new feature of mysqlnd was the fetch_all method on MySQLi Result objects. At both dealnews.com and in Phorum I have written a function to simply run a query and fetch all the results into an array and return it. It is a common operation when writing API or ORM layers. mysqlnd introduces a native fetch_all method that does this all in the extension. No PHP code needed. PDO already offers a fetchAll method, but PDO comes with a little more overhead than the native extensions and I have been using mysql functions for 14 years. I am very happy using them.
Store Result vs. Use Result
I have spoken in the past (see my slides and interview: MySQL Tips and Tricks) about using mysql_unbuffered_query or using mysqli_query with the MYSQLI_USE_RESULT flag. Without going into a whole post about that topic, it basically allows you to stream the results from MySQL back into your PHP code rather than having them buffered in memory. In the case of libmysqlclient, they could be buffered twice. So, my natural thought was that using MYSQLI_USE_RESULT with fetch_all would yield the most awesome performance ever. The data would not be buffered and it would get put into a PHP array in C instead of native code. The code I had hoped to use would look like:$res = $db->query($sql, MYSQLI_USE_RESULT); $rows = $res->fetch_all(MYSQLI_ASSOC);
But, I quickly found out that this does not work. For some reason, this is not supported. fetch_all only works with the default which is MYSQLI_STORE_RESULT. I filed a bug which was marked bogus. Which I put back to new because I really don't see a reason this should not work other than a complete oversight by the mysqlnd developers. So, I started doing some tests in hopes I could show the developers how much faster using MYSQLI_USE_RESULT could be. What happened next was not expected. I ended up benchmarking several different options for fetching all the rows of a result into an array.
Test Data
I tested using PHP 5.3.3 and MySQL 5.1.44 using InnoDB tables. For test data I made a table that has one varchar(255) column. I filled that table with 30k rows of random lengths between 10 and 255 characters. I then selected all rows and fetched them using 4 different methods.
- mysqli_result::fetch_all*
- PDOStatement::fetchAll
- mysqli_query with MYSQLI_STORE_RESULT followed by a loop
- mysqli_query with MYSQLI_USE_RESULT followed by a loop
In addition, I ran this test with mysqlnd enabled and disabled. For mysqli_result::fetch_all, only mysqlnd was tested as it is only available with mysqlnd. I ran each test 6 times and threw out the worst and best result for each test. FWIW, the best and worst did not show any major deviation for any of the tests. For measuring memory usage, I read the VmRSS value from Linux's /proc data. memory_get_usage() does not show the hidden memory used by libmysqlclient and does not seem to show all the memory used by mysqlnd either.

So, that is what I found. The memory usage graphs are all what I thought they would be. PDO has more overhead by its nature. Storing the result always uses more memory than using it. mysqli_result::fetch_all uses less memory than the loop, but more than directly using the results.
There are some very surprising things in the timing graphs however. First, the tried and true method of using the result followed by a loop is clearly still the right choice in libmysqlclient. However, it is a horrible choice for mysqlnd. I don't really see why this is so. It is nearly twice as slow. There is something really, really wrong with MYSQLI_USE_RESULT in mysqlnd. There is no reason it should ever be slower than storing the result and then reading it again. This is also evidenced in the poor performance of PDO (since even PDO uses mysqlnd when enabled). PDO uses an unbuffered query for its fetchAll method and it too got slower. It is noticably slower than libmysqlclient. The good news I guess is that if you are using mysqlnd, the fetch_all method is the best option for getting all the data back.
Next Steps
My next steps from here will be to find some real workloads that I can test this on. Phorum has several places where I can apply real world pages loads to these different methods and see how they perform. Perhaps the test data is too small. Perhaps the number of columns would have a different effect. I am not sure.
If you are reading this and have worked on or looked at the mysqlnd code and can explain any of it, please feel free to comment.
http://brian.moonspot.net/php-5-3-mysqlnd
Post Link
|
|
|
Posted on: August 05, 2010
I was telling someone how we roll changes to production at dealnews and they seemed really amazed by it. I have never really thought it was that impressive. It just made sense. It has kind of happened organically here over the years. Anyhow, I thought I would share.
Version Control
So, to start with, everything is in SVN. PHP code, Apache configs, DNS and even the scripts we use to deploy code. That is huge. We even have a misc directory in SVN where we put any useful scripts we
use on our laptops for managing our code base. Everyone can share that
way. Everyone can see what changed when. We can roll things back, branch if we need to, etc. I don't know how anyone lives with out. We did way back when. It was bad. People were stepping on each other. It was a mess. We quickly decided it did not work.
For our PHP code, we have trunk and a production branch. There are also a couple of developers (me) that like to have their own branch because they break things for weeks at a time. But, everything goes into trunk from my branch before going into production. We have a PHP script that can merge from a developer branch into trunk with conflict resolution assistance built in. It is also capable of merging changes from trunk back into a branch. Once it is in trunk we use our staging environment to put it into production.
Staging/Testing
Everything has a staging point. For our PHP code, it is a set of test staging servers in our home office that have a checkout of the production branch. To roll code, the developer working on the project logs in via ssh to a staging server as a restricted user and uses a tool we created that is similar to the Python based svnmerge.py. Ours is written in PHP and tailored for our directory structure and roll out procedures. It also runs php -l on all .php and .html files as a last check for any errors. Once the merge is clean, the developer(s) use the staging servers just as they would our public web site. The database on the staging server is updated nightly from production. It is as close to a production view of our site as you can get without being on production. Assuming the application performs as expected, the developer uses the merge tool to commit the changes to the production branch. They then use the production staging servers to deploy.
Rolling to Production
For deploying code and hands on configuration changes into our production systems, we have a staging server in our primary data center. The developer (that is key IMO) logs in to the production staging servers, as a restricted user, and uses our Makefile to update the checkout and rsync the changes to the servers. Each different configuration environment has an accompanying nodes file that lists the servers that are to receive code from the checkout. This ensures that code is rolled to servers in the correct order. If an application server gets new markup before the supporting CSS or images are loaded onto the CDN source servers, you can get an ugly page. The Makefile is also capable of copying files to a single node. We will often do this for big changes. We can remove a node from service, check code out to it, and via VPN access that server directly to review how the changes worked.
For some services (cron, syslog, ssh, snmp and ntp) we use Puppet to manage configuration and to ensure the packages are installed. Puppet and Gentoo get along great. If someone mistakenly uninstalls cron, Puppet will put it back for us. (I don't know how that could happen, but ya never know). We hope to deploy more and more Puppet as we get comfortable with it.
Keeping Everyone in the Loop
Having everyone know what is going on is important. To do that, we start with Trac for ticketing. Secondly, we use OpenFire XMPP server throughout the company. The devops team has a channel that everyone is in all day. When someone rolls code to production, the scripts mentioned above that sync code out to the servers sends a message via an XMPP bot that we wrote using Ruby (Ruby has the best multi-user chat libraries for XMPP). It interfaces with Trac via HTTP and tells everyone what changesets were just rolled and who committed them. So, in 5 minutes if something breaks, we can go back and look at what just rolled.
In addition to bots telling us things, there is a cultural requirement. Often before a big roll out, we will discuss it in chat. That is the part than can not be scripted or programmed. You have to get your developers and operations talking to each other about things.
Final Thoughts
There are some subtle concepts in this post that may not be clear. One is that the code that is written on a development server is the exact same code that is used on a production server. It is not massaged in any way. Things like database server names, passwords, etc. are all kept in configuration files on each node. They are tailored for the data center that server lives in. Another I want to point out again is that the person that wrote the code is responsible all the way through to production. While at first this may make some developers nervous, it eventually gives them a sense of ownership. Of course, we don't hire someone off the street and give them that access. ; But it is expected that all developers will have that responsibility eventually.
http://brian.moonspot.net/devops-dealnews
Post Link
|
|
|
Posted on: August 02, 2010
I was helping someone in IRC deal with some "headers already sent" issues and told them to use ob_start. Very diligently, the person went looking for why that was the right answer. He did not find a good explination. I looked around and I did not either. So, here is why this happens and why ob_start can fix it.
How HTTP works
HTTP is the communication protocol that happens between your web server and the user's browser. ; Without too much detail, this is broken into two pieces of data: headers and the body. ; The body is the HTML you send. But, before the body is sent, the HTTP headers are sent. Here is an example of an HTTP request response including headers:
HTTP/1.1 200 OK Date: Fri, 29 Jan 2010 15:30:34 GMT Server: Apache X-Powered-By: PHP/5.2.12-pl0-gentoo Set-Cookie: WCSESSID=xxxxxxxxxxxxxxxxxxxxxxxxxxxx; expires=Sun, 28-Feb-2010 15:30:34 GMT; path=/ Content-Encoding: gzip Vary: Accept-Encoding Keep-Alive: timeout=15, max=99 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: text/html; charset=UTF-8
Ramblings of a web guy . .
So, all those lines before the HTML starts have to come first. HTTP headers are where things like cookies and redirection occur. When a PHP script starts to send HTML out to the browser, the headers are stopped and the body begins. When your code tries to set a cookie after this has started, you get the "headers already sent" error message.
How ob_start works
So, how does ob_start help? The ob in ob_start stands for output buffering. ob_start will buffer the output (HTML) until the page is completely done. Once the page is completely done, the headers are sent and then the output is sent. This means any calls to setcookie or the header function will not cause an error and will be sent to the browser properly. You do need to call ob_start before any output occurs. If you start output, it is too late.
The down side
The down side of doing this is that the output is buffered and sent all at once. That means that the time between the user request and the time the first byte gets back to the user is longer than it has to be. However, in modern PHP application design, this is often already the case. An MVC framework for example would do all the data gathering before any presentation is done. So, your application may not have any issue with this.
Another down side is that you (or someone) could get lazy and start throwing setcookie calls in any old place. This should be avoided. It is simply not good programming design. In a perfect world, we would not need output buffering to solve this problem for us.
http://brian.moonspot.net/php-ob-start-headers
Post Link
|
|
|
Posted on: August 01, 2010
There are a bunch of scripting language sessions at the Oracle
Develop and JavaOne parts of Oracle OpenWorld extravaganza. This starts
on Sunday 19 September 2010 at various locations in San Francisco.
The easiest way to explore sessions is to go to the Content Catalog,
click Advanced Search, and use the Free Text field to enter keywords
your interested in e.g. PHP
Conference Sessions
S316995 Developing, Deploying, and Diagnosing Applications on Oracle Database 11g
Monday 10:00, Hotel Nikko, Golden Gate
S313963 Script Bowl 2010: A Scripting Languages Shoot-out (Clojure, Groovy, JRuby, and Scala)
Monday 10:00 Hilton, Continental Parlor 1/2/3
S319119 Fast Web Applications Development with Ruby on Rails on Oracle
Monday 2:30, Hotel Nikko, Golden Gate
S317002 Best Practices for Building High-Performance Applications with Oracle Database
Tuesday 11:30, Hotel Nikko, Nikko Ballroom I
S312989 Comparing Groovy and JRuby
Tuesday 11:30, Parc 55, Divisidero
S314094 Speedy Scripting: Productivity and Performance (Scala and JavaFX vs JRuby, Jython, and Groovy)
Tuesday 1:00, Parc 55, Divisidero
S317007 PHP, Python, Ruby, and Perl in Enterprises: Advanced Tips for Agile Development
Tuesday 2:30, Hotel Nikko, Golden Gate
S319181 Oracle Develop Keynote: What's New in Oracle Database Application Development
Tuesday 4:00, Hilton, Grand Ballroom AB
S317400 Improving the Scalability and Availability of PHP/Python/Ruby Web Applications
Wednesday 4:45, Hotel Nikko, Nikko Ballroom II
Hands-On Lab Sessions
S313507 Hands-on JRuby: Making Your Job Easy
Monday 10:00, Parc 55, Embarcadero
S318543 Develop a PHP Web Application with Oracle Database 11g in One Hour
Wednesday 4:45, Hilton, Franciscan A/B/C/D
S318547 Develop a Python/Django Web Application with Oracle Database 11g in One Hour
Thursday 11:00, Hilton, Franciscan A/B/C/D
S318545 Develop a Ruby on Rails Web Application with Oracle Database 11g in One Hour
Thursday 12:30, Hilton, Franciscan A/B/C/D
S318572 Develop Enterprise Apps in PHP, Python, or Ruby, and Scale with Oracle Tuxedo
Thursday 3:30, Hilton, Franciscan A/B/C/D
Keep an eye on the schedule for any last minute changes.
Exhibition Hall
The Exhibition hall will be open Monday, Tuesday and Wednesday.
I'll be at the scripting languages booth in the database area. It's
worth checking out the TimesTen, Berkeley DB, Tuxedo and NetBeans teams
too.
http://blogs.oracle.com/opal/2010/07/interesting_sessions_at_the_or.html
Post Link
|
|
|
Posted on: July 29, 2010
I spoke at CodeWorks in
Atlanta, GA this week. ; I totally dropped the ball promoting
it on my blog. ; It was a neat venue. ; Rather than a large
conference they are doing a traveling show. ; Seven cities in
14 days. ; Many of the presenters are working in every
city. ; Crazy. ; I was just in Atlanta. ; It is close
to home and easy for me to get to.
I spoke about memcached. ; I tried
to dig a bit deeper into how memcached works. ; On the mailing
list we get a lot of new people that make assumptions about
memcached. ; Most talks I have seen focus on why caching is
good, how to use memcached, the performance gain. ; I kind of
assumed everyone knew that stuff already. ; I guess you could
say I gave a talk that was the real FAQs of the project.
Here are the slides. ; Derick Rethans took video of the
talk. ; When he gets that online I will add it to this
post.
http://brian.moonspot.net/what-is-memcached
Post Link
|
|
|
Posted on: July 29, 2010
We use PHP everywhere in our stack. For us, it makes sense because
we have hired a great staff of PHP developers. So, we leverage that
talent by using PHP everywhere we can.
One place where people seem to stumble with PHP is with long
running PHP processes or parallel processing. The pcntl extension gives you the
ability to fork PHP processes and run lots of children like
many other unix daemons might. We use this for various things.
Most notably, we use it run Gearman worker processes. While at
the OReilly Open Sourc Convention in 2009, we were asked about
how we pulled this off. So, we are releasing the two scripts
that handle the forking and some instructions on how we use
them.
This is not a detailed post about long running PHP
scripts. ; Maybe I can get to the dos and don'ts of that
another time. ; But, these are the scripts we use to manage
long running processes. ; They work great for us on
Linux. ; They will not run on Windows at all. ; We also
never had any trouble running them on Mac OS X.
The first script, prefork.php, is for forking a given function
from a given file and running n children that will
execute that function. There can be a startup function that is
run before any forking begins and a shutdown function to run
when all the children have died.
The second script, prefork_class.php, uses a class with defined
methods instead of relying on the command line for function
names. This script has the added benefit of having functions
that can be run just before each fork and after each fork. This
allows the parent process to farm work out to each child by
changing the variables that will be present when the child
starts up. This is the script we use for managing our Gearman
workers. We have a class that controls how many workers are
started and what functions they provide. I may release a
generic class that does that soon. Right now it is tied to our
code library structure pretty tightly.
We have also included two examples. They are simple, but do
work to show you how the scripts work.
You can download the code from the dealnews.com developers'
page. UPDATE: I have released a Gearman Worker Manager on Github.
http://brian.moonspot.net/php-fork
Post Link
|
|
|
Posted on: July 27, 2010
The latest package of Wordcraft, the
PHP/MySQL based blog software that runs this site, is available for
download
from Google Code. ; Just some minor bug fixes and cosmetic
stuff. ; Its getting a little use in the wild. ; That is
always fun to see.
http://brian.moonspot.net/wordcraft-0-10-available
Post Link
|
|
|
Posted on: July 21, 2010
Amy Hoy has written a blog post about why forums are crap.
And she is right. Forum software does not always do a good job of
helping people communicate. I have worked with Amy. She did a great
analysis of dealnews.com that
led to our new design. So, she is not to be ignored.
However, as a software developer (Phorum), I see a lot of problems and
no answers. ; And it is not all on the software. ; Web site
owners use forums to solve problems that they really, really suck
at. ; Ideally, every web site would be very unique for their
audience. ; They would use a custom solution that fits a number
of patterns that best solves their problem. ; However, most web
site owners don't want to take the time to do such things. ;
They want a one stop, drop in solution. See the monolith that is
vBulletin, scary.
And what if a forum is the best solution? Well, software
developers, in general, are not good designers. They don't think
like normal people. And they don't see their applications as a
whole, but as pieces that do jobs. The forum software market has
been run by software developers for over 10 years. Most of them all
are still copies of what UBB was 13 years
ago. And software (like Phorum) that has tried to be different is
shunned by the online communities of the world because they don't
work/look/feel like every other forum software on the planet.
So, as software developers, what are we to do? We want to make
great software. We want to help our users help their users. But,
what we have been doing for 10+ years has only been adequate. As
the leader of an open source forum software project, I am open to
any and all ideas.
http://brian.moonspot.net/forums-are-crap-help-us
Post Link
|
|
|
Posted on: July 09, 2010
Memcached is the de facto standard for caching in dynamic web sites. PHP is the one of the most widely used languages on the web. So, naturally there is lots of interest in using the two together. There are two choices for using memcached with PHP: PECL/memcache and PECL/memcached.
Great names huh? But as of this writing there are issues with the two most popular Memcached libraries for PHP. This is a summary of those issues that I hope will help people being hurt by them and may bring about some change.
PECL/memcache
This is the older of the two and was the first C based extension for using memcached with PHP. Before this all the options were native PHP code. While they worked, they were slower of course. C > PHP. That is just fact. However, there has not been much active development on this code in some time. Yes, they have fixed bugs, but support for new features in the memcached server have not been added to this extension. Newer version of the server suppot a more efficient binary protocol and many new features. In addition, there are some parts of the extension that simply don't work anymore.
The most glaring one is the delete() function. It takes a second parameter that is documented as: "the item will expire after
timeout seconds". In fact that was never a feature of memcached. It was completely misunderstood by the original extension authors. When that parameter was supported, it locked the key for timeout seconds and would not allow a new add operation on that key. Second, this feature was completely removed in memcached 1.4.0. So, if you send a timeout to the delete function, you simply get a failure. This is creating a huge support issue in the memcached community (not the PHP/PECL community) with people not being able to delete keys because of bad documentation and unsupported behavior. I sent a documentation patch for the this function to the PHP Docs list. I then modified it based on feedback. But since I have heard nothing about it getting merged. I have a PHP svn account, but even if I do have karma on the docs repository, I don't want to hijack them without the support of the people that work on the docs all the time. If you are reading this and can change the docs, please make the documentation for that function say "DON'T USE THIS PARAMETER, IT HAS BEEN DEPRECATED IN THE MEMCACHED SERVER!" or something.
Not too long ago the extension was officially abandoned by its original maintainers. Some people stepped up and claimed they wanted to see it continue. But, since that time, there have been no releases. There are bugs being closed though so maybe there is good things coming.
A very problematic issue with this extension is with the 3.0 beta release. It needs to just die. It has huge bugs that, IMO, were introduced by the previous maintainers in an effort to bring it up to speed, but never saw them through to make sure the new code worked. In their defense, it is marked as beta on PECL. But, thanks to Google, people don't see the word beta anymore. There are lots of people using this version and when they get bad results they blame the whole memcached world. Really, the new maintainers would do the world a favor if they just removed the 3.x releases from the PECL site.
PECL/memcached
This extension was started by Andrei Zmievski while working at Digg.com as an open source developer. It uses libmemcached, a C++ memcached library that does all the memcached work. This made it quite easy to support the new features in the memcached daemon as it as it was being developed at the same time as the new server. However, it has not had a stable release on PECL in nearly a year except for release to make it compatible with new versions of libmemcached. No bug fixes and no new features. There are currently 28 open bugs on PECL for this extension. Not all of which are bugs. Some are feature requests. The ironic thing is that the GitHub repository for this extension has seen a lot of development. But, none of these bug fixes have made it into the official PECL channel. And some of these bugs are major and others are just huge WTF for a developer.
The most major bug is one that I found. If you use persistent connections with this extension, it basically leaks those connections, not reusing an existing connection but also not closing the ones already made. This uses up the memory in your processes until they crash and it creates an exponential number of connections to your memcached server until it has no more connections available. Andrei does report in the bug that it is fixed in hist GitHub. But, for now, you can't use persistent connections.
The big WTF for a developer is that some functions don't take a numeric key and use it properly. $mc = new Memcached();
$mc->addServer("localhost", 11211);
$mc->set(123, "yes!");
var_dump($mc->getMulti(array(123)));
?> The above code should generate:array(1) { ; [123]=> ; string(4) "yes!" }But, in reality, it generates:bool(false) The set succeeds, but the getMulti fails. Again, this is being fixed in GitHub, but is not available for release on PECL.
Compatibility
One big issue with these two extensions is that they are not drop in replacements for each other. If you want to move from one to the other, you have to take into consideration some time to convert your code. For instance, the older extension's set() function takes flags as the third parameter. The newer extension does not take a flags parameter at all. The older uses get() with an array to do a multi-get and the newer extension has a separate method for that called getMulti(). There are others as well.
Summary
So, what should you do as a PHP developer? If you are deploying memcached today, I would use the 2.2.x branch of PECL/memcache. It is the most stable. Just avoid the delete bug. It is not as fast and does not have the features. But, it is very reliable for set, get, add.... the basics of memcached. For the long term, it is a bit unclear. PECL/memcached looks to fix a lot of things in 2.0. But, I have not used it yet. In addition the long term growth of the project is a bit in question. Will there be a 2.1, 2.2, etc? I hope so. The other unknown is if the those people fixing the PECL/memcache bugs will keep it up and release a good stable product that supports new features of the server. Again, I hope so. The best scenario would be to have a choice between two fully compatible and feature rich extensions. Keep your fingers crossed.
http://brian.moonspot.net/php-memcached-issues
Post Link
|
|
TagCloud: Know U'r TWEAK
GUI
blogger
&
web server
Blog
CGI
??????
Explorer
Java
ATL
php
Perl
????
VBRecent Posts
What Should CEOs Do Differently? Generating Complex Events from a Partitioned Stream How Will Google Instant Affect Your Company's SEO? Apple Relaxes Restrictions on Mobile App Development Amazon Upgrades Checkout, Plays Catch-up with Google, PayPal For Advertisers, Location-Based Services "Blew Up Overnight" Google launches 'Instant' search Police in 14 Countries Raid File-Sharing Hosts And Hit Close to Wikileaks Call 911? Maybe not from a cell phone Bahraini Blogger Arrested, Probably Tortured
Categories
Web Technologies
Archives
September 2010
August 2010
July 2010
June 2010
May 2010
Sponsors
Partners
|